diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/ParameterUtil.java b/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/ParameterUtil.java index f84f29bf..3105377d 100644 --- a/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/ParameterUtil.java +++ b/de.gebit.integrity.dsl/src/de/gebit/integrity/utils/ParameterUtil.java @@ -1,678 +1,679 @@ package de.gebit.integrity.utils; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.math.BigInteger; import java.text.DateFormat; import java.text.ParseException; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import de.gebit.integrity.dsl.BooleanValue; import de.gebit.integrity.dsl.DateAndTimeValue; import de.gebit.integrity.dsl.DateValue; import de.gebit.integrity.dsl.DecimalValue; import de.gebit.integrity.dsl.EnumValue; import de.gebit.integrity.dsl.IntegerValue; import de.gebit.integrity.dsl.NullValue; import de.gebit.integrity.dsl.Operation; import de.gebit.integrity.dsl.StringValue; import de.gebit.integrity.dsl.TimeValue; import de.gebit.integrity.dsl.Value; import de.gebit.integrity.dsl.ValueOrEnumValueOrOperation; import de.gebit.integrity.dsl.ValueOrEnumValueOrOperationCollection; import de.gebit.integrity.dsl.Variable; import de.gebit.integrity.dsl.VariableEntity; import de.gebit.integrity.operations.OperationWrapper; import de.gebit.integrity.operations.OperationWrapper.UnexecutableException; /** * A utility class for handling of test/call parameters. * * @author Rene Schneider * */ public final class ParameterUtil { /** * Instantiates a new parameter util. */ private ParameterUtil() { // nothing to do } /** * The "fake" name of the default parameter. This is used for unnamed parameters in maps which require a non-null * key. */ public static final String DEFAULT_PARAMETER_NAME = ""; /** * Converts a given Java type value to a given Java type class, if possible. * * @param aParamType * the target type * @param aValue * the value * @return the converted value */ public static Object convertValueToParamType(Class<?> aParamType, Object aValue) { if (aParamType.isArray()) { Class<?> tempActualParamType = aParamType.getComponentType(); Object tempResultArray; if (aValue.getClass().isArray()) { // both are arrays tempResultArray = Array.newInstance(tempActualParamType, Array.getLength(aValue)); for (int i = 0; i < Array.getLength(aValue); i++) { Array.set(tempResultArray, i, convertSingleValueToParamType(tempActualParamType, Array.get(aValue, i))); } } else { // target is an array, but value is a single value tempResultArray = Array.newInstance(tempActualParamType, 1); Array.set(tempResultArray, 0, convertSingleValueToParamType(tempActualParamType, aValue)); } return tempResultArray; } else { // target is a single value if (aValue.getClass().isArray()) { // this is not convertible, but since this method does not guarantee any conversion... return aValue; } else { return convertSingleValueToParamType(aParamType, aValue); } } } /** * Convert a given single Java type value to param type (which is also a Java type). * * @param aParamType * the param type * @param aValue * the value * @return the object */ private static Object convertSingleValueToParamType(Class<?> aParamType, Object aValue) { if (aValue instanceof Number) { if (aParamType == Integer.class) { return aValue; } else if (aParamType == Long.class) { return ((Number) aValue).longValue(); } else if (aParamType == Short.class) { return ((Number) aValue).shortValue(); } else if (aParamType == Byte.class) { return ((Number) aValue).byteValue(); } else if (aParamType == BigInteger.class) { return BigInteger.valueOf(((Number) aValue).longValue()); } else if (aParamType == BigDecimal.class) { if (aValue instanceof Integer) { return new BigDecimal((Integer) aValue); } else if (aValue instanceof Long) { return new BigDecimal((Long) aValue); } else if (aValue instanceof Short) { return new BigDecimal((Short) aValue); } else if (aValue instanceof Byte) { return new BigDecimal((Byte) aValue); } else if (aValue instanceof Float) { return new BigDecimal((Float) aValue); } else if (aValue instanceof Double) { return new BigDecimal((Double) aValue); } else if (aValue instanceof BigInteger) { return new BigDecimal((BigInteger) aValue); } } else if (aParamType == Float.class) { return ((Number) aValue).floatValue(); } else if (aParamType == Double.class) { return ((Number) aValue).doubleValue(); } else if (aParamType == String.class) { return aValue.toString(); } } else if (aValue instanceof String) { if (aParamType == Integer.class) { return Integer.parseInt((String) aValue); } else if (aParamType == Long.class) { return Long.parseLong((String) aValue); } else if (aParamType == Short.class) { return Short.parseShort((String) aValue); } else if (aParamType == Byte.class) { return Byte.parseByte((String) aValue); } else if (aParamType == Float.class) { return Float.parseFloat((String) aValue); } else if (aParamType == Double.class) { return Double.parseDouble((String) aValue); } else if (aParamType == BigDecimal.class) { return new BigDecimal((String) aValue); } else if (aParamType == BigInteger.class) { return new BigInteger((String) aValue); } } else if (aValue instanceof Boolean) { if (aParamType == String.class) { return aValue.toString(); } } return aValue; } /** * Converts a given parameter value to a given Java type class, if possible. * * @param aParamType * the target type * @param aValue * the value * @param aVariableMap * the variable map, if variable references shall be resolved. If this is null, unresolved variable * references given as values will provoke an exception! * @return the converted value * @throws UnresolvableVariableException * the unresolvable variable exception * @throws ClassNotFoundException * @throws InstantiationException * @throws UnexecutableException */ public static Object convertEncapsulatedValueToParamType(Class<?> aParamType, ValueOrEnumValueOrOperation aValue, Map<VariableEntity, Object> aVariableMap, ClassLoader aClassLoader) throws UnresolvableVariableException, ClassNotFoundException, UnexecutableException, InstantiationException { if (aValue == null) { return null; } if (aValue instanceof Operation) { if (aClassLoader == null) { // cannot execute operations without the ability to load them return null; } else { OperationWrapper tempWrapper = new OperationWrapper((Operation) aValue, aClassLoader); Object tempResult = tempWrapper.executeOperation(aVariableMap, false); return convertValueToParamType(aParamType, tempResult); } } else if (aValue instanceof DecimalValue) { if (aParamType == Float.class) { return ((DecimalValue) aValue).getDecimalValue().floatValue(); } else if (aParamType == Double.class) { return ((DecimalValue) aValue).getDecimalValue().doubleValue(); } else if (aParamType == BigDecimal.class) { return ((DecimalValue) aValue).getDecimalValue(); } else if (aParamType == String.class) { return ((DecimalValue) aValue).getDecimalValue().toString(); } } else if (aValue instanceof IntegerValue) { if (aParamType == Integer.class) { return ((IntegerValue) aValue).getIntegerValue().intValue(); } else if (aParamType == Short.class) { return ((IntegerValue) aValue).getIntegerValue().shortValue(); } else if (aParamType == Byte.class) { return ((IntegerValue) aValue).getIntegerValue().byteValue(); } else if (aParamType == Long.class) { return ((IntegerValue) aValue).getIntegerValue().longValue(); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((IntegerValue) aValue).getIntegerValue(), 0); } else if (aParamType == BigInteger.class) { return ((IntegerValue) aValue).getIntegerValue(); } else if (aParamType == Float.class) { return ((IntegerValue) aValue).getIntegerValue().floatValue(); } else if (aParamType == Double.class) { return ((IntegerValue) aValue).getIntegerValue().doubleValue(); } else if (aParamType == String.class) { return Integer.toString(((IntegerValue) aValue).getIntegerValue().intValue()); } } else if (aValue instanceof NullValue) { return null; } else if (aValue instanceof StringValue) { if (aParamType == String.class) { return ((StringValue) aValue).getStringValue(); } else { try { if (aParamType == Integer.class) { return Integer.parseInt(((StringValue) aValue).getStringValue()); } else if (aParamType == Short.class) { return Short.parseShort(((StringValue) aValue).getStringValue()); } else if (aParamType == Byte.class) { return Byte.parseByte(((StringValue) aValue).getStringValue()); } else if (aParamType == Long.class) { return Long.parseLong(((StringValue) aValue).getStringValue()); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((StringValue) aValue).getStringValue()); } else if (aParamType == BigInteger.class) { return new BigInteger(((StringValue) aValue).getStringValue()); } else if (aParamType == Float.class) { return Float.parseFloat(((StringValue) aValue).getStringValue()); } else if (aParamType == Double.class) { return Double.parseDouble(((StringValue) aValue).getStringValue()); } else if (aParamType == Boolean.class) { return Boolean.parseBoolean(((StringValue) aValue).getStringValue()); } } catch (NumberFormatException exc) { throw new IllegalArgumentException("String value '" + ((StringValue) aValue).getStringValue() + "'" + " is not autoconvertible to parameter type " + aParamType); } } } else if (aValue instanceof EnumValue) { if (Enum.class.isAssignableFrom(aParamType)) { for (Object tempConstant : aParamType.getEnumConstants()) { if (tempConstant.toString().equals(((EnumValue) aValue).getEnumValue().getSimpleName())) { return tempConstant; } } } } else if (aValue instanceof Variable) { if (aVariableMap != null) { Object tempActualValue = aVariableMap.get(((Variable) aValue).getName()); if (tempActualValue != null) { if (tempActualValue instanceof Value) { return convertEncapsulatedValueToParamType(aParamType, (Value) tempActualValue, aVariableMap, aClassLoader); } else { return convertValueToParamType(aParamType, tempActualValue); } } else { return null; } } else { throw new UnresolvableVariableException("Unresolved variable " + ((Variable) aValue).getName().getName() + " encountered, but missing variable to value map!"); } } else if (aValue instanceof BooleanValue) { if (aParamType == Boolean.class) { return Boolean.valueOf(((BooleanValue) aValue).getBooleanValue()); } else if (aParamType == String.class) { return ((BooleanValue) aValue).getBooleanValue(); } } else if (aValue instanceof DateValue) { if (aParamType == Date.class) { return guardedDateConversion((DateValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateConversion((DateValue) aValue); } else if (aParamType == String.class) { - return DateFormat.getDateInstance(DateFormat.LONG).format(guardedDateConversion((DateValue) aValue)); + return DateFormat.getDateInstance(DateFormat.LONG).format( + guardedDateConversion((DateValue) aValue).getTime()); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof TimeValue) { if (aParamType == Date.class) { return guardedTimeConversion((TimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedTimeConversion((TimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getTimeInstance(DateFormat.LONG).format(guardedTimeConversion((TimeValue) aValue)); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof DateAndTimeValue) { if (aParamType == Date.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format( guardedDateAndTimeConversion((DateAndTimeValue) aValue)); } else { throw new IllegalArgumentException("Date/Time value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else { throw new UnsupportedOperationException("Value " + aValue.getClass() + " is unsupported"); } throw new IllegalArgumentException("Value " + aValue.getClass() + " is incompatible with parameter type " + aParamType); } /** * Converts a given value to a String. * * @param aValue * the value (can be an {@link OperationOrValueCollection} or a plain Java Object) * @param aVariableMap * the variable map, if variable references as values shall be resolved. If this is null, unresolved * variable references will always return either the string "(null)" or a null value, depending on the * following flag * @param aClassLoader * the classloader to use in order to resolve operations. If not given, operations will be "resolved" to * the string "UNSUPPORTED". * @param anAllowNullResultFlag * whether a null value shall be returned in case of unresolvable variable references or operations * @return the string */ public static String convertValueToString(Object aValue, Map<VariableEntity, Object> aVariableMap, ClassLoader aClassLoader, boolean anAllowNullResultFlag) { if (aValue instanceof Operation) { if (aClassLoader == null) { return anAllowNullResultFlag ? null : "UNSUPPORTED"; } else { Object tempResult = null; try { OperationWrapper tempWrapper = new OperationWrapper((Operation) aValue, aClassLoader); tempResult = tempWrapper.executeOperation(aVariableMap, false); } catch (ClassNotFoundException exc) { return anAllowNullResultFlag ? null : "FAILURE"; } catch (UnexecutableException exc) { return anAllowNullResultFlag ? null : "FAILURE"; } catch (InstantiationException exc) { return anAllowNullResultFlag ? null : "FAILURE"; } if (tempResult != null && tempResult.getClass().isArray()) { StringBuilder tempBuilder = new StringBuilder(); for (int i = 0; i < Array.getLength(tempResult); i++) { if (i > 0) { tempBuilder.append(", "); } tempBuilder.append(convertValueToString(Array.get(tempResult, i), aVariableMap, aClassLoader, anAllowNullResultFlag)); } return tempBuilder.toString(); } else { return convertValueToString(tempResult, aVariableMap, aClassLoader, anAllowNullResultFlag); } } } else if (aValue instanceof ValueOrEnumValueOrOperationCollection) { ValueOrEnumValueOrOperationCollection tempValueCollection = (ValueOrEnumValueOrOperationCollection) aValue; if (tempValueCollection.getMoreValues().size() == 0) { return convertValueToString(tempValueCollection.getValue(), aVariableMap, aClassLoader, anAllowNullResultFlag); } else { StringBuilder tempBuilder = new StringBuilder(); for (int i = 0; i < tempValueCollection.getMoreValues().size() + 1; i++) { if (i > 0) { tempBuilder.append(", "); } tempBuilder.append(convertValueToString(i == 0 ? tempValueCollection.getValue() : tempValueCollection.getMoreValues().get(i - 1), aVariableMap, aClassLoader, anAllowNullResultFlag)); } return tempBuilder.toString(); } } else if (aValue != null && aValue.getClass().isArray()) { // this is basically the same as above, but the collection has already been "merged" into an array StringBuilder tempBuilder = new StringBuilder(); for (int i = 0; i < Array.getLength(aValue); i++) { if (i > 0) { tempBuilder.append(", "); } tempBuilder.append(convertValueToString(Array.get(aValue, i), aVariableMap, aClassLoader, anAllowNullResultFlag)); } return tempBuilder.toString(); } else if (aValue instanceof DecimalValue) { return maskNullString(((DecimalValue) aValue).getDecimalValue().toString(), !anAllowNullResultFlag); } else if (aValue instanceof IntegerValue) { return maskNullString(((IntegerValue) aValue).getIntegerValue().toString(), !anAllowNullResultFlag); } else if (aValue instanceof StringValue) { return maskNullString(((StringValue) aValue).getStringValue().toString(), !anAllowNullResultFlag); } else if (aValue instanceof Variable) { Object tempActualValue = aVariableMap != null ? aVariableMap.get(((Variable) aValue).getName()) : null; return convertValueToString(tempActualValue, aVariableMap, aClassLoader, anAllowNullResultFlag); } else if (aValue instanceof EnumValue) { return maskNullString(((EnumValue) aValue).getEnumValue().getSimpleName(), !anAllowNullResultFlag); } else if (aValue instanceof BooleanValue) { return maskNullString(((BooleanValue) aValue).getBooleanValue(), !anAllowNullResultFlag); } else if (aValue instanceof DateValue) { DateFormat tempFormat = DateFormat.getDateInstance(DateFormat.LONG); Calendar tempCalendar = guardedDateConversion((DateValue) aValue); tempFormat.setCalendar(tempCalendar); return maskNullString(tempFormat.format(tempCalendar.getTime()), !anAllowNullResultFlag); } else if (aValue instanceof TimeValue) { DateFormat tempFormat = DateFormat.getTimeInstance(DateFormat.LONG); Calendar tempCalendar = guardedTimeConversion((TimeValue) aValue); tempFormat.setCalendar(tempCalendar); return maskNullString(tempFormat.format(tempCalendar.getTime()), !anAllowNullResultFlag); } else if (aValue instanceof DateAndTimeValue) { DateFormat tempFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG); Calendar tempCalendar = guardedDateAndTimeConversion((DateAndTimeValue) aValue); tempFormat.setCalendar(tempCalendar); return maskNullString(tempFormat.format(tempCalendar.getTime()), !anAllowNullResultFlag); } else if (aValue instanceof Date) { return maskNullString(DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format(aValue), !anAllowNullResultFlag); } else if (aValue instanceof NullValue) { return "null"; } else { if (aValue != null) { return aValue.toString(); } else { return maskNullString(null, !anAllowNullResultFlag); } } } /** * Ensures that a string is not null. * * @param aValue * the a value * @param aMaskValueFlag * the a mask value flag * @return the string */ public static String maskNullString(String aValue, boolean aMaskValueFlag) { if (aMaskValueFlag && aValue == null) { return "(null)"; } else { return aValue; } } /** * Converts a given value collection to a given Java type class, if possible. Will return an array if the collection * contains more than one item. This method is only being called inside Eclipse! * * @param aParamType * the target type * @param aCollection * the value collection * @param aVariableMap * the variable map, if variable references shall be resolved. If this is null, unresolved variable * references given as values will provoke an exception! * @param aClassLoader * the a class loader * @return the converted value * @throws ClassNotFoundException * the class not found exception * @throws UnexecutableException * the unexecutable exception * @throws InstantiationException * the instantiation exception */ public static Object convertEncapsulatedValueCollectionToParamType(Class<?> aParamType, ValueOrEnumValueOrOperationCollection aCollection, Map<VariableEntity, Object> aVariableMap, ClassLoader aClassLoader) throws ClassNotFoundException, UnexecutableException, InstantiationException { Class<?> tempTargetParamType = null; if (aParamType.isArray()) { tempTargetParamType = aParamType.getComponentType(); } else { tempTargetParamType = aParamType; } if (aCollection.getMoreValues() != null && aCollection.getMoreValues().size() > 0) { // this is actually an array Object tempResultArray = Array.newInstance(tempTargetParamType, aCollection.getMoreValues().size() + 1); for (int i = 0; i < aCollection.getMoreValues().size() + 1; i++) { ValueOrEnumValueOrOperation tempValue = (i == 0 ? aCollection.getValue() : aCollection.getMoreValues() .get(i - 1)); Object tempResultValue = convertEncapsulatedValueToParamType(tempTargetParamType, tempValue, aVariableMap, aClassLoader); Array.set(tempResultArray, i, tempResultValue); } // now we need to see whether we're even allowed to return an array if (aParamType.isArray()) { return tempResultArray; } else { throw new IllegalArgumentException("Parameter type class " + aParamType + " is not an array, but more than one value was given for conversion."); } } else { // this is just a single value Object tempResult = convertEncapsulatedValueToParamType(tempTargetParamType, aCollection.getValue(), aVariableMap, aClassLoader); // but we might need to return this as an array with one element if (aParamType.isArray()) { Object tempResultArray = Array.newInstance(tempTargetParamType, 1); Array.set(tempResultArray, 0, tempResult); return tempResultArray; } else { return tempResult; } } } /** * Returns a map of named result names to values acquired from a given named result container. This container is * assumed to be a simple Java Bean, with accessible accessor methods useable to retrieve the values of fields. The * field names are used as result names and thus keys in the map. Unreachable fields are ignored. * * @param aContainer * the container instance * @return the map of result names to values * @throws IntrospectionException * the introspection exception * @throws IllegalArgumentException * the illegal argument exception * @throws IllegalAccessException * the illegal access exception * @throws InvocationTargetException * the invocation target exception */ public static Map<String, Object> getValuesFromNamedResultContainer(Object aContainer) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { Map<String, Object> tempResultMap = new HashMap<String, Object>(); if (aContainer != null) { for (PropertyDescriptor tempDescriptor : Introspector.getBeanInfo(aContainer.getClass()) .getPropertyDescriptors()) { Method tempReadMethod = tempDescriptor.getReadMethod(); if (tempReadMethod != null) { if (Map.class.isAssignableFrom(tempDescriptor.getPropertyType())) { // this is a map for arbitrary result names @SuppressWarnings("unchecked") Map<String, Object> tempMap = (Map<String, Object>) tempReadMethod.invoke(aContainer); for (Entry<String, Object> tempEntry : tempMap.entrySet()) { tempResultMap.put(tempEntry.getKey(), tempEntry.getValue()); } } else { tempResultMap.put(tempDescriptor.getName(), tempReadMethod.invoke(aContainer)); } } } } return tempResultMap; } /** * Determines the result type by looking at a result container type for a specific result name. * * @param aContainerType * the container type * @param aResultName * the name of the result * @return the result type * @throws IntrospectionException * the introspection exception */ public static Class<?> getResultTypeFromNamedResultContainerType(Class<?> aContainerType, String aResultName) throws IntrospectionException { for (PropertyDescriptor tempDescriptor : Introspector.getBeanInfo(aContainerType).getPropertyDescriptors()) { if (tempDescriptor.getName().equals(aResultName)) { return tempDescriptor.getPropertyType(); } } return null; } private static Calendar guardedDateConversion(DateValue aValue) { try { return DateUtil.convertDateValue((DateValue) aValue); } catch (ParseException exc) { throw new IllegalArgumentException("Failed to parse date", exc); } } private static Calendar guardedTimeConversion(TimeValue aValue) { try { return DateUtil.convertTimeValue((TimeValue) aValue); } catch (ParseException exc) { throw new IllegalArgumentException("Failed to parse time", exc); } } private static Calendar guardedDateAndTimeConversion(DateAndTimeValue aValue) { try { return DateUtil.convertDateAndTimeValue((DateAndTimeValue) aValue); } catch (ParseException exc) { throw new IllegalArgumentException("Failed to parse date/time", exc); } } /** * Thrown if a variable value cannot be resolved because there's no variable map given. * * * @author Rene Schneider * */ public static class UnresolvableVariableException extends RuntimeException { /** * Serialization version. */ private static final long serialVersionUID = -7255981207674292161L; /** * Instantiates a new unresolvable variable exception. */ public UnresolvableVariableException() { super(); } /** * Instantiates a new unresolvable variable exception. * * @param aMessage * the a message * @param aCause * the a cause */ public UnresolvableVariableException(String aMessage, Throwable aCause) { super(aMessage, aCause); } /** * Instantiates a new unresolvable variable exception. * * @param aMessage * the a message */ public UnresolvableVariableException(String aMessage) { super(aMessage); } /** * Instantiates a new unresolvable variable exception. * * @param aCause * the a cause */ public UnresolvableVariableException(Throwable aCause) { super(aCause); } } }
true
true
public static Object convertEncapsulatedValueToParamType(Class<?> aParamType, ValueOrEnumValueOrOperation aValue, Map<VariableEntity, Object> aVariableMap, ClassLoader aClassLoader) throws UnresolvableVariableException, ClassNotFoundException, UnexecutableException, InstantiationException { if (aValue == null) { return null; } if (aValue instanceof Operation) { if (aClassLoader == null) { // cannot execute operations without the ability to load them return null; } else { OperationWrapper tempWrapper = new OperationWrapper((Operation) aValue, aClassLoader); Object tempResult = tempWrapper.executeOperation(aVariableMap, false); return convertValueToParamType(aParamType, tempResult); } } else if (aValue instanceof DecimalValue) { if (aParamType == Float.class) { return ((DecimalValue) aValue).getDecimalValue().floatValue(); } else if (aParamType == Double.class) { return ((DecimalValue) aValue).getDecimalValue().doubleValue(); } else if (aParamType == BigDecimal.class) { return ((DecimalValue) aValue).getDecimalValue(); } else if (aParamType == String.class) { return ((DecimalValue) aValue).getDecimalValue().toString(); } } else if (aValue instanceof IntegerValue) { if (aParamType == Integer.class) { return ((IntegerValue) aValue).getIntegerValue().intValue(); } else if (aParamType == Short.class) { return ((IntegerValue) aValue).getIntegerValue().shortValue(); } else if (aParamType == Byte.class) { return ((IntegerValue) aValue).getIntegerValue().byteValue(); } else if (aParamType == Long.class) { return ((IntegerValue) aValue).getIntegerValue().longValue(); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((IntegerValue) aValue).getIntegerValue(), 0); } else if (aParamType == BigInteger.class) { return ((IntegerValue) aValue).getIntegerValue(); } else if (aParamType == Float.class) { return ((IntegerValue) aValue).getIntegerValue().floatValue(); } else if (aParamType == Double.class) { return ((IntegerValue) aValue).getIntegerValue().doubleValue(); } else if (aParamType == String.class) { return Integer.toString(((IntegerValue) aValue).getIntegerValue().intValue()); } } else if (aValue instanceof NullValue) { return null; } else if (aValue instanceof StringValue) { if (aParamType == String.class) { return ((StringValue) aValue).getStringValue(); } else { try { if (aParamType == Integer.class) { return Integer.parseInt(((StringValue) aValue).getStringValue()); } else if (aParamType == Short.class) { return Short.parseShort(((StringValue) aValue).getStringValue()); } else if (aParamType == Byte.class) { return Byte.parseByte(((StringValue) aValue).getStringValue()); } else if (aParamType == Long.class) { return Long.parseLong(((StringValue) aValue).getStringValue()); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((StringValue) aValue).getStringValue()); } else if (aParamType == BigInteger.class) { return new BigInteger(((StringValue) aValue).getStringValue()); } else if (aParamType == Float.class) { return Float.parseFloat(((StringValue) aValue).getStringValue()); } else if (aParamType == Double.class) { return Double.parseDouble(((StringValue) aValue).getStringValue()); } else if (aParamType == Boolean.class) { return Boolean.parseBoolean(((StringValue) aValue).getStringValue()); } } catch (NumberFormatException exc) { throw new IllegalArgumentException("String value '" + ((StringValue) aValue).getStringValue() + "'" + " is not autoconvertible to parameter type " + aParamType); } } } else if (aValue instanceof EnumValue) { if (Enum.class.isAssignableFrom(aParamType)) { for (Object tempConstant : aParamType.getEnumConstants()) { if (tempConstant.toString().equals(((EnumValue) aValue).getEnumValue().getSimpleName())) { return tempConstant; } } } } else if (aValue instanceof Variable) { if (aVariableMap != null) { Object tempActualValue = aVariableMap.get(((Variable) aValue).getName()); if (tempActualValue != null) { if (tempActualValue instanceof Value) { return convertEncapsulatedValueToParamType(aParamType, (Value) tempActualValue, aVariableMap, aClassLoader); } else { return convertValueToParamType(aParamType, tempActualValue); } } else { return null; } } else { throw new UnresolvableVariableException("Unresolved variable " + ((Variable) aValue).getName().getName() + " encountered, but missing variable to value map!"); } } else if (aValue instanceof BooleanValue) { if (aParamType == Boolean.class) { return Boolean.valueOf(((BooleanValue) aValue).getBooleanValue()); } else if (aParamType == String.class) { return ((BooleanValue) aValue).getBooleanValue(); } } else if (aValue instanceof DateValue) { if (aParamType == Date.class) { return guardedDateConversion((DateValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateConversion((DateValue) aValue); } else if (aParamType == String.class) { return DateFormat.getDateInstance(DateFormat.LONG).format(guardedDateConversion((DateValue) aValue)); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof TimeValue) { if (aParamType == Date.class) { return guardedTimeConversion((TimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedTimeConversion((TimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getTimeInstance(DateFormat.LONG).format(guardedTimeConversion((TimeValue) aValue)); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof DateAndTimeValue) { if (aParamType == Date.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format( guardedDateAndTimeConversion((DateAndTimeValue) aValue)); } else { throw new IllegalArgumentException("Date/Time value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else { throw new UnsupportedOperationException("Value " + aValue.getClass() + " is unsupported"); } throw new IllegalArgumentException("Value " + aValue.getClass() + " is incompatible with parameter type " + aParamType); }
public static Object convertEncapsulatedValueToParamType(Class<?> aParamType, ValueOrEnumValueOrOperation aValue, Map<VariableEntity, Object> aVariableMap, ClassLoader aClassLoader) throws UnresolvableVariableException, ClassNotFoundException, UnexecutableException, InstantiationException { if (aValue == null) { return null; } if (aValue instanceof Operation) { if (aClassLoader == null) { // cannot execute operations without the ability to load them return null; } else { OperationWrapper tempWrapper = new OperationWrapper((Operation) aValue, aClassLoader); Object tempResult = tempWrapper.executeOperation(aVariableMap, false); return convertValueToParamType(aParamType, tempResult); } } else if (aValue instanceof DecimalValue) { if (aParamType == Float.class) { return ((DecimalValue) aValue).getDecimalValue().floatValue(); } else if (aParamType == Double.class) { return ((DecimalValue) aValue).getDecimalValue().doubleValue(); } else if (aParamType == BigDecimal.class) { return ((DecimalValue) aValue).getDecimalValue(); } else if (aParamType == String.class) { return ((DecimalValue) aValue).getDecimalValue().toString(); } } else if (aValue instanceof IntegerValue) { if (aParamType == Integer.class) { return ((IntegerValue) aValue).getIntegerValue().intValue(); } else if (aParamType == Short.class) { return ((IntegerValue) aValue).getIntegerValue().shortValue(); } else if (aParamType == Byte.class) { return ((IntegerValue) aValue).getIntegerValue().byteValue(); } else if (aParamType == Long.class) { return ((IntegerValue) aValue).getIntegerValue().longValue(); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((IntegerValue) aValue).getIntegerValue(), 0); } else if (aParamType == BigInteger.class) { return ((IntegerValue) aValue).getIntegerValue(); } else if (aParamType == Float.class) { return ((IntegerValue) aValue).getIntegerValue().floatValue(); } else if (aParamType == Double.class) { return ((IntegerValue) aValue).getIntegerValue().doubleValue(); } else if (aParamType == String.class) { return Integer.toString(((IntegerValue) aValue).getIntegerValue().intValue()); } } else if (aValue instanceof NullValue) { return null; } else if (aValue instanceof StringValue) { if (aParamType == String.class) { return ((StringValue) aValue).getStringValue(); } else { try { if (aParamType == Integer.class) { return Integer.parseInt(((StringValue) aValue).getStringValue()); } else if (aParamType == Short.class) { return Short.parseShort(((StringValue) aValue).getStringValue()); } else if (aParamType == Byte.class) { return Byte.parseByte(((StringValue) aValue).getStringValue()); } else if (aParamType == Long.class) { return Long.parseLong(((StringValue) aValue).getStringValue()); } else if (aParamType == BigDecimal.class) { return new BigDecimal(((StringValue) aValue).getStringValue()); } else if (aParamType == BigInteger.class) { return new BigInteger(((StringValue) aValue).getStringValue()); } else if (aParamType == Float.class) { return Float.parseFloat(((StringValue) aValue).getStringValue()); } else if (aParamType == Double.class) { return Double.parseDouble(((StringValue) aValue).getStringValue()); } else if (aParamType == Boolean.class) { return Boolean.parseBoolean(((StringValue) aValue).getStringValue()); } } catch (NumberFormatException exc) { throw new IllegalArgumentException("String value '" + ((StringValue) aValue).getStringValue() + "'" + " is not autoconvertible to parameter type " + aParamType); } } } else if (aValue instanceof EnumValue) { if (Enum.class.isAssignableFrom(aParamType)) { for (Object tempConstant : aParamType.getEnumConstants()) { if (tempConstant.toString().equals(((EnumValue) aValue).getEnumValue().getSimpleName())) { return tempConstant; } } } } else if (aValue instanceof Variable) { if (aVariableMap != null) { Object tempActualValue = aVariableMap.get(((Variable) aValue).getName()); if (tempActualValue != null) { if (tempActualValue instanceof Value) { return convertEncapsulatedValueToParamType(aParamType, (Value) tempActualValue, aVariableMap, aClassLoader); } else { return convertValueToParamType(aParamType, tempActualValue); } } else { return null; } } else { throw new UnresolvableVariableException("Unresolved variable " + ((Variable) aValue).getName().getName() + " encountered, but missing variable to value map!"); } } else if (aValue instanceof BooleanValue) { if (aParamType == Boolean.class) { return Boolean.valueOf(((BooleanValue) aValue).getBooleanValue()); } else if (aParamType == String.class) { return ((BooleanValue) aValue).getBooleanValue(); } } else if (aValue instanceof DateValue) { if (aParamType == Date.class) { return guardedDateConversion((DateValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateConversion((DateValue) aValue); } else if (aParamType == String.class) { return DateFormat.getDateInstance(DateFormat.LONG).format( guardedDateConversion((DateValue) aValue).getTime()); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof TimeValue) { if (aParamType == Date.class) { return guardedTimeConversion((TimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedTimeConversion((TimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getTimeInstance(DateFormat.LONG).format(guardedTimeConversion((TimeValue) aValue)); } else { throw new IllegalArgumentException("Date value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else if (aValue instanceof DateAndTimeValue) { if (aParamType == Date.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue).getTime(); } else if (aParamType == Calendar.class) { return guardedDateAndTimeConversion((DateAndTimeValue) aValue); } else if (aParamType == String.class) { return DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG).format( guardedDateAndTimeConversion((DateAndTimeValue) aValue)); } else { throw new IllegalArgumentException("Date/Time value '" + aValue + "'" + " is not autoconvertible to parameter type " + aParamType); } } else { throw new UnsupportedOperationException("Value " + aValue.getClass() + " is unsupported"); } throw new IllegalArgumentException("Value " + aValue.getClass() + " is incompatible with parameter type " + aParamType); }
diff --git a/src/java/HECL/src/HECL.java b/src/java/HECL/src/HECL.java index 8d94fd4..956df0a 100644 --- a/src/java/HECL/src/HECL.java +++ b/src/java/HECL/src/HECL.java @@ -1,159 +1,159 @@ import com.jogamp.common.nio.Buffers; import com.jogamp.opencl.CLBuffer; import com.jogamp.opencl.CLCommandQueue; import com.jogamp.opencl.CLContext; import com.jogamp.opencl.CLImage2d; import com.jogamp.opencl.CLImageFormat; import com.jogamp.opencl.CLImageFormat.*; import com.jogamp.opencl.CLKernel; import java.awt.image.BufferedImage; import java.io.IOException; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.InputMismatchException; import java.util.Scanner; import static java.lang.System.*; public class HECL { private static final int HIST_SIZE = 256; private static CLParams clParams = null; public static float[] testRgbToSpherical() { BufferedImage image = ImageUtils.readImage("lena_f.png"); CLBuffer<FloatBuffer> resultImage = Converter.convertToSpherical(clParams, image); float[] pixels = new float[image.getData().getDataBuffer().getSize()]; resultImage.getBuffer().get(pixels, 0, pixels.length); for(int i = 0; i < 100; ++i) { System.out.print(pixels[i] + " "); } System.out.println(); return pixels; } public static void testSphericalToRgb(float[] sphericalImageFloats) { BufferedImage image = null; image = ImageUtils.readImage("lena_f.png"); BufferedImage rgbImage = Converter.convertToRGB(clParams, sphericalImageFloats, image.getWidth(), image.getHeight()); ImageUtils.show(rgbImage, 0, 0, "RGB Image"); } private static void testCopyImage() { BufferedImage image = ImageUtils.readImage("lena_f.png"); ImageUtils.show(image, 0, 0, "Original image"); CLContext context = clParams.getContext(); CLCommandQueue queue = clParams.getQueue(); float[] pixels = image.getRaster().getPixels(0, 0, image.getWidth(), image.getHeight(), (float[])null); // We use ChanelOrder.INTENSITY because it's grey CLImageFormat format = new CLImageFormat(ChannelOrder.INTENSITY, ChannelType.FLOAT); CLImage2d<FloatBuffer> imageA = context.createImage2d(Buffers.newDirectFloatBuffer(pixels), image.getWidth(), image.getHeight(), format); CLImage2d<FloatBuffer> imageB = context.createImage2d(Buffers.newDirectFloatBuffer(pixels.length), image.getWidth(), image.getHeight(), format); out.println("used device memory: " + (imageA.getCLSize()+imageB.getCLSize())/1000000 +"MB"); // get a reference to the kernel function with the name 'copy_image' // and map the buffers to its input parameters. CLKernel kernel = clParams.getKernel("copy_image"); kernel.putArgs(imageA, imageB).putArg(image.getWidth()).putArg(image.getHeight()); // asynchronous write of data to GPU device, // followed by blocking read to get the computed results back. long time = nanoTime(); queue.putWriteImage(imageA, false) .put2DRangeKernel(kernel, 0, 0, image.getWidth(), image.getHeight(), 0, 0) .putReadImage(imageB, true); time = nanoTime() - time; // show resulting image. FloatBuffer bufferB = imageB.getBuffer(); CLBuffer<FloatBuffer> buffer = context.createBuffer(bufferB, CLBuffer.Mem.READ_WRITE); BufferedImage resultImage = ImageUtils.createImage(image.getWidth(), image.getHeight(), buffer); ImageUtils.show(resultImage, 0, 0, "Image copy"); out.println("computation took: "+(time/1000000)+"ms"); } public static boolean Menu() { @SuppressWarnings("resource") Scanner reader = new Scanner(System.in); System.out.println("Choose an option:\n" + "1. Test RGB to Spherical\n" + "2. Test Spherical to RGB\n" + "3. Test Copy image\n" + "4. Exit"); boolean exit = false; try { if(reader.hasNext()) { int choice = reader.nextInt(); - if(choice < 0 || choice > 3) return false; + if(choice < 0 || choice > 4) return false; switch(choice) { case 1: testRgbToSpherical(); break; case 2: testSphericalToRgb(testRgbToSpherical()); break; case 3: testCopyImage(); break; case 4: exit = true; break; } } else { return false; } } catch(InputMismatchException ioException) { System.out.println("Invalid, must enter a number."); return false; } finally { if(exit && clParams != null) { clParams.release(); clParams = null; } } return exit; } public static void main(String[] args) { clParams = new CLParams("kernels.cl"); try { clParams.init(); } catch (IOException e) { System.out.println("Kernels file not found"); e.printStackTrace(); } boolean exit = false; while(!exit) { exit = Menu(); } } public static int roundUp(int groupSize, int globalSize) { int r = globalSize % groupSize; if (r == 0) { return globalSize; } else { return globalSize + groupSize - r; } } }
true
true
public static boolean Menu() { @SuppressWarnings("resource") Scanner reader = new Scanner(System.in); System.out.println("Choose an option:\n" + "1. Test RGB to Spherical\n" + "2. Test Spherical to RGB\n" + "3. Test Copy image\n" + "4. Exit"); boolean exit = false; try { if(reader.hasNext()) { int choice = reader.nextInt(); if(choice < 0 || choice > 3) return false; switch(choice) { case 1: testRgbToSpherical(); break; case 2: testSphericalToRgb(testRgbToSpherical()); break; case 3: testCopyImage(); break; case 4: exit = true; break; } } else { return false; } } catch(InputMismatchException ioException) { System.out.println("Invalid, must enter a number."); return false; } finally { if(exit && clParams != null) { clParams.release(); clParams = null; } } return exit; }
public static boolean Menu() { @SuppressWarnings("resource") Scanner reader = new Scanner(System.in); System.out.println("Choose an option:\n" + "1. Test RGB to Spherical\n" + "2. Test Spherical to RGB\n" + "3. Test Copy image\n" + "4. Exit"); boolean exit = false; try { if(reader.hasNext()) { int choice = reader.nextInt(); if(choice < 0 || choice > 4) return false; switch(choice) { case 1: testRgbToSpherical(); break; case 2: testSphericalToRgb(testRgbToSpherical()); break; case 3: testCopyImage(); break; case 4: exit = true; break; } } else { return false; } } catch(InputMismatchException ioException) { System.out.println("Invalid, must enter a number."); return false; } finally { if(exit && clParams != null) { clParams.release(); clParams = null; } } return exit; }
diff --git a/filemgr/src/main/java/org/apache/oodt/cas/filemgr/tools/ExpImpCatalog.java b/filemgr/src/main/java/org/apache/oodt/cas/filemgr/tools/ExpImpCatalog.java index 32f2c4029..9d124c9e7 100644 --- a/filemgr/src/main/java/org/apache/oodt/cas/filemgr/tools/ExpImpCatalog.java +++ b/filemgr/src/main/java/org/apache/oodt/cas/filemgr/tools/ExpImpCatalog.java @@ -1,445 +1,448 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.oodt.cas.filemgr.tools; // JDK imports import java.io.File; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; // OODT imports import org.apache.oodt.cas.filemgr.catalog.Catalog; import org.apache.oodt.cas.filemgr.structs.Product; import org.apache.oodt.cas.filemgr.structs.ProductPage; import org.apache.oodt.cas.filemgr.structs.ProductType; import org.apache.oodt.cas.filemgr.structs.exceptions.CatalogException; import org.apache.oodt.cas.filemgr.structs.exceptions.ConnectionException; import org.apache.oodt.cas.filemgr.system.XmlRpcFileManagerClient; import org.apache.oodt.cas.filemgr.util.GenericFileManagerObjectFactory; import org.apache.oodt.cas.metadata.Metadata; /** * @author mattmann * @version $Revision$ * * <p> * A Tool to export from a source file manager catalog and import into a dest * file manager catalog. * </p> * */ public class ExpImpCatalog { /* the client to the source catalog to export */ private XmlRpcFileManagerClient sourceClient = null; /* the client to the dest catalog to import into */ private XmlRpcFileManagerClient destClient = null; /* a source catalog I/F to export from (if no fm client is desired) */ private Catalog srcCatalog = null; /* a dest catalog I/F to import into (if no fm client is desired) */ private Catalog destCatalog = null; /* whether or not we should ensure a product doesn't exist before copying */ private boolean ensureUnique = false; /* our log stream */ private static final Logger LOG = Logger.getLogger(ExpImpCatalog.class .getName()); /** * Default Constructor. * * @param sUrl * The url to the source file manager to export from. * @param dUrl * The url to the dest file manager to import into. * @param unique * Whether or not the import tool should ensure that the product * from the source does not exist in the dest. */ public ExpImpCatalog(URL sUrl, URL dUrl, boolean unique) { try { sourceClient = new XmlRpcFileManagerClient(sUrl); } catch (ConnectionException e) { LOG.log(Level.WARNING, "Unable to connect to source filemgr: [" + sUrl + "]"); throw new RuntimeException(e); } try { destClient = new XmlRpcFileManagerClient(dUrl); } catch (ConnectionException e) { LOG.log(Level.WARNING, "Unable to connect to dest filemgr: [" + dUrl + "]"); throw new RuntimeException(e); } this.ensureUnique = unique; } public ExpImpCatalog(String sPropFilePath, String dPropFilePath, boolean unique) throws InstantiationException { this.ensureUnique = unique; LOG.log(Level.INFO, "Constructing tool using catalog interfaces"); // first load the source prop file try { System.getProperties().load( new File(sPropFilePath).toURL().openStream()); } catch (Exception e) { throw new InstantiationException(e.getMessage()); } // now construct the source catalog String srcCatFactoryStr = System.getProperty("filemgr.catalog.factory"); LOG.log(Level.INFO, "source catalog factory: [" + srcCatFactoryStr + "]"); this.srcCatalog = GenericFileManagerObjectFactory .getCatalogServiceFromFactory(srcCatFactoryStr); // first load the dest prop file try { System.getProperties().load( new File(dPropFilePath).toURL().openStream()); } catch (Exception e) { throw new InstantiationException(e.getMessage()); } String destCatFactoryStr = System .getProperty("filemgr.catalog.factory"); LOG .log(Level.INFO, "dest catalog factory: [" + destCatFactoryStr + "]"); this.destCatalog = GenericFileManagerObjectFactory .getCatalogServiceFromFactory(destCatFactoryStr); } public void doExpImport(List sourceProductTypes) throws Exception { if (this.sourceClient != null && this.destClient != null) { // do validation of source/dest types // otherwise, user is on their own discretion List destProductTypes = destClient.getProductTypes(); if (!typesExist(sourceProductTypes, destProductTypes)) { throw new Exception( "The source product types must be present in the dest file manager!"); } else { LOG .log(Level.INFO, "Source types and Dest types match: beginning processing"); } } else LOG.log(Level.INFO, "Skipping type validation: catalog i/f impls being used."); // we'll use the get product page method for each product type // paginate through products using source product type for (Iterator i = sourceProductTypes.iterator(); i.hasNext();) { ProductType type = (ProductType) i.next(); try { exportTypeToDest(type); } catch (Exception e) { LOG.log(Level.WARNING, "Error exporting product type: [" + type.getName() + "] from source to dest: Message: " + e.getMessage(), e); throw e; } } } public void doExpImport() throws Exception { if (sourceClient == null) throw new RuntimeException( "Cannot request exp/imp of all product types if no filemgr url specified!"); List sourceProductTypes = sourceClient.getProductTypes(); doExpImport(sourceProductTypes); } private void exportTypeToDest(ProductType type) throws Exception { ProductPage page = null; if (this.srcCatalog != null) { page = srcCatalog.getFirstPage(type); } else { page = sourceClient.getFirstPage(type); } if (page == null) return; exportProductsToDest(page.getPageProducts(), type); while (!page.isLastPage()) { if (this.srcCatalog != null) { page = srcCatalog.getNextPage(type, page); } else page = sourceClient.getNextPage(type, page); if (page == null) break; exportProductsToDest(page.getPageProducts(), type); } } private void exportProductsToDest(List products, ProductType type) throws Exception { if (products != null && products.size() > 0) { for (Iterator i = products.iterator(); i.hasNext();) { Product p = (Product) i.next(); if (ensureUnique) { boolean hasProduct = safeHasProductTypeByName(p .getProductName()); if (hasProduct) { LOG.log(Level.INFO, "Skipping product: [" + p.getProductName() + "]: ensure unique enabled: " + "product exists in dest catalog"); continue; } } p.setProductType(type); if (sourceClient != null) { p .setProductReferences(sourceClient .getProductReferences(p)); } else p.setProductReferences(srcCatalog.getProductReferences(p)); Metadata met = null; if (sourceClient != null) { met = sourceClient.getMetadata(p); } else { met = srcCatalog.getMetadata(p); } LOG .log( Level.INFO, "Source Product: [" + p.getProductName() + "]: Met Extraction and " + "Reference Extraction successful: writing to dest file manager"); - // remove the default CAS fields for metadata - met.removeMetadata("CAS.ProductId"); - met.removeMetadata("CAS.ProductReceivedTime"); - met.removeMetadata("CAS.ProductName"); + // OODT-543 + if(sourceClient != null){ + // remove the default CAS fields for metadata + met.removeMetadata("CAS.ProductId"); + met.removeMetadata("CAS.ProductReceivedTime"); + met.removeMetadata("CAS.ProductName"); + } Product destProduct = new Product(); // copy through destProduct.setProductName(p.getProductName()); destProduct.setProductStructure(p.getProductStructure()); destProduct.setProductType((destClient != null) ? destClient .getProductTypeById(type.getProductTypeId()) : type); destProduct.setTransferStatus(p.getTransferStatus()); LOG.log(Level.INFO, "Cataloging Product: [" + p.getProductName() + "]"); String destProductId = null; if (destCatalog != null) { destCatalog.addProduct(destProduct); destProductId = destProduct.getProductId(); } else destProductId = destClient.catalogProduct(destProduct); LOG.log(Level.INFO, "Catalog successful: dest product id: [" + destProductId + "]"); destProduct.setProductId(destProductId); LOG.log(Level.INFO, "Adding references for dest product: [" + destProductId + "]"); destProduct.setProductReferences(p.getProductReferences()); if (destCatalog != null) { destCatalog.addProductReferences(destProduct); } else destClient.addProductReferences(destProduct); LOG.log(Level.INFO, "Reference addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Adding metadata for dest product: [" + destProductId + "]"); if (destCatalog != null) { destCatalog.addMetadata(met, destProduct); } else destClient.addMetadata(destProduct, met); LOG.log(Level.INFO, "Met addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Successful import of product: [" + p.getProductName() + "] into dest file manager"); } } } /** * @return Returns the ensureUnique. */ public boolean isEnsureUnique() { return ensureUnique; } /** * @param ensureUnique * The ensureUnique to set. */ public void setEnsureUnique(boolean ensureUnique) { this.ensureUnique = ensureUnique; } /** * @param args */ public static void main(String[] args) throws Exception { String sourceUrl = null, destUrl = null, srcCatPropFile = null, destCatPropFile = null; boolean unique = false; List types = null; String usage = "ExpImpCatalog [options] \n" + "--source <url>\n" + "--dest <url>\n " + "--unique\n" + "[--types <comma separate list of product type names>]\n" + "[--sourceCatProps <file> --destCatProps <file>]\n"; for (int i = 0; i < args.length; i++) { if (args[i].equals("--source")) { sourceUrl = args[++i]; } else if (args[i].equals("--dest")) { destUrl = args[++i]; } else if (args[i].equals("--unique")) { unique = true; } else if (args[i].equals("--types")) { String[] typesAndIdsEnc = args[++i].split(","); types = new Vector(typesAndIdsEnc.length); for (int j = 0; j < typesAndIdsEnc.length; j++) { String[] typeIdToks = typesAndIdsEnc[j].split("\\|"); ProductType type = new ProductType(); type.setName(typeIdToks[0]); type.setProductTypeId(typeIdToks[1]); types.add(type); } } else if (args[i].equals("--sourceCatProps")) { srcCatPropFile = args[++i]; } else if (args[i].equals("--destCatProps")) { destCatPropFile = args[++i]; } } if (((sourceUrl == null || destUrl == null) && (srcCatPropFile == null || destCatPropFile == null)) || (sourceUrl != null && destUrl != null && (srcCatPropFile != null || destCatPropFile != null)) || ((srcCatPropFile != null && destCatPropFile == null) || (destCatPropFile != null && srcCatPropFile == null))) { System.err.println(usage); System.exit(1); } ExpImpCatalog tool = null; if (srcCatPropFile != null) { tool = new ExpImpCatalog(srcCatPropFile, destCatPropFile, unique); } else tool = new ExpImpCatalog(new URL(sourceUrl), new URL(destUrl), unique); if (types != null && types.size() > 0) { tool.doExpImport(types); } else tool.doExpImport(); } private boolean typesExist(List sourceList, List destList) { if (sourceList == null || (sourceList != null && sourceList.size() == 0)) { return false; } if (destList == null || (destList != null && destList.size() == 0)) { return false; } // iterate through the source types and try and find the type in the // destList for (Iterator i = sourceList.iterator(); i.hasNext();) { ProductType type = (ProductType) i.next(); if (!typeInList(type, destList)) { LOG.log(Level.WARNING, "Source type: [" + type.getName() + "] not present in dest file manager"); return false; } } return true; } private boolean typeInList(ProductType type, List typeList) { if (typeList == null || (typeList != null && typeList.size() == 0)) { return false; } for (Iterator i = typeList.iterator(); i.hasNext();) { ProductType destType = (ProductType) i.next(); if (destType.getProductTypeId().equals(type.getProductTypeId()) && destType.getName().equals(type.getName())) { return true; } } return false; } private boolean safeHasProductTypeByName(String productName) { if (destCatalog != null) { try { return (destCatalog.getProductByName(productName) != null); } catch (CatalogException e) { e.printStackTrace(); LOG .log(Level.WARNING, "Exceptiong checking for product type by name: [" + productName + "]: Message: " + e.getMessage()); return false; } } else { try { return destClient.hasProduct(productName); } catch (CatalogException e) { e.printStackTrace(); LOG .log(Level.WARNING, "Exceptiong checking for product type by name: [" + productName + "]: Message: " + e.getMessage()); return false; } } } }
true
true
private void exportProductsToDest(List products, ProductType type) throws Exception { if (products != null && products.size() > 0) { for (Iterator i = products.iterator(); i.hasNext();) { Product p = (Product) i.next(); if (ensureUnique) { boolean hasProduct = safeHasProductTypeByName(p .getProductName()); if (hasProduct) { LOG.log(Level.INFO, "Skipping product: [" + p.getProductName() + "]: ensure unique enabled: " + "product exists in dest catalog"); continue; } } p.setProductType(type); if (sourceClient != null) { p .setProductReferences(sourceClient .getProductReferences(p)); } else p.setProductReferences(srcCatalog.getProductReferences(p)); Metadata met = null; if (sourceClient != null) { met = sourceClient.getMetadata(p); } else { met = srcCatalog.getMetadata(p); } LOG .log( Level.INFO, "Source Product: [" + p.getProductName() + "]: Met Extraction and " + "Reference Extraction successful: writing to dest file manager"); // remove the default CAS fields for metadata met.removeMetadata("CAS.ProductId"); met.removeMetadata("CAS.ProductReceivedTime"); met.removeMetadata("CAS.ProductName"); Product destProduct = new Product(); // copy through destProduct.setProductName(p.getProductName()); destProduct.setProductStructure(p.getProductStructure()); destProduct.setProductType((destClient != null) ? destClient .getProductTypeById(type.getProductTypeId()) : type); destProduct.setTransferStatus(p.getTransferStatus()); LOG.log(Level.INFO, "Cataloging Product: [" + p.getProductName() + "]"); String destProductId = null; if (destCatalog != null) { destCatalog.addProduct(destProduct); destProductId = destProduct.getProductId(); } else destProductId = destClient.catalogProduct(destProduct); LOG.log(Level.INFO, "Catalog successful: dest product id: [" + destProductId + "]"); destProduct.setProductId(destProductId); LOG.log(Level.INFO, "Adding references for dest product: [" + destProductId + "]"); destProduct.setProductReferences(p.getProductReferences()); if (destCatalog != null) { destCatalog.addProductReferences(destProduct); } else destClient.addProductReferences(destProduct); LOG.log(Level.INFO, "Reference addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Adding metadata for dest product: [" + destProductId + "]"); if (destCatalog != null) { destCatalog.addMetadata(met, destProduct); } else destClient.addMetadata(destProduct, met); LOG.log(Level.INFO, "Met addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Successful import of product: [" + p.getProductName() + "] into dest file manager"); } } }
private void exportProductsToDest(List products, ProductType type) throws Exception { if (products != null && products.size() > 0) { for (Iterator i = products.iterator(); i.hasNext();) { Product p = (Product) i.next(); if (ensureUnique) { boolean hasProduct = safeHasProductTypeByName(p .getProductName()); if (hasProduct) { LOG.log(Level.INFO, "Skipping product: [" + p.getProductName() + "]: ensure unique enabled: " + "product exists in dest catalog"); continue; } } p.setProductType(type); if (sourceClient != null) { p .setProductReferences(sourceClient .getProductReferences(p)); } else p.setProductReferences(srcCatalog.getProductReferences(p)); Metadata met = null; if (sourceClient != null) { met = sourceClient.getMetadata(p); } else { met = srcCatalog.getMetadata(p); } LOG .log( Level.INFO, "Source Product: [" + p.getProductName() + "]: Met Extraction and " + "Reference Extraction successful: writing to dest file manager"); // OODT-543 if(sourceClient != null){ // remove the default CAS fields for metadata met.removeMetadata("CAS.ProductId"); met.removeMetadata("CAS.ProductReceivedTime"); met.removeMetadata("CAS.ProductName"); } Product destProduct = new Product(); // copy through destProduct.setProductName(p.getProductName()); destProduct.setProductStructure(p.getProductStructure()); destProduct.setProductType((destClient != null) ? destClient .getProductTypeById(type.getProductTypeId()) : type); destProduct.setTransferStatus(p.getTransferStatus()); LOG.log(Level.INFO, "Cataloging Product: [" + p.getProductName() + "]"); String destProductId = null; if (destCatalog != null) { destCatalog.addProduct(destProduct); destProductId = destProduct.getProductId(); } else destProductId = destClient.catalogProduct(destProduct); LOG.log(Level.INFO, "Catalog successful: dest product id: [" + destProductId + "]"); destProduct.setProductId(destProductId); LOG.log(Level.INFO, "Adding references for dest product: [" + destProductId + "]"); destProduct.setProductReferences(p.getProductReferences()); if (destCatalog != null) { destCatalog.addProductReferences(destProduct); } else destClient.addProductReferences(destProduct); LOG.log(Level.INFO, "Reference addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Adding metadata for dest product: [" + destProductId + "]"); if (destCatalog != null) { destCatalog.addMetadata(met, destProduct); } else destClient.addMetadata(destProduct, met); LOG.log(Level.INFO, "Met addition successful for dest product: [" + destProductId + "]"); LOG.log(Level.INFO, "Successful import of product: [" + p.getProductName() + "] into dest file manager"); } } }
diff --git a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java index f5b18841..524b4a1a 100644 --- a/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java +++ b/src/java/org/jivesoftware/sparkimpl/plugin/transcripts/ChatTranscriptPlugin.java @@ -1,386 +1,386 @@ /** * $Revision: $ * $Date: $ * * Copyright (C) 2006 Jive Software. All rights reserved. * * This software is published under the terms of the GNU Lesser Public License (LGPL), * a copy of which is included in this distribution. */ package org.jivesoftware.sparkimpl.plugin.transcripts; import org.jdesktop.swingx.calendar.DateUtils; import org.jivesoftware.MainWindowListener; import org.jivesoftware.resource.Res; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.smack.ConnectionListener; import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.util.StringUtils; import org.jivesoftware.spark.SparkManager; import org.jivesoftware.spark.component.BackgroundPanel; import org.jivesoftware.spark.plugin.ContextMenuListener; import org.jivesoftware.spark.ui.ChatRoom; import org.jivesoftware.spark.ui.ChatRoomButton; import org.jivesoftware.spark.ui.ChatRoomListener; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.ui.ContactList; import org.jivesoftware.spark.ui.VCardPanel; import org.jivesoftware.spark.ui.rooms.ChatRoomImpl; import org.jivesoftware.spark.util.GraphicUtils; import org.jivesoftware.spark.util.SwingWorker; import org.jivesoftware.spark.util.TaskEngine; import org.jivesoftware.sparkimpl.settings.local.LocalPreferences; import org.jivesoftware.sparkimpl.settings.local.SettingsManager; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.text.html.HTMLEditorKit; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.File; import java.text.SimpleDateFormat; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.TimerTask; /** * The <code>ChatTranscriptPlugin</code> is responsible for transcript handling within Spark. * * @author Derek DeMoro */ public class ChatTranscriptPlugin implements ChatRoomListener { private final SimpleDateFormat notificationDateFormatter; private final SimpleDateFormat messageDateFormatter; /** * Register the listeners for transcript persistence. */ public ChatTranscriptPlugin() { SparkManager.getChatManager().addChatRoomListener(this); notificationDateFormatter = new SimpleDateFormat("EEEEE, MMMMM d, yyyy"); messageDateFormatter = new SimpleDateFormat("h:mm a"); final ContactList contactList = SparkManager.getWorkspace().getContactList(); final Action viewHistoryAction = new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { ContactItem item = (ContactItem)contactList.getSelectedUsers().iterator().next(); final String jid = item.getJID(); showHistory(jid); } }; viewHistoryAction.putValue(Action.NAME, Res.getString("menuitem.view.contact.history")); viewHistoryAction.putValue(Action.SMALL_ICON, SparkRes.getImageIcon(SparkRes.HISTORY_16x16)); contactList.addContextMenuListener(new ContextMenuListener() { public void poppingUp(Object object, JPopupMenu popup) { if (object instanceof ContactItem) { popup.add(viewHistoryAction); } } public void poppingDown(JPopupMenu popup) { } public boolean handleDefaultAction(MouseEvent e) { return false; } }); SparkManager.getMainWindow().addMainWindowListener(new MainWindowListener() { public void shutdown() { persistConversations(); } public void mainWindowActivated() { } public void mainWindowDeactivated() { } }); SparkManager.getConnection().addConnectionListener(new ConnectionListener() { public void connectionClosed() { } public void connectionClosedOnError(Exception e) { persistConversations(); } public void reconnectingIn(int i) { } public void reconnectionSuccessful() { } public void reconnectionFailed(Exception exception) { } }); } public void persistConversations() { for (ChatRoom room : SparkManager.getChatManager().getChatContainer().getChatRooms()) { if (room instanceof ChatRoomImpl) { ChatRoomImpl roomImpl = (ChatRoomImpl)room; if (roomImpl.isActive()) { persistChatRoom(roomImpl); } } } } public boolean canShutDown() { return true; } public void chatRoomOpened(final ChatRoom room) { LocalPreferences pref = SettingsManager.getLocalPreferences(); if (!pref.isChatHistoryEnabled()) { return; } final String jid = room.getRoomname(); File transcriptFile = ChatTranscripts.getTranscriptFile(jid); if (!transcriptFile.exists()) { return; } if (room instanceof ChatRoomImpl) { // Add History Button ChatRoomButton chatRoomButton = new ChatRoomButton(SparkRes.getImageIcon(SparkRes.HISTORY_24x24_IMAGE)); room.getToolBar().addChatRoomButton(chatRoomButton); chatRoomButton.setToolTipText(Res.getString("tooltip.view.history")); chatRoomButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { ChatRoomImpl roomImpl = (ChatRoomImpl)room; showHistory(roomImpl.getParticipantJID()); } }); } } public void chatRoomLeft(ChatRoom room) { } public void chatRoomClosed(final ChatRoom room) { // Persist only agent to agent chat rooms. if (room.getChatType() == Message.Type.chat) { persistChatRoom(room); } } private void persistChatRoom(final ChatRoom room) { LocalPreferences pref = SettingsManager.getLocalPreferences(); if (!pref.isChatHistoryEnabled()) { return; } final String jid = room.getRoomname(); final List<Message> transcripts = room.getTranscripts(); ChatTranscript transcript = new ChatTranscript(); for (Message message : transcripts) { HistoryMessage history = new HistoryMessage(); history.setTo(message.getTo()); history.setFrom(message.getFrom()); history.setBody(message.getBody()); Date date = (Date)message.getProperty("date"); if (date != null) { history.setDate(date); } else { history.setDate(new Date()); } transcript.addHistoryMessage(history); } ChatTranscripts.appendToTranscript(jid, transcript); } public void chatRoomActivated(ChatRoom room) { } public void userHasJoined(ChatRoom room, String userid) { } public void userHasLeft(ChatRoom room, String userid) { } public void uninstall() { // Do nothing. } private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); final VCardPanel topPanel = new VCardPanel(jid); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(50); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final ChatTranscript transcript = (ChatTranscript)get(); final List<HistoryMessage> list = transcript.getMessages(); final String personalNickname = SparkManager.getUserManager().getNickname(); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = message.getBody(); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='" + color + "'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>" + Res.getString("message.no.history.found") + "</b>"); } window.setText(builder.toString()); } }; - TaskEngine.getInstance().schedule(transcriptTask, 500); + TaskEngine.getInstance().schedule(transcriptTask, 10); } }; transcriptLoader.start(); } /** * Sort HistoryMessages by date. */ final Comparator dateComparator = new Comparator() { public int compare(Object messageOne, Object messageTwo) { final HistoryMessage historyMessageOne = (HistoryMessage)messageOne; final HistoryMessage historyMessageTwo = (HistoryMessage)messageTwo; long time1 = historyMessageOne.getDate().getTime(); long time2 = historyMessageTwo.getDate().getTime(); if (time1 < time2) { return 1; } else if (time1 > time2) { return -1; } return 0; } }; }
true
true
private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); final VCardPanel topPanel = new VCardPanel(jid); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(50); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final ChatTranscript transcript = (ChatTranscript)get(); final List<HistoryMessage> list = transcript.getMessages(); final String personalNickname = SparkManager.getUserManager().getNickname(); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = message.getBody(); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='" + color + "'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>" + Res.getString("message.no.history.found") + "</b>"); } window.setText(builder.toString()); } }; TaskEngine.getInstance().schedule(transcriptTask, 500); } }; transcriptLoader.start(); }
private void showHistory(final String jid) { SwingWorker transcriptLoader = new SwingWorker() { public Object construct() { String bareJID = StringUtils.parseBareAddress(jid); return ChatTranscripts.getChatTranscript(bareJID); } public void finished() { final JPanel mainPanel = new BackgroundPanel(); mainPanel.setLayout(new BorderLayout()); final VCardPanel topPanel = new VCardPanel(jid); mainPanel.add(topPanel, BorderLayout.NORTH); final JEditorPane window = new JEditorPane(); window.setEditorKit(new HTMLEditorKit()); window.setBackground(Color.white); final JScrollPane pane = new JScrollPane(window); pane.getVerticalScrollBar().setBlockIncrement(50); pane.getVerticalScrollBar().setUnitIncrement(20); mainPanel.add(pane, BorderLayout.CENTER); final ChatTranscript transcript = (ChatTranscript)get(); final List<HistoryMessage> list = transcript.getMessages(); final String personalNickname = SparkManager.getUserManager().getNickname(); final JFrame frame = new JFrame(Res.getString("title.history.for", jid)); frame.setIconImage(SparkRes.getImageIcon(SparkRes.HISTORY_16x16).getImage()); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(mainPanel, BorderLayout.CENTER); frame.pack(); frame.setSize(600, 400); window.setCaretPosition(0); GraphicUtils.centerWindowOnScreen(frame); frame.setVisible(true); window.setEditable(false); final StringBuilder builder = new StringBuilder(); builder.append("<html><body><table cellpadding=0 cellspacing=0>"); final TimerTask transcriptTask = new TimerTask() { public void run() { Date lastPost = null; String lastPerson = null; boolean initialized = false; for (HistoryMessage message : list) { String color = "blue"; String from = message.getFrom(); String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom()); String body = message.getBody(); if (nickname.equals(message.getFrom())) { String otherJID = StringUtils.parseBareAddress(message.getFrom()); String myJID = SparkManager.getSessionManager().getBareAddress(); if (otherJID.equals(myJID)) { nickname = personalNickname; } else { nickname = StringUtils.parseName(nickname); } } if (!StringUtils.parseBareAddress(from).equals(SparkManager.getSessionManager().getBareAddress())) { color = "red"; } long lastPostTime = lastPost != null ? lastPost.getTime() : 0; int diff = DateUtils.getDaysDiff(lastPostTime, message.getDate().getTime()); if (diff != 0) { if (initialized) { builder.append("<tr><td><br></td></tr>"); } builder.append("<tr><td colspan=2><font size=4 color=gray><b><u>" + notificationDateFormatter.format(message.getDate()) + "</u></b></font></td></tr>"); lastPerson = null; initialized = true; } String value = "[" + messageDateFormatter.format(message.getDate()) + "]&nbsp;&nbsp; "; boolean newInsertions = lastPerson == null || !lastPerson.equals(nickname); if (newInsertions) { builder.append("<tr valign=top><td colspan=2 nowrap>"); builder.append("<font size=4 color='" + color + "'><b>"); builder.append(nickname); builder.append("</b></font>"); builder.append("</td></tr>"); } builder.append("<tr valign=top><td align=left nowrap>"); builder.append(value); builder.append("</td><td align=left>"); builder.append(body); builder.append("</td></tr>"); lastPost = message.getDate(); lastPerson = nickname; } builder.append("</table></body></html>"); // Handle no history if (transcript.getMessages().size() == 0) { builder.append("<b>" + Res.getString("message.no.history.found") + "</b>"); } window.setText(builder.toString()); } }; TaskEngine.getInstance().schedule(transcriptTask, 10); } }; transcriptLoader.start(); }
diff --git a/src/br/pucrio/inf/learn/structlearning/discriminative/application/sequence/data/SequenceDataset.java b/src/br/pucrio/inf/learn/structlearning/discriminative/application/sequence/data/SequenceDataset.java index 37f41f6..d7635c4 100644 --- a/src/br/pucrio/inf/learn/structlearning/discriminative/application/sequence/data/SequenceDataset.java +++ b/src/br/pucrio/inf/learn/structlearning/discriminative/application/sequence/data/SequenceDataset.java @@ -1,610 +1,610 @@ package br.pucrio.inf.learn.structlearning.discriminative.application.sequence.data; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collection; import java.util.LinkedList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import br.pucrio.inf.learn.structlearning.discriminative.data.Dataset; import br.pucrio.inf.learn.structlearning.discriminative.data.DatasetException; import br.pucrio.inf.learn.structlearning.discriminative.data.encoding.FeatureEncoding; import br.pucrio.inf.learn.structlearning.discriminative.data.encoding.StringMapEncoding; /** * Represent a textual dataset whose examples are sequence of tokens. * * The feature values are stored as integers and are also called feature codes. * Different schema can be used to encode textual feature values to integer * codes by specializing the class <code>FeatureEncoding</code>. The default * feature encoding scheme is <code>StringMapEncoding</code>. It stores an array * of strings and use the index in this array as feature code. A * <code>HashMap</code> stores the inverted index, i.e., efficiently provides * the code of a feature value given its textual representation. * */ public class SequenceDataset implements Dataset { /** * Loging object. */ private static final Log LOG = LogFactory.getLog(SequenceDataset.class); /** * Special code used to indicate non-annotated tokens. */ public static final int NON_ANNOTATED_STATE_CODE = -10; /** * Special code used to indicate unknown token labels. */ public static final int UNKNOWN_STATE_CODE = -20; /** * Special code used to indicate unknown features. */ public static final int UNKNOWN_FEATURE_CODE = -30; /** * Indicate whether this is a training dataset or not. */ protected boolean training; /** * Map string feature values to integer values (codes). */ protected FeatureEncoding<String> featureEncoding; /** * Map string state values to integer values (codes). */ protected FeatureEncoding<String> stateEncoding; /** * Vector of the input-part of the examples. */ protected SequenceInput[] inputSequences; /** * Vector of the output-part of the examples (correct predictions). */ protected SequenceOutput[] outputSequences; /** * Special label that indicates non-annotated tokens. */ protected String nonAnnotatedStateLabel; /** * If <code>true</code>, when loading partially-labeled datasets, skip * examples that do not include any label. */ protected boolean skipCompletelyNonAnnotatedExamples; /** * Store the maximum number of emission features seen in a unique token in * the dataset. */ protected int maxNumberOfEmissionFeatures; /** * Default constructor. */ public SequenceDataset() { this(new StringMapEncoding(), new StringMapEncoding()); } /** * Create a dataset using the given feature-value and state-label encodings. * One can use this constructor to create a dataset compatible with a * previous loaded model, for instance. * * @param featureEncoding * @param stateEncoding */ public SequenceDataset(FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding) { this.featureEncoding = featureEncoding; this.stateEncoding = stateEncoding; this.skipCompletelyNonAnnotatedExamples = false; this.training = false; } public SequenceDataset(FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding, String nonAnnotatedStateLabel) { this.featureEncoding = featureEncoding; this.stateEncoding = stateEncoding; this.nonAnnotatedStateLabel = nonAnnotatedStateLabel; this.skipCompletelyNonAnnotatedExamples = false; this.training = false; } public SequenceDataset(FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding, String nonAnnotatedStateLabel, boolean training) { this.featureEncoding = featureEncoding; this.stateEncoding = stateEncoding; this.nonAnnotatedStateLabel = nonAnnotatedStateLabel; this.skipCompletelyNonAnnotatedExamples = false; this.training = training; } /** * Load the dataset from a file. * * @param fileName * the name of a file to load the dataset. * * @throws DatasetException * @throws IOException */ public SequenceDataset(String fileName) throws IOException, DatasetException { this(new StringMapEncoding(), new StringMapEncoding()); load(fileName); } public SequenceDataset(String fileName, String nonAnnotatedStateLabel) throws IOException, DatasetException { this(new StringMapEncoding(), new StringMapEncoding()); this.nonAnnotatedStateLabel = nonAnnotatedStateLabel; load(fileName); } /** * Load the dataset from a <code>InputStream</code>. * * @param is * @throws IOException * @throws DatasetException */ public SequenceDataset(InputStream is) throws IOException, DatasetException { this(new StringMapEncoding(), new StringMapEncoding()); load(is); } /** * Load the dataset from the given file and use the given feature-value and * state-label encodings. One can use this constructor to load a dataset * compatible with a previous loaded model, for instance. * * @param fileName * name and path of a file. * @param featureEncoding * use a determined feature values encoding. * @param stateEncoding * use a determined state labels encoding. * * @throws IOException * if occurs some problem reading the file. * @throws DatasetException * if the file contains invalid data. */ public SequenceDataset(String fileName, FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding) throws IOException, DatasetException { this(featureEncoding, stateEncoding); load(fileName); } public SequenceDataset(String fileName, FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding, String nonAnnotatedStateLabel) throws IOException, DatasetException { this(featureEncoding, stateEncoding); this.nonAnnotatedStateLabel = nonAnnotatedStateLabel; load(fileName); } public SequenceDataset(String fileName, FeatureEncoding<String> featureEncoding, FeatureEncoding<String> stateEncoding, String nonAnnotatedStateLabel, boolean skipCompletelyNonAnnotatedExamples) throws IOException, DatasetException { this(featureEncoding, stateEncoding); this.nonAnnotatedStateLabel = nonAnnotatedStateLabel; this.skipCompletelyNonAnnotatedExamples = skipCompletelyNonAnnotatedExamples; load(fileName); } @Override public boolean isTraining() { return training; } @Override public int getNumberOfExamples() { return inputSequences.length; } @Override public SequenceInput[] getInputs() { return inputSequences; } @Override public SequenceOutput[] getOutputs() { return outputSequences; } @Override public SequenceInput getInput(int index) { return inputSequences[index]; } @Override public SequenceOutput getOutput(int index) { return outputSequences[index]; } /** * Return the encoding scheme for feature values. * * @return */ public FeatureEncoding<String> getFeatureEncoding() { return featureEncoding; } /** * Return the encoding scheme for state labels. * * @return */ public FeatureEncoding<String> getStateEncoding() { return stateEncoding; } /** * Load a dataset from the given stream. * * @param fileName * the name of a file where to read from the dataset. * * @throws IOException * @throws DatasetException */ public void load(String fileName) throws IOException, DatasetException { BufferedReader reader = new BufferedReader(new FileReader(fileName)); load(reader); reader.close(); } /** * Load a dataset from the given stream. * * @param is * an input stream from where the dataset is loaded. * @throws DatasetException * @throws IOException */ public void load(InputStream is) throws IOException, DatasetException { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); load(reader); } /** * Load a dataset from the given buffered reader. * * @param reader * @throws IOException * @throws DatasetException */ public void load(BufferedReader reader) throws IOException, DatasetException { LinkedList<ArraySequenceInput> inputSequences = new LinkedList<ArraySequenceInput>(); LinkedList<ArraySequenceOutput> outputSequences = new LinkedList<ArraySequenceOutput>(); // Parse each example. int numTotal = 0; int numAdded = 0; String buff; while ((buff = skipBlanksAndComments(reader)) != null) { if (parseExample(inputSequences, outputSequences, buff)) ++numAdded; ++numTotal; } LOG.info("Skipped " + (numTotal - numAdded) + " examples of " + numTotal + " (" + (numTotal - numAdded) * 100d / numTotal + "%)"); this.inputSequences = inputSequences.toArray(new SequenceInput[0]); this.outputSequences = outputSequences.toArray(new SequenceOutput[0]); } /** * Add the examples in the given dataset to this dataset. * * @param other */ public void add(SequenceDataset other) throws DatasetException { if (!featureEncoding.equals(other.featureEncoding) || !stateEncoding.equals(other.stateEncoding)) throw new DatasetException("Different encodings"); // Alloc room to store both datasets (this one and the given one). SequenceInput[] newInputSequences = new SequenceInput[inputSequences.length + other.inputSequences.length]; SequenceOutput[] newOutputSequences = new SequenceOutput[outputSequences.length + other.outputSequences.length]; // Copy (only reference) the examples in this dataset to the new arrays. int idx = 0; for (; idx < inputSequences.length; ++idx) { newInputSequences[idx] = inputSequences[idx]; newOutputSequences[idx] = outputSequences[idx]; } // Copy (only reference) the examples in the given dataset to the new // arrays. for (int idxO = 0; idxO < other.inputSequences.length; ++idxO, ++idx) { newInputSequences[idx] = other.inputSequences[idxO]; newOutputSequences[idx] = other.outputSequences[idxO]; } // Adjust the pointers of this dataset to the new arrays. this.inputSequences = newInputSequences; this.outputSequences = newOutputSequences; } /** * Skip blank lines and lines starting by the comment character #. * * @param reader * @return * @throws IOException */ protected String skipBlanksAndComments(BufferedReader reader) throws IOException { String buff; while ((buff = reader.readLine()) != null) { // Skip empty lines. if (buff.trim().length() == 0) continue; // Skip comment lines. if (buff.startsWith("#")) continue; break; } return buff; } /** * Parse the given string and load an example. * * @param buff * a string that contains an example. * * @return <code>true</code> if the given string is a valid example. * * @throws DatasetException * if there is some format problem with the given string. */ public boolean parseExample(Collection<ArraySequenceInput> sequenceInputs, Collection<ArraySequenceOutput> sequenceOutputs, String buff) throws DatasetException { // Split tokens. String tokens[] = buff.split("\\t"); if (tokens.length == 0) return false; // The first field is the sentence id. String id = tokens[0]; if (id.trim().length() == 0) return false; LinkedList<LinkedList<Integer>> sequenceInputAsList = new LinkedList<LinkedList<Integer>>(); LinkedList<Integer> sequenceOutputAsList = new LinkedList<Integer>(); boolean someAnnotatedToken = false; for (int idxTkn = 1; idxTkn < tokens.length; ++idxTkn) { String token = tokens[idxTkn]; // Parse the token features. int numEmissionFeatures = 0; String[] features = token.split("[ ]"); LinkedList<Integer> featureList = new LinkedList<Integer>(); for (int idxFtr = 0; idxFtr < features.length - 1; ++idxFtr) { ++numEmissionFeatures; - int code = featureEncoding.put(features[idxFtr]); + int code = featureEncoding.put(new String(features[idxFtr])); if (code >= 0) featureList.add(code); } if (numEmissionFeatures > maxNumberOfEmissionFeatures) maxNumberOfEmissionFeatures = numEmissionFeatures; // The last feature is the token label. String label = features[features.length - 1]; if (label.equals(nonAnnotatedStateLabel)) // The label indicates a non-annotated token and then we use the // non-annotated state code, instead of encoding this special // label. Note that the above test always returns false if the // special label is null (totally annotated dataset). sequenceOutputAsList.add(NON_ANNOTATED_STATE_CODE); else { - int code = stateEncoding.put(label); + int code = stateEncoding.put(new String(label)); if (code < 0) LOG.warn("Unknown label (" + label + ") in token " + (idxTkn - 1) + " of example " + id + " is unknown"); sequenceOutputAsList.add(code); someAnnotatedToken = true; } sequenceInputAsList.add(featureList); } // Store the loaded example. if (!skipCompletelyNonAnnotatedExamples || someAnnotatedToken) { if (training) { /* * Training examples must store internally their indexes in the * array of training examples. */ - sequenceInputs.add(new ArraySequenceInput(id, sequenceInputs + sequenceInputs.add(new ArraySequenceInput(new String(id), sequenceInputs .size(), sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } else { - sequenceInputs.add(new ArraySequenceInput(id, + sequenceInputs.add(new ArraySequenceInput(new String(id), sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } return true; } return false; } /** * Save this dataset in the given file. * * @param fileName * name of the file to save this dataset. * * @throws IOException * if some problem occurs when opening or writing to the file. */ public void save(String fileName) throws IOException { PrintStream ps = new PrintStream(fileName); save(ps); ps.close(); } /** * Save the dataset to the given stream. * * @param os * an output stream to where the dataset is saved. */ public void save(PrintStream ps) { for (int idxSequence = 0; idxSequence < getNumberOfExamples(); ++idxSequence) { SequenceInput input = inputSequences[idxSequence]; SequenceOutput output = outputSequences[idxSequence]; // The sentence identifier string. ps.print(input.getId()); for (int token = 0; token < input.size(); ++token) { // Tokens as separated. ps.print("\t"); // Token features. for (int ftr : input.getFeatureCodes(token)) ps.print(featureEncoding.getValueByCode(ftr) + " "); // Label of this token. ps.println(featureEncoding.getValueByCode(output .getLabel(token))); } // Next line for the next sequence. ps.println(); } } /** * Return the number of tokens within the given example index. * * @param idxExample * index of an example. * * @return the number of tokens within the given example index. */ public int getNumberOfTokens(int idxExample) { return inputSequences[idxExample].size(); } /** * Return the number of symbols in the dataset feature-value encoding * object. In general, this corresponds to the total number of different * symbols in the dataset, but can be a different number if the encoding was * used by other code despite this dataset. * * @return */ public int getNumberOfSymbols() { return featureEncoding.size(); } /** * Return the number of different state labels within the dataset * state-label encoding. In general, this corresponds to the total number of * different state labels in the dataset, but can be a different number if * the encoding was used by other code despite this dataset. * * @return */ public int getNumberOfStates() { return stateEncoding.size(); } /** * If set to <code>true</code>, skip examples with no labeled token. * * @param skipCompletelyNonAnnotatedExamples */ public void setSkipCompletelyNonAnnotatedExamples( boolean skipCompletelyNonAnnotatedExamples) { this.skipCompletelyNonAnnotatedExamples = skipCompletelyNonAnnotatedExamples; } /** * Normalize all the input structures within this dataset to have the same * given norm. * * @param norm */ public void normalizeInputStructures(double norm) { for (SequenceInput in : inputSequences) in.normalize(norm); } /** * Return the maximum number of emission features seen in a unique token. * * @return */ public int getMaxNumberOfEmissionFeatures() { return maxNumberOfEmissionFeatures; } /** * Sort feature values of each token to speedup kernel functions * computations. */ public void sortFeatureValues() { for (SequenceInput seq : inputSequences) seq.sortFeatures(); } @Override public void save(BufferedWriter writer) throws IOException, DatasetException { // TODO Auto-generated method stub } @Override public void save(OutputStream os) throws IOException, DatasetException { // TODO Auto-generated method stub } }
false
true
public boolean parseExample(Collection<ArraySequenceInput> sequenceInputs, Collection<ArraySequenceOutput> sequenceOutputs, String buff) throws DatasetException { // Split tokens. String tokens[] = buff.split("\\t"); if (tokens.length == 0) return false; // The first field is the sentence id. String id = tokens[0]; if (id.trim().length() == 0) return false; LinkedList<LinkedList<Integer>> sequenceInputAsList = new LinkedList<LinkedList<Integer>>(); LinkedList<Integer> sequenceOutputAsList = new LinkedList<Integer>(); boolean someAnnotatedToken = false; for (int idxTkn = 1; idxTkn < tokens.length; ++idxTkn) { String token = tokens[idxTkn]; // Parse the token features. int numEmissionFeatures = 0; String[] features = token.split("[ ]"); LinkedList<Integer> featureList = new LinkedList<Integer>(); for (int idxFtr = 0; idxFtr < features.length - 1; ++idxFtr) { ++numEmissionFeatures; int code = featureEncoding.put(features[idxFtr]); if (code >= 0) featureList.add(code); } if (numEmissionFeatures > maxNumberOfEmissionFeatures) maxNumberOfEmissionFeatures = numEmissionFeatures; // The last feature is the token label. String label = features[features.length - 1]; if (label.equals(nonAnnotatedStateLabel)) // The label indicates a non-annotated token and then we use the // non-annotated state code, instead of encoding this special // label. Note that the above test always returns false if the // special label is null (totally annotated dataset). sequenceOutputAsList.add(NON_ANNOTATED_STATE_CODE); else { int code = stateEncoding.put(label); if (code < 0) LOG.warn("Unknown label (" + label + ") in token " + (idxTkn - 1) + " of example " + id + " is unknown"); sequenceOutputAsList.add(code); someAnnotatedToken = true; } sequenceInputAsList.add(featureList); } // Store the loaded example. if (!skipCompletelyNonAnnotatedExamples || someAnnotatedToken) { if (training) { /* * Training examples must store internally their indexes in the * array of training examples. */ sequenceInputs.add(new ArraySequenceInput(id, sequenceInputs .size(), sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } else { sequenceInputs.add(new ArraySequenceInput(id, sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } return true; } return false; }
public boolean parseExample(Collection<ArraySequenceInput> sequenceInputs, Collection<ArraySequenceOutput> sequenceOutputs, String buff) throws DatasetException { // Split tokens. String tokens[] = buff.split("\\t"); if (tokens.length == 0) return false; // The first field is the sentence id. String id = tokens[0]; if (id.trim().length() == 0) return false; LinkedList<LinkedList<Integer>> sequenceInputAsList = new LinkedList<LinkedList<Integer>>(); LinkedList<Integer> sequenceOutputAsList = new LinkedList<Integer>(); boolean someAnnotatedToken = false; for (int idxTkn = 1; idxTkn < tokens.length; ++idxTkn) { String token = tokens[idxTkn]; // Parse the token features. int numEmissionFeatures = 0; String[] features = token.split("[ ]"); LinkedList<Integer> featureList = new LinkedList<Integer>(); for (int idxFtr = 0; idxFtr < features.length - 1; ++idxFtr) { ++numEmissionFeatures; int code = featureEncoding.put(new String(features[idxFtr])); if (code >= 0) featureList.add(code); } if (numEmissionFeatures > maxNumberOfEmissionFeatures) maxNumberOfEmissionFeatures = numEmissionFeatures; // The last feature is the token label. String label = features[features.length - 1]; if (label.equals(nonAnnotatedStateLabel)) // The label indicates a non-annotated token and then we use the // non-annotated state code, instead of encoding this special // label. Note that the above test always returns false if the // special label is null (totally annotated dataset). sequenceOutputAsList.add(NON_ANNOTATED_STATE_CODE); else { int code = stateEncoding.put(new String(label)); if (code < 0) LOG.warn("Unknown label (" + label + ") in token " + (idxTkn - 1) + " of example " + id + " is unknown"); sequenceOutputAsList.add(code); someAnnotatedToken = true; } sequenceInputAsList.add(featureList); } // Store the loaded example. if (!skipCompletelyNonAnnotatedExamples || someAnnotatedToken) { if (training) { /* * Training examples must store internally their indexes in the * array of training examples. */ sequenceInputs.add(new ArraySequenceInput(new String(id), sequenceInputs .size(), sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } else { sequenceInputs.add(new ArraySequenceInput(new String(id), sequenceInputAsList)); sequenceOutputs.add(new ArraySequenceOutput( sequenceOutputAsList, sequenceOutputAsList.size())); } return true; } return false; }
diff --git a/SE/dvbs/app/controllers/LocationController.java b/SE/dvbs/app/controllers/LocationController.java index 52b9dd0..f535cad 100644 --- a/SE/dvbs/app/controllers/LocationController.java +++ b/SE/dvbs/app/controllers/LocationController.java @@ -1,57 +1,57 @@ package controllers; import java.util.List; import javax.persistence.Query; import play.db.jpa.GenericModel.JPAQuery; import play.mvc.Before; import play.mvc.Controller; import play.mvc.With; import models.Author; import models.Location; @With(Secure.class) public class LocationController extends Controller { public static void formEditLocation(String lid) { Location location=Location.findById(Long.parseLong(lid)); render(location); } public static void formAddLocation() { List<Location> allLocations=Location.findAll(); render(allLocations); } public static void addLocation(String name, String zip, String parentId) { // TODO:Autor übergeben (@author alex) Author aut=new Author(); aut.save(); Location newLoc; if(parentId.equals("0")) newLoc = new Location(name, Integer.parseInt(zip), null, aut); else{ - Location parentObj=Location.findById(Integer.parseInt(parentId)); + Location parentObj=Location.findById(Long.parseLong(parentId)); newLoc = new Location(name, Integer.parseInt(zip), parentObj, aut); } newLoc.save(); flash.success("Ort wurde gespeichert."); Application.index(); //Redirect to index } public static void saveLocation(long locId, String name, int zip, Location parent) { // TODO: Autor übergeben Location loc = Location.findById(locId); loc.name = name; loc.zip = zip; loc.parent = parent; } public static void showLocations() { List<Location> allLocations = Location.findAll(); render(allLocations); } }
true
true
public static void addLocation(String name, String zip, String parentId) { // TODO:Autor übergeben (@author alex) Author aut=new Author(); aut.save(); Location newLoc; if(parentId.equals("0")) newLoc = new Location(name, Integer.parseInt(zip), null, aut); else{ Location parentObj=Location.findById(Integer.parseInt(parentId)); newLoc = new Location(name, Integer.parseInt(zip), parentObj, aut); } newLoc.save(); flash.success("Ort wurde gespeichert."); Application.index(); //Redirect to index }
public static void addLocation(String name, String zip, String parentId) { // TODO:Autor übergeben (@author alex) Author aut=new Author(); aut.save(); Location newLoc; if(parentId.equals("0")) newLoc = new Location(name, Integer.parseInt(zip), null, aut); else{ Location parentObj=Location.findById(Long.parseLong(parentId)); newLoc = new Location(name, Integer.parseInt(zip), parentObj, aut); } newLoc.save(); flash.success("Ort wurde gespeichert."); Application.index(); //Redirect to index }
diff --git a/src/main/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactory.java b/src/main/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactory.java index 63a3b4aee44..910481b3049 100644 --- a/src/main/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactory.java +++ b/src/main/java/org/elasticsearch/index/analysis/StemmerTokenFilterFactory.java @@ -1,172 +1,175 @@ /* * Licensed to ElasticSearch and Shay Banon under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. ElasticSearch licenses this * file to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.analysis; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.ar.ArabicStemFilter; import org.apache.lucene.analysis.bg.BulgarianStemFilter; import org.apache.lucene.analysis.br.BrazilianStemFilter; import org.apache.lucene.analysis.cz.CzechStemFilter; import org.apache.lucene.analysis.de.GermanLightStemFilter; import org.apache.lucene.analysis.de.GermanMinimalStemFilter; import org.apache.lucene.analysis.el.GreekStemFilter; import org.apache.lucene.analysis.en.EnglishMinimalStemFilter; import org.apache.lucene.analysis.en.EnglishPossessiveFilter; import org.apache.lucene.analysis.en.KStemFilter; import org.apache.lucene.analysis.en.PorterStemFilter; import org.apache.lucene.analysis.es.SpanishLightStemFilter; import org.apache.lucene.analysis.fi.FinnishLightStemFilter; import org.apache.lucene.analysis.fr.FrenchLightStemFilter; import org.apache.lucene.analysis.fr.FrenchMinimalStemFilter; import org.apache.lucene.analysis.hi.HindiStemFilter; import org.apache.lucene.analysis.hu.HungarianLightStemFilter; import org.apache.lucene.analysis.id.IndonesianStemFilter; import org.apache.lucene.analysis.it.ItalianLightStemFilter; import org.apache.lucene.analysis.lv.LatvianStemFilter; import org.apache.lucene.analysis.no.NorwegianMinimalStemFilter; import org.apache.lucene.analysis.pt.PortugueseLightStemFilter; import org.apache.lucene.analysis.pt.PortugueseMinimalStemFilter; import org.apache.lucene.analysis.pt.PortugueseStemFilter; import org.apache.lucene.analysis.ru.RussianLightStemFilter; import org.apache.lucene.analysis.snowball.SnowballFilter; import org.apache.lucene.analysis.sv.SwedishLightStemFilter; import org.elasticsearch.common.Strings; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.inject.assistedinject.Assisted; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.Index; import org.elasticsearch.index.settings.IndexSettings; import org.tartarus.snowball.ext.*; /** */ public class StemmerTokenFilterFactory extends AbstractTokenFilterFactory { private String language; @Inject public StemmerTokenFilterFactory(Index index, @IndexSettings Settings indexSettings, @Assisted String name, @Assisted Settings settings) { super(index, indexSettings, name, settings); this.language = Strings.capitalize(settings.get("language", settings.get("name", "porter"))); } @Override public TokenStream create(TokenStream tokenStream) { if ("arabic".equalsIgnoreCase(language)) { return new ArabicStemFilter(tokenStream); } else if ("armenian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ArmenianStemmer()); } else if ("basque".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new BasqueStemmer()); } else if ("brazilian".equalsIgnoreCase(language)) { return new BrazilianStemFilter(tokenStream); } else if ("bulgarian".equalsIgnoreCase(language)) { return new BulgarianStemFilter(tokenStream); } else if ("catalan".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new CatalanStemmer()); } else if ("czech".equalsIgnoreCase(language)) { return new CzechStemFilter(tokenStream); } else if ("danish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DanishStemmer()); } else if ("dutch".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DutchStemmer()); } else if ("english".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new EnglishStemmer()); } else if ("finnish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FinnishStemmer()); } else if ("french".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FrenchStemmer()); } else if ("german".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new GermanStemmer()); } else if ("german2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new German2Stemmer()); } else if ("hungarian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new HungarianStemmer()); } else if ("italian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ItalianStemmer()); } else if ("kp".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new KpStemmer()); } else if ("kstem".equalsIgnoreCase(language)) { return new KStemFilter(tokenStream); } else if ("lovins".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new LovinsStemmer()); } else if ("latvian".equalsIgnoreCase(language)) { return new LatvianStemFilter(tokenStream); } else if ("norwegian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new NorwegianStemmer()); } else if ("minimal_norwegian".equalsIgnoreCase(language) || "minimalNorwegian".equals(language)) { return new NorwegianMinimalStemFilter(tokenStream); } else if ("porter".equalsIgnoreCase(language)) { return new PorterStemFilter(tokenStream); } else if ("porter2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PorterStemmer()); } else if ("portuguese".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PortugueseStemmer()); } else if ("romanian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RomanianStemmer()); } else if ("russian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RussianStemmer()); } else if ("spanish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SpanishStemmer()); } else if ("swedish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SwedishStemmer()); } else if ("turkish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new TurkishStemmer()); } else if ("minimal_english".equalsIgnoreCase(language) || "minimalEnglish".equalsIgnoreCase(language)) { return new EnglishMinimalStemFilter(tokenStream); } else if ("possessive_english".equalsIgnoreCase(language) || "possessiveEnglish".equalsIgnoreCase(language)) { return new EnglishPossessiveFilter(version, tokenStream); } else if ("light_finish".equalsIgnoreCase(language) || "lightFinish".equalsIgnoreCase(language)) { + // leaving this for backward compatibility + return new FinnishLightStemFilter(tokenStream); + } else if ("light_finnish".equalsIgnoreCase(language) || "lightFinnish".equalsIgnoreCase(language)) { return new FinnishLightStemFilter(tokenStream); } else if ("light_french".equalsIgnoreCase(language) || "lightFrench".equalsIgnoreCase(language)) { return new FrenchLightStemFilter(tokenStream); } else if ("minimal_french".equalsIgnoreCase(language) || "minimalFrench".equalsIgnoreCase(language)) { return new FrenchMinimalStemFilter(tokenStream); } else if ("light_german".equalsIgnoreCase(language) || "lightGerman".equalsIgnoreCase(language)) { return new GermanLightStemFilter(tokenStream); } else if ("minimal_german".equalsIgnoreCase(language) || "minimalGerman".equalsIgnoreCase(language)) { return new GermanMinimalStemFilter(tokenStream); } else if ("hindi".equalsIgnoreCase(language)) { return new HindiStemFilter(tokenStream); } else if ("light_hungarian".equalsIgnoreCase(language) || "lightHungarian".equalsIgnoreCase(language)) { return new HungarianLightStemFilter(tokenStream); } else if ("indonesian".equalsIgnoreCase(language)) { return new IndonesianStemFilter(tokenStream); } else if ("light_italian".equalsIgnoreCase(language) || "lightItalian".equalsIgnoreCase(language)) { return new ItalianLightStemFilter(tokenStream); } else if ("light_portuguese".equalsIgnoreCase(language) || "lightPortuguese".equalsIgnoreCase(language)) { return new PortugueseLightStemFilter(tokenStream); } else if ("minimal_portuguese".equalsIgnoreCase(language) || "minimalPortuguese".equalsIgnoreCase(language)) { return new PortugueseMinimalStemFilter(tokenStream); } else if ("portuguese".equalsIgnoreCase(language)) { return new PortugueseStemFilter(tokenStream); } else if ("light_russian".equalsIgnoreCase(language) || "lightRussian".equalsIgnoreCase(language)) { return new RussianLightStemFilter(tokenStream); } else if ("light_spanish".equalsIgnoreCase(language) || "lightSpanish".equalsIgnoreCase(language)) { return new SpanishLightStemFilter(tokenStream); } else if ("light_swedish".equalsIgnoreCase(language) || "lightSwedish".equalsIgnoreCase(language)) { return new SwedishLightStemFilter(tokenStream); } else if ("greek".equalsIgnoreCase(language)) { return new GreekStemFilter(tokenStream); } return new SnowballFilter(tokenStream, language); } }
true
true
public TokenStream create(TokenStream tokenStream) { if ("arabic".equalsIgnoreCase(language)) { return new ArabicStemFilter(tokenStream); } else if ("armenian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ArmenianStemmer()); } else if ("basque".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new BasqueStemmer()); } else if ("brazilian".equalsIgnoreCase(language)) { return new BrazilianStemFilter(tokenStream); } else if ("bulgarian".equalsIgnoreCase(language)) { return new BulgarianStemFilter(tokenStream); } else if ("catalan".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new CatalanStemmer()); } else if ("czech".equalsIgnoreCase(language)) { return new CzechStemFilter(tokenStream); } else if ("danish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DanishStemmer()); } else if ("dutch".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DutchStemmer()); } else if ("english".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new EnglishStemmer()); } else if ("finnish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FinnishStemmer()); } else if ("french".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FrenchStemmer()); } else if ("german".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new GermanStemmer()); } else if ("german2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new German2Stemmer()); } else if ("hungarian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new HungarianStemmer()); } else if ("italian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ItalianStemmer()); } else if ("kp".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new KpStemmer()); } else if ("kstem".equalsIgnoreCase(language)) { return new KStemFilter(tokenStream); } else if ("lovins".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new LovinsStemmer()); } else if ("latvian".equalsIgnoreCase(language)) { return new LatvianStemFilter(tokenStream); } else if ("norwegian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new NorwegianStemmer()); } else if ("minimal_norwegian".equalsIgnoreCase(language) || "minimalNorwegian".equals(language)) { return new NorwegianMinimalStemFilter(tokenStream); } else if ("porter".equalsIgnoreCase(language)) { return new PorterStemFilter(tokenStream); } else if ("porter2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PorterStemmer()); } else if ("portuguese".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PortugueseStemmer()); } else if ("romanian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RomanianStemmer()); } else if ("russian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RussianStemmer()); } else if ("spanish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SpanishStemmer()); } else if ("swedish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SwedishStemmer()); } else if ("turkish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new TurkishStemmer()); } else if ("minimal_english".equalsIgnoreCase(language) || "minimalEnglish".equalsIgnoreCase(language)) { return new EnglishMinimalStemFilter(tokenStream); } else if ("possessive_english".equalsIgnoreCase(language) || "possessiveEnglish".equalsIgnoreCase(language)) { return new EnglishPossessiveFilter(version, tokenStream); } else if ("light_finish".equalsIgnoreCase(language) || "lightFinish".equalsIgnoreCase(language)) { return new FinnishLightStemFilter(tokenStream); } else if ("light_french".equalsIgnoreCase(language) || "lightFrench".equalsIgnoreCase(language)) { return new FrenchLightStemFilter(tokenStream); } else if ("minimal_french".equalsIgnoreCase(language) || "minimalFrench".equalsIgnoreCase(language)) { return new FrenchMinimalStemFilter(tokenStream); } else if ("light_german".equalsIgnoreCase(language) || "lightGerman".equalsIgnoreCase(language)) { return new GermanLightStemFilter(tokenStream); } else if ("minimal_german".equalsIgnoreCase(language) || "minimalGerman".equalsIgnoreCase(language)) { return new GermanMinimalStemFilter(tokenStream); } else if ("hindi".equalsIgnoreCase(language)) { return new HindiStemFilter(tokenStream); } else if ("light_hungarian".equalsIgnoreCase(language) || "lightHungarian".equalsIgnoreCase(language)) { return new HungarianLightStemFilter(tokenStream); } else if ("indonesian".equalsIgnoreCase(language)) { return new IndonesianStemFilter(tokenStream); } else if ("light_italian".equalsIgnoreCase(language) || "lightItalian".equalsIgnoreCase(language)) { return new ItalianLightStemFilter(tokenStream); } else if ("light_portuguese".equalsIgnoreCase(language) || "lightPortuguese".equalsIgnoreCase(language)) { return new PortugueseLightStemFilter(tokenStream); } else if ("minimal_portuguese".equalsIgnoreCase(language) || "minimalPortuguese".equalsIgnoreCase(language)) { return new PortugueseMinimalStemFilter(tokenStream); } else if ("portuguese".equalsIgnoreCase(language)) { return new PortugueseStemFilter(tokenStream); } else if ("light_russian".equalsIgnoreCase(language) || "lightRussian".equalsIgnoreCase(language)) { return new RussianLightStemFilter(tokenStream); } else if ("light_spanish".equalsIgnoreCase(language) || "lightSpanish".equalsIgnoreCase(language)) { return new SpanishLightStemFilter(tokenStream); } else if ("light_swedish".equalsIgnoreCase(language) || "lightSwedish".equalsIgnoreCase(language)) { return new SwedishLightStemFilter(tokenStream); } else if ("greek".equalsIgnoreCase(language)) { return new GreekStemFilter(tokenStream); } return new SnowballFilter(tokenStream, language); }
public TokenStream create(TokenStream tokenStream) { if ("arabic".equalsIgnoreCase(language)) { return new ArabicStemFilter(tokenStream); } else if ("armenian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ArmenianStemmer()); } else if ("basque".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new BasqueStemmer()); } else if ("brazilian".equalsIgnoreCase(language)) { return new BrazilianStemFilter(tokenStream); } else if ("bulgarian".equalsIgnoreCase(language)) { return new BulgarianStemFilter(tokenStream); } else if ("catalan".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new CatalanStemmer()); } else if ("czech".equalsIgnoreCase(language)) { return new CzechStemFilter(tokenStream); } else if ("danish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DanishStemmer()); } else if ("dutch".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new DutchStemmer()); } else if ("english".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new EnglishStemmer()); } else if ("finnish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FinnishStemmer()); } else if ("french".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new FrenchStemmer()); } else if ("german".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new GermanStemmer()); } else if ("german2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new German2Stemmer()); } else if ("hungarian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new HungarianStemmer()); } else if ("italian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new ItalianStemmer()); } else if ("kp".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new KpStemmer()); } else if ("kstem".equalsIgnoreCase(language)) { return new KStemFilter(tokenStream); } else if ("lovins".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new LovinsStemmer()); } else if ("latvian".equalsIgnoreCase(language)) { return new LatvianStemFilter(tokenStream); } else if ("norwegian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new NorwegianStemmer()); } else if ("minimal_norwegian".equalsIgnoreCase(language) || "minimalNorwegian".equals(language)) { return new NorwegianMinimalStemFilter(tokenStream); } else if ("porter".equalsIgnoreCase(language)) { return new PorterStemFilter(tokenStream); } else if ("porter2".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PorterStemmer()); } else if ("portuguese".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new PortugueseStemmer()); } else if ("romanian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RomanianStemmer()); } else if ("russian".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new RussianStemmer()); } else if ("spanish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SpanishStemmer()); } else if ("swedish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new SwedishStemmer()); } else if ("turkish".equalsIgnoreCase(language)) { return new SnowballFilter(tokenStream, new TurkishStemmer()); } else if ("minimal_english".equalsIgnoreCase(language) || "minimalEnglish".equalsIgnoreCase(language)) { return new EnglishMinimalStemFilter(tokenStream); } else if ("possessive_english".equalsIgnoreCase(language) || "possessiveEnglish".equalsIgnoreCase(language)) { return new EnglishPossessiveFilter(version, tokenStream); } else if ("light_finish".equalsIgnoreCase(language) || "lightFinish".equalsIgnoreCase(language)) { // leaving this for backward compatibility return new FinnishLightStemFilter(tokenStream); } else if ("light_finnish".equalsIgnoreCase(language) || "lightFinnish".equalsIgnoreCase(language)) { return new FinnishLightStemFilter(tokenStream); } else if ("light_french".equalsIgnoreCase(language) || "lightFrench".equalsIgnoreCase(language)) { return new FrenchLightStemFilter(tokenStream); } else if ("minimal_french".equalsIgnoreCase(language) || "minimalFrench".equalsIgnoreCase(language)) { return new FrenchMinimalStemFilter(tokenStream); } else if ("light_german".equalsIgnoreCase(language) || "lightGerman".equalsIgnoreCase(language)) { return new GermanLightStemFilter(tokenStream); } else if ("minimal_german".equalsIgnoreCase(language) || "minimalGerman".equalsIgnoreCase(language)) { return new GermanMinimalStemFilter(tokenStream); } else if ("hindi".equalsIgnoreCase(language)) { return new HindiStemFilter(tokenStream); } else if ("light_hungarian".equalsIgnoreCase(language) || "lightHungarian".equalsIgnoreCase(language)) { return new HungarianLightStemFilter(tokenStream); } else if ("indonesian".equalsIgnoreCase(language)) { return new IndonesianStemFilter(tokenStream); } else if ("light_italian".equalsIgnoreCase(language) || "lightItalian".equalsIgnoreCase(language)) { return new ItalianLightStemFilter(tokenStream); } else if ("light_portuguese".equalsIgnoreCase(language) || "lightPortuguese".equalsIgnoreCase(language)) { return new PortugueseLightStemFilter(tokenStream); } else if ("minimal_portuguese".equalsIgnoreCase(language) || "minimalPortuguese".equalsIgnoreCase(language)) { return new PortugueseMinimalStemFilter(tokenStream); } else if ("portuguese".equalsIgnoreCase(language)) { return new PortugueseStemFilter(tokenStream); } else if ("light_russian".equalsIgnoreCase(language) || "lightRussian".equalsIgnoreCase(language)) { return new RussianLightStemFilter(tokenStream); } else if ("light_spanish".equalsIgnoreCase(language) || "lightSpanish".equalsIgnoreCase(language)) { return new SpanishLightStemFilter(tokenStream); } else if ("light_swedish".equalsIgnoreCase(language) || "lightSwedish".equalsIgnoreCase(language)) { return new SwedishLightStemFilter(tokenStream); } else if ("greek".equalsIgnoreCase(language)) { return new GreekStemFilter(tokenStream); } return new SnowballFilter(tokenStream, language); }
diff --git a/app/src/processing/app/tools/CreateFont.java b/app/src/processing/app/tools/CreateFont.java index f1d2309c1..d87b00c6d 100644 --- a/app/src/processing/app/tools/CreateFont.java +++ b/app/src/processing/app/tools/CreateFont.java @@ -1,327 +1,330 @@ /* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Processing project - http://processing.org Copyright (c) 2004-06 Ben Fry and Casey Reas Copyright (c) 2001-04 Massachusetts Institute of Technology This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package processing.app.tools; import processing.app.*; import processing.core.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; /** * gui interface to font creation heaven/hell. */ public class CreateFont extends JFrame { File targetFolder; Dimension windowSize; JList fontSelector; //JComboBox styleSelector; JTextField sizeSelector; JCheckBox allBox; JCheckBox smoothBox; JTextArea sample; JButton okButton; JTextField filenameField; Hashtable table; boolean smooth = true; boolean all = false; Font font; String list[]; int selection = -1; //static { //System.out.println("yep yep yep"); //} //static final String styles[] = { //"Plain", "Bold", "Italic", "Bold Italic" //}; public CreateFont(Editor editor) { super("Create Font"); targetFolder = editor.sketch.dataFolder; Container paine = getContentPane(); paine.setLayout(new BorderLayout()); //10, 10)); JPanel pain = new JPanel(); pain.setBorder(new EmptyBorder(13, 13, 13, 13)); paine.add(pain, BorderLayout.CENTER); pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); String labelText = "Use this tool to create bitmap fonts for your program.\n" + "Select a font and size, and click 'OK' to generate the font.\n" + "It will be added to the data folder of the current sketch."; JTextArea textarea = new JTextArea(labelText); textarea.setBorder(new EmptyBorder(10, 10, 20, 10)); textarea.setBackground(null); textarea.setEditable(false); textarea.setHighlighter(null); textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(textarea); // don't care about families starting with . or # // also ignore dialog, dialoginput, monospaced, serif, sansserif // getFontList is deprecated in 1.4, so this has to be used GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font fonts[] = ge.getAllFonts(); String flist[] = new String[fonts.length]; table = new Hashtable(); int index = 0; for (int i = 0; i < fonts.length; i++) { //String psname = fonts[i].getPSName(); //if (psname == null) System.err.println("ps name is null"); flist[index++] = fonts[i].getPSName(); table.put(fonts[i].getPSName(), fonts[i]); } list = new String[index]; System.arraycopy(flist, 0, list, 0, index); fontSelector = new JList(list); fontSelector.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { selection = fontSelector.getSelectedIndex(); okButton.setEnabled(true); update(); } } }); fontSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSelector.setVisibleRowCount(12); JScrollPane fontScroller = new JScrollPane(fontSelector); pain.add(fontScroller); Dimension d1 = new Dimension(13, 13); pain.add(new Box.Filler(d1, d1, d1)); // see http://rinkworks.com/words/pangrams.shtml sample = new JTextArea("The quick brown fox blah blah.") { // Forsaking monastic tradition, twelve jovial friars gave up their // vocation for a questionable existence on the flying trapeze. public void paintComponent(Graphics g) { //System.out.println("disabling aa"); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, smooth ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); super.paintComponent(g2); } }; + // Seems that in some instances, no default font is set + // http://dev.processing.org/bugs/show_bug.cgi?id=777 + sample.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(sample); Dimension d2 = new Dimension(6, 6); pain.add(new Box.Filler(d2, d2, d2)); JPanel panel = new JPanel(); panel.add(new JLabel("Size:")); sizeSelector = new JTextField(" 48 "); sizeSelector.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } public void changedUpdate(DocumentEvent e) { } }); panel.add(sizeSelector); smoothBox = new JCheckBox("Smooth"); smoothBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { smooth = smoothBox.isSelected(); update(); } }); smoothBox.setSelected(smooth); panel.add(smoothBox); allBox = new JCheckBox("All Characters"); allBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { all = allBox.isSelected(); } }); allBox.setSelected(all); panel.add(allBox); pain.add(panel); JPanel filestuff = new JPanel(); filestuff.add(new JLabel("Filename:")); filestuff.add(filenameField = new JTextField(20)); filestuff.add(new JLabel(".vlw")); pain.add(filestuff); JPanel buttons = new JPanel(); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { build(); } }); okButton.setEnabled(false); buttons.add(cancelButton); buttons.add(okButton); pain.add(buttons); JRootPane root = getRootPane(); root.setDefaultButton(okButton); ActionListener disposer = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; Base.registerWindowCloseKeys(root, disposer); Base.setIcon(this); pack(); // do this after pack so it doesn't affect layout sample.setFont(new Font(list[0], Font.PLAIN, 48)); fontSelector.setSelectedIndex(0); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); windowSize = getSize(); setLocation((screen.width - windowSize.width) / 2, (screen.height - windowSize.height) / 2); } /** * make the window vertically resizable */ public Dimension getMaximumSize() { return new Dimension(windowSize.width, 2000); } public Dimension getMinimumSize() { return windowSize; } /* public void show(File targetFolder) { this.targetFolder = targetFolder; show(); } */ public void update() { int fontsize = 0; try { fontsize = Integer.parseInt(sizeSelector.getText().trim()); //System.out.println("'" + sizeSelector.getText() + "'"); } catch (NumberFormatException e2) { } // if a deselect occurred, selection will be -1 if ((fontsize > 0) && (fontsize < 256) && (selection != -1)) { //font = new Font(list[selection], Font.PLAIN, fontsize); Font instance = (Font) table.get(list[selection]); font = instance.deriveFont(Font.PLAIN, fontsize); //System.out.println("setting font to " + font); sample.setFont(font); String filenameSuggestion = list[selection].replace(' ', '_'); filenameSuggestion += "-" + fontsize; filenameField.setText(filenameSuggestion); } } public void build() { int fontsize = 0; try { fontsize = Integer.parseInt(sizeSelector.getText().trim()); } catch (NumberFormatException e) { } if (fontsize <= 0) { JOptionPane.showMessageDialog(this, "Bad font size, try again.", "Badness", JOptionPane.WARNING_MESSAGE); return; } String filename = filenameField.getText(); if (filename.length() == 0) { JOptionPane.showMessageDialog(this, "Enter a file name for the font.", "Lameness", JOptionPane.WARNING_MESSAGE); return; } if (!filename.endsWith(".vlw")) { filename += ".vlw"; } try { Font instance = (Font) table.get(list[selection]); font = instance.deriveFont(Font.PLAIN, fontsize); PFont f = new PFont(font, smooth, all ? null : PFont.DEFAULT_CHARSET); // make sure the 'data' folder exists if (!targetFolder.exists()) targetFolder.mkdirs(); f.save(new FileOutputStream(new File(targetFolder, filename))); } catch (IOException e) { JOptionPane.showMessageDialog(this, "An error occurred while creating font.", "No font for you", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); } setVisible(false); } }
true
true
public CreateFont(Editor editor) { super("Create Font"); targetFolder = editor.sketch.dataFolder; Container paine = getContentPane(); paine.setLayout(new BorderLayout()); //10, 10)); JPanel pain = new JPanel(); pain.setBorder(new EmptyBorder(13, 13, 13, 13)); paine.add(pain, BorderLayout.CENTER); pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); String labelText = "Use this tool to create bitmap fonts for your program.\n" + "Select a font and size, and click 'OK' to generate the font.\n" + "It will be added to the data folder of the current sketch."; JTextArea textarea = new JTextArea(labelText); textarea.setBorder(new EmptyBorder(10, 10, 20, 10)); textarea.setBackground(null); textarea.setEditable(false); textarea.setHighlighter(null); textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(textarea); // don't care about families starting with . or # // also ignore dialog, dialoginput, monospaced, serif, sansserif // getFontList is deprecated in 1.4, so this has to be used GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font fonts[] = ge.getAllFonts(); String flist[] = new String[fonts.length]; table = new Hashtable(); int index = 0; for (int i = 0; i < fonts.length; i++) { //String psname = fonts[i].getPSName(); //if (psname == null) System.err.println("ps name is null"); flist[index++] = fonts[i].getPSName(); table.put(fonts[i].getPSName(), fonts[i]); } list = new String[index]; System.arraycopy(flist, 0, list, 0, index); fontSelector = new JList(list); fontSelector.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { selection = fontSelector.getSelectedIndex(); okButton.setEnabled(true); update(); } } }); fontSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSelector.setVisibleRowCount(12); JScrollPane fontScroller = new JScrollPane(fontSelector); pain.add(fontScroller); Dimension d1 = new Dimension(13, 13); pain.add(new Box.Filler(d1, d1, d1)); // see http://rinkworks.com/words/pangrams.shtml sample = new JTextArea("The quick brown fox blah blah.") { // Forsaking monastic tradition, twelve jovial friars gave up their // vocation for a questionable existence on the flying trapeze. public void paintComponent(Graphics g) { //System.out.println("disabling aa"); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, smooth ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); super.paintComponent(g2); } }; pain.add(sample); Dimension d2 = new Dimension(6, 6); pain.add(new Box.Filler(d2, d2, d2)); JPanel panel = new JPanel(); panel.add(new JLabel("Size:")); sizeSelector = new JTextField(" 48 "); sizeSelector.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } public void changedUpdate(DocumentEvent e) { } }); panel.add(sizeSelector); smoothBox = new JCheckBox("Smooth"); smoothBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { smooth = smoothBox.isSelected(); update(); } }); smoothBox.setSelected(smooth); panel.add(smoothBox); allBox = new JCheckBox("All Characters"); allBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { all = allBox.isSelected(); } }); allBox.setSelected(all); panel.add(allBox); pain.add(panel); JPanel filestuff = new JPanel(); filestuff.add(new JLabel("Filename:")); filestuff.add(filenameField = new JTextField(20)); filestuff.add(new JLabel(".vlw")); pain.add(filestuff); JPanel buttons = new JPanel(); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { build(); } }); okButton.setEnabled(false); buttons.add(cancelButton); buttons.add(okButton); pain.add(buttons); JRootPane root = getRootPane(); root.setDefaultButton(okButton); ActionListener disposer = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; Base.registerWindowCloseKeys(root, disposer); Base.setIcon(this); pack(); // do this after pack so it doesn't affect layout sample.setFont(new Font(list[0], Font.PLAIN, 48)); fontSelector.setSelectedIndex(0); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); windowSize = getSize(); setLocation((screen.width - windowSize.width) / 2, (screen.height - windowSize.height) / 2); }
public CreateFont(Editor editor) { super("Create Font"); targetFolder = editor.sketch.dataFolder; Container paine = getContentPane(); paine.setLayout(new BorderLayout()); //10, 10)); JPanel pain = new JPanel(); pain.setBorder(new EmptyBorder(13, 13, 13, 13)); paine.add(pain, BorderLayout.CENTER); pain.setLayout(new BoxLayout(pain, BoxLayout.Y_AXIS)); String labelText = "Use this tool to create bitmap fonts for your program.\n" + "Select a font and size, and click 'OK' to generate the font.\n" + "It will be added to the data folder of the current sketch."; JTextArea textarea = new JTextArea(labelText); textarea.setBorder(new EmptyBorder(10, 10, 20, 10)); textarea.setBackground(null); textarea.setEditable(false); textarea.setHighlighter(null); textarea.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(textarea); // don't care about families starting with . or # // also ignore dialog, dialoginput, monospaced, serif, sansserif // getFontList is deprecated in 1.4, so this has to be used GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Font fonts[] = ge.getAllFonts(); String flist[] = new String[fonts.length]; table = new Hashtable(); int index = 0; for (int i = 0; i < fonts.length; i++) { //String psname = fonts[i].getPSName(); //if (psname == null) System.err.println("ps name is null"); flist[index++] = fonts[i].getPSName(); table.put(fonts[i].getPSName(), fonts[i]); } list = new String[index]; System.arraycopy(flist, 0, list, 0, index); fontSelector = new JList(list); fontSelector.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() == false) { selection = fontSelector.getSelectedIndex(); okButton.setEnabled(true); update(); } } }); fontSelector.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); fontSelector.setVisibleRowCount(12); JScrollPane fontScroller = new JScrollPane(fontSelector); pain.add(fontScroller); Dimension d1 = new Dimension(13, 13); pain.add(new Box.Filler(d1, d1, d1)); // see http://rinkworks.com/words/pangrams.shtml sample = new JTextArea("The quick brown fox blah blah.") { // Forsaking monastic tradition, twelve jovial friars gave up their // vocation for a questionable existence on the flying trapeze. public void paintComponent(Graphics g) { //System.out.println("disabling aa"); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, smooth ? RenderingHints.VALUE_TEXT_ANTIALIAS_ON : RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); super.paintComponent(g2); } }; // Seems that in some instances, no default font is set // http://dev.processing.org/bugs/show_bug.cgi?id=777 sample.setFont(new Font("Dialog", Font.PLAIN, 12)); pain.add(sample); Dimension d2 = new Dimension(6, 6); pain.add(new Box.Filler(d2, d2, d2)); JPanel panel = new JPanel(); panel.add(new JLabel("Size:")); sizeSelector = new JTextField(" 48 "); sizeSelector.getDocument().addDocumentListener(new DocumentListener() { public void insertUpdate(DocumentEvent e) { update(); } public void removeUpdate(DocumentEvent e) { update(); } public void changedUpdate(DocumentEvent e) { } }); panel.add(sizeSelector); smoothBox = new JCheckBox("Smooth"); smoothBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { smooth = smoothBox.isSelected(); update(); } }); smoothBox.setSelected(smooth); panel.add(smoothBox); allBox = new JCheckBox("All Characters"); allBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { all = allBox.isSelected(); } }); allBox.setSelected(all); panel.add(allBox); pain.add(panel); JPanel filestuff = new JPanel(); filestuff.add(new JLabel("Filename:")); filestuff.add(filenameField = new JTextField(20)); filestuff.add(new JLabel(".vlw")); pain.add(filestuff); JPanel buttons = new JPanel(); JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); } }); okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { build(); } }); okButton.setEnabled(false); buttons.add(cancelButton); buttons.add(okButton); pain.add(buttons); JRootPane root = getRootPane(); root.setDefaultButton(okButton); ActionListener disposer = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { setVisible(false); } }; Base.registerWindowCloseKeys(root, disposer); Base.setIcon(this); pack(); // do this after pack so it doesn't affect layout sample.setFont(new Font(list[0], Font.PLAIN, 48)); fontSelector.setSelectedIndex(0); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); windowSize = getSize(); setLocation((screen.width - windowSize.width) / 2, (screen.height - windowSize.height) / 2); }
diff --git a/tests/java/fr/isima/ponge/wsprotocol/timed/constraints/parser/GrammarTestCase.java b/tests/java/fr/isima/ponge/wsprotocol/timed/constraints/parser/GrammarTestCase.java index 110aecf..7724449 100644 --- a/tests/java/fr/isima/ponge/wsprotocol/timed/constraints/parser/GrammarTestCase.java +++ b/tests/java/fr/isima/ponge/wsprotocol/timed/constraints/parser/GrammarTestCase.java @@ -1,68 +1,72 @@ /* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at LICENSE.txt * or at http://www.opensource.org/licenses/cddl1.php. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at LICENSE.txt. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2006 Julien Ponge. All rights reserved. * Use is subject to license terms. */ package fr.isima.ponge.wsprotocol.timed.constraints.parser; import java.io.StringReader; import fr.isima.ponge.wsprotocol.timed.constraints.IConstraintNode; import antlr.CommonAST; import junit.framework.TestCase; public class GrammarTestCase extends TestCase { public void testGrammar() { - // TODO: add failure cases, and M-Invoke non-valid input such as M-Invoke(T1 < 3) String[] input = { "C-Invoke((((T1 < 5) && (T2 >= 10)) || (T3 = 7)))", - "C-Invoke((T1< 3) && (T2 >=5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)" }; + "C-Invoke((T1< 3) && (T2 >=5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)", + "M-Invoke(T1 = 3)", "M-Invoke(T1 < 3)"}; String[] output = { "C-Invoke(((T1 < 5) && (T2 >= 10)) || (T3 = 7))", - "C-Invoke((T1 < 3) && (T2 >= 5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)" }; + "C-Invoke((T1 < 3) && (T2 >= 5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)", + "M-Invoke(T1 = 3)", null}; TemporalConstraintTreeWalker walker = new TemporalConstraintTreeWalker(); for (int i = 0; i < input.length; ++i) { try { TemporalConstraintLexer lexer = new TemporalConstraintLexer(new StringReader( input[i])); TemporalConstraintParser parser = new TemporalConstraintParser(lexer); parser.constraint(); CommonAST tree = (CommonAST) parser.getAST(); IConstraintNode constraint = walker.constraint(tree); TestCase.assertEquals(output[i], constraint.toString()); } catch (Exception e) { - TestCase.fail(); + if (output[i] != null) + { + TestCase.fail(); + } } } } }
false
true
public void testGrammar() { // TODO: add failure cases, and M-Invoke non-valid input such as M-Invoke(T1 < 3) String[] input = { "C-Invoke((((T1 < 5) && (T2 >= 10)) || (T3 = 7)))", "C-Invoke((T1< 3) && (T2 >=5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)" }; String[] output = { "C-Invoke(((T1 < 5) && (T2 >= 10)) || (T3 = 7))", "C-Invoke((T1 < 3) && (T2 >= 5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)" }; TemporalConstraintTreeWalker walker = new TemporalConstraintTreeWalker(); for (int i = 0; i < input.length; ++i) { try { TemporalConstraintLexer lexer = new TemporalConstraintLexer(new StringReader( input[i])); TemporalConstraintParser parser = new TemporalConstraintParser(lexer); parser.constraint(); CommonAST tree = (CommonAST) parser.getAST(); IConstraintNode constraint = walker.constraint(tree); TestCase.assertEquals(output[i], constraint.toString()); } catch (Exception e) { TestCase.fail(); } } }
public void testGrammar() { String[] input = { "C-Invoke((((T1 < 5) && (T2 >= 10)) || (T3 = 7)))", "C-Invoke((T1< 3) && (T2 >=5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)", "M-Invoke(T1 = 3)", "M-Invoke(T1 < 3)"}; String[] output = { "C-Invoke(((T1 < 5) && (T2 >= 10)) || (T3 = 7))", "C-Invoke((T1 < 3) && (T2 >= 5))", "M-Invoke(T1 = 3)", "C-Invoke(T1 < 3)", "M-Invoke(T1 = 3)", null}; TemporalConstraintTreeWalker walker = new TemporalConstraintTreeWalker(); for (int i = 0; i < input.length; ++i) { try { TemporalConstraintLexer lexer = new TemporalConstraintLexer(new StringReader( input[i])); TemporalConstraintParser parser = new TemporalConstraintParser(lexer); parser.constraint(); CommonAST tree = (CommonAST) parser.getAST(); IConstraintNode constraint = walker.constraint(tree); TestCase.assertEquals(output[i], constraint.toString()); } catch (Exception e) { if (output[i] != null) { TestCase.fail(); } } } }
diff --git a/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewCodeGenerate.java b/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewCodeGenerate.java index 0eb711e1..c5b5ea96 100644 --- a/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewCodeGenerate.java +++ b/javafx.editor/src/org/netbeans/modules/javafx/preview/PreviewCodeGenerate.java @@ -1,114 +1,116 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common * Development and Distribution License("CDDL") (collectively, the * "License"). You may not use this file except in compliance with the * License. You can obtain a copy of the License at * http://www.netbeans.org/cddl-gplv2.html * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the * specific language governing permissions and limitations under the * License. When distributing the software, include this License Header * Notice in each file and include the License file at * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the * License Header, with the fields enclosed by brackets [] replaced by * your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * * If you wish your version of this file to be governed by only the CDDL * or only the GPL Version 2, indicate your decision by adding * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." If you do not indicate a * single choice of license, a recipient has the option to distribute * your version of this file under either the CDDL, the GPL Version 2 or * to extend the choice of license to its licensees as provided above. * However, if you add GPL Version 2 code and therefore, elected the GPL * Version 2 license, then the option applies only if the new code is * made subject to such option by the copyright holder. * * Contributor(s): * * Portions Copyrighted 2008 Sun Microsystems, Inc. */ package org.netbeans.modules.javafx.preview; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.tools.JavaFileObject; import org.netbeans.api.java.classpath.ClassPath; import org.netbeans.api.javafx.source.CancellableTask; import org.netbeans.api.javafx.source.ClassOutputBuffer; import org.netbeans.api.javafx.source.CompilationInfo; import org.netbeans.modules.javafx.editor.JavaFXDocument; import org.netbeans.modules.javafx.preview.CodeUtils.Context; import org.openide.cookies.EditorCookie; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileStateInvalidException; import org.openide.loaders.DataObject; import org.openide.util.Exceptions; public class PreviewCodeGenerate implements CancellableTask<CompilationInfo> { private FileObject file; private AtomicBoolean cancel = new AtomicBoolean(); public PreviewCodeGenerate(FileObject file) { this.file = file; } public void cancel() { cancel.set(true); } public void run(CompilationInfo info) throws Exception { cancel.set(false); process(info); } public static void process(CompilationInfo info) throws ClassNotFoundException, Exception { FileObject fo = info.getFileObject(); DataObject od = DataObject.find(fo); EditorCookie ec = od.getCookie(EditorCookie.class); JavaFXDocument doc = (JavaFXDocument) ec.openDocument(); if (doc.executionAllowed()) { - Map<String, byte[]> classBytes = new HashMap<String, byte[]>(); - if (classBytes != null) { + if (info.getClassBytes() != null) { + Map<String, byte[]> classBytes = new HashMap<String, byte[]>(); for (JavaFileObject jfo : info.getClassBytes()) { - classBytes.put(((ClassOutputBuffer)jfo).getBinaryName(), ((ClassOutputBuffer)jfo).getClassBytes()); + byte[] cb = ((ClassOutputBuffer)jfo).getClassBytes(); + if (cb != null) + classBytes.put(((ClassOutputBuffer)jfo).getBinaryName(), cb); } ClassPath sourceCP = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClassPath compileCP = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath executeCP = ClassPath.getClassPath(fo, ClassPath.EXECUTE); ClassPath bootCP = ClassPath.getClassPath(fo, ClassPath.BOOT); String className = sourceCP.getResourceName(info.getFileObject(), '.', false); // NOI18N String fileName = fo.getNameExt(); final PreviewSideServerFace previewSideServerFace = Bridge.getPreview(doc); if (previewSideServerFace != null) previewSideServerFace.run(new Context(classBytes, className, fileName, toURLs(sourceCP), toURLs(executeCP), toURLs(bootCP))); } } } private static URL[] toURLs(ClassPath classPath) { URL urls[] = new URL[classPath.getRoots().length]; for (int j = 0; j < classPath.getRoots().length; j++) try { urls[j] = classPath.getRoots()[j].getURL(); } catch (FileStateInvalidException ex) { Exceptions.printStackTrace(ex); } return urls; } }
false
true
public static void process(CompilationInfo info) throws ClassNotFoundException, Exception { FileObject fo = info.getFileObject(); DataObject od = DataObject.find(fo); EditorCookie ec = od.getCookie(EditorCookie.class); JavaFXDocument doc = (JavaFXDocument) ec.openDocument(); if (doc.executionAllowed()) { Map<String, byte[]> classBytes = new HashMap<String, byte[]>(); if (classBytes != null) { for (JavaFileObject jfo : info.getClassBytes()) { classBytes.put(((ClassOutputBuffer)jfo).getBinaryName(), ((ClassOutputBuffer)jfo).getClassBytes()); } ClassPath sourceCP = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClassPath compileCP = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath executeCP = ClassPath.getClassPath(fo, ClassPath.EXECUTE); ClassPath bootCP = ClassPath.getClassPath(fo, ClassPath.BOOT); String className = sourceCP.getResourceName(info.getFileObject(), '.', false); // NOI18N String fileName = fo.getNameExt(); final PreviewSideServerFace previewSideServerFace = Bridge.getPreview(doc); if (previewSideServerFace != null) previewSideServerFace.run(new Context(classBytes, className, fileName, toURLs(sourceCP), toURLs(executeCP), toURLs(bootCP))); } } }
public static void process(CompilationInfo info) throws ClassNotFoundException, Exception { FileObject fo = info.getFileObject(); DataObject od = DataObject.find(fo); EditorCookie ec = od.getCookie(EditorCookie.class); JavaFXDocument doc = (JavaFXDocument) ec.openDocument(); if (doc.executionAllowed()) { if (info.getClassBytes() != null) { Map<String, byte[]> classBytes = new HashMap<String, byte[]>(); for (JavaFileObject jfo : info.getClassBytes()) { byte[] cb = ((ClassOutputBuffer)jfo).getClassBytes(); if (cb != null) classBytes.put(((ClassOutputBuffer)jfo).getBinaryName(), cb); } ClassPath sourceCP = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClassPath compileCP = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath executeCP = ClassPath.getClassPath(fo, ClassPath.EXECUTE); ClassPath bootCP = ClassPath.getClassPath(fo, ClassPath.BOOT); String className = sourceCP.getResourceName(info.getFileObject(), '.', false); // NOI18N String fileName = fo.getNameExt(); final PreviewSideServerFace previewSideServerFace = Bridge.getPreview(doc); if (previewSideServerFace != null) previewSideServerFace.run(new Context(classBytes, className, fileName, toURLs(sourceCP), toURLs(executeCP), toURLs(bootCP))); } } }
diff --git a/srcj/com/sun/electric/tool/io/GDSLayers.java b/srcj/com/sun/electric/tool/io/GDSLayers.java index b406448a3..b3d608c03 100644 --- a/srcj/com/sun/electric/tool/io/GDSLayers.java +++ b/srcj/com/sun/electric/tool/io/GDSLayers.java @@ -1,148 +1,149 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: GDSLayers.java * Input/output tool: GDS layer parsing * Written by Steven M. Rubin, Sun Microsystems. * * Copyright (c) 2005 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.io; import com.sun.electric.database.text.ArrayIterator; import com.sun.electric.database.text.TextUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Class to define GDS layer information. */ public class GDSLayers { public static final GDSLayers EMPTY = new GDSLayers(Collections.<Integer>emptyList(), -1, -1); private final Integer[] normalLayers; private final int pinLayer; private final int textLayer; public GDSLayers(List<Integer> normalLayers, int pinLayer, int textLayer) { this.normalLayers = normalLayers.toArray(new Integer[normalLayers.size()]); this.pinLayer = pinLayer; this.textLayer = textLayer; } public int getNumLayers() { return normalLayers.length; } public Iterator<Integer> getLayers() { return ArrayIterator.iterator(normalLayers); } public Integer getFirstLayer() { if (normalLayers.length == 0) return Integer.valueOf(0); return normalLayers[0]; } public int getPinLayer() { return pinLayer; } public int getTextLayer() { return textLayer; } /** * Method to determine if the numbers in this GDSLayers are the same as another. * @param other the other GDSLayers being compared with this. * @return true if they have the same values. */ public boolean equals(GDSLayers other) { if (pinLayer != other.pinLayer) return false; if (textLayer != other.textLayer) return false; return Arrays.equals(normalLayers, other.normalLayers); } @Override public String toString() { String s = ""; for (Integer layVal: normalLayers) { int layNum = layVal.intValue() & 0xFFFF; int layType = (layVal.intValue() >> 16) & 0xFFFF; s += Integer.toString(layNum); if (layType != 0) s += "/" + layType; } if (pinLayer != -1) { s += "," + (pinLayer & 0xFFFF); int pinType = (pinLayer >> 16) & 0xFFFF; if (pinType != 0) s += "/" + pinType; s += "p"; } if (textLayer != -1) { s += "," + (textLayer & 0xFFFF); int textType = (textLayer >> 16) & 0xFFFF; if (textType != 0) s += "/" + textType; s += "t"; } return s; } /** * Method to parse the GDS layer string and get the layer numbers and types (plain, text, and pin). * @param string the GDS layer string, of the form [NUM[/TYP]]*[,NUM[/TYP]t][,NUM[/TYP]p] * @return a GDSLayers object with the values filled-in. */ public static GDSLayers parseLayerString(String string) { ArrayList<Integer> normalLayers = new ArrayList<Integer>(); int pinLayer = -1; int textLayer = -1; for(;;) { String trimmed = string.trim(); if (trimmed.length() == 0) break; int slashPos = trimmed.indexOf('/'); int endPos = trimmed.indexOf(','); if (endPos < 0) endPos = trimmed.length(); int number = TextUtils.atoi(trimmed); if (number != 0 || trimmed.equals("0")) { int type = 0; if (slashPos >= 0 && slashPos < endPos) type = TextUtils.atoi(trimmed.substring(slashPos+1)); char lastCh = trimmed.charAt(endPos-1); if (lastCh == 't') { textLayer = number | (type << 16); } else if (lastCh == 'p') { pinLayer = number | (type << 16); } else { Integer normalLayer = new Integer(number | (type << 16)); normalLayers.add(normalLayer); } if (endPos == trimmed.length()) break; } - string = trimmed.substring(endPos+1); + if (endPos < trimmed.length()) endPos++; + string = trimmed.substring(endPos); } if (normalLayers.isEmpty() && pinLayer == -1 && textLayer == -1) return EMPTY; return new GDSLayers(normalLayers, pinLayer, textLayer); } }
true
true
public static GDSLayers parseLayerString(String string) { ArrayList<Integer> normalLayers = new ArrayList<Integer>(); int pinLayer = -1; int textLayer = -1; for(;;) { String trimmed = string.trim(); if (trimmed.length() == 0) break; int slashPos = trimmed.indexOf('/'); int endPos = trimmed.indexOf(','); if (endPos < 0) endPos = trimmed.length(); int number = TextUtils.atoi(trimmed); if (number != 0 || trimmed.equals("0")) { int type = 0; if (slashPos >= 0 && slashPos < endPos) type = TextUtils.atoi(trimmed.substring(slashPos+1)); char lastCh = trimmed.charAt(endPos-1); if (lastCh == 't') { textLayer = number | (type << 16); } else if (lastCh == 'p') { pinLayer = number | (type << 16); } else { Integer normalLayer = new Integer(number | (type << 16)); normalLayers.add(normalLayer); } if (endPos == trimmed.length()) break; } string = trimmed.substring(endPos+1); } if (normalLayers.isEmpty() && pinLayer == -1 && textLayer == -1) return EMPTY; return new GDSLayers(normalLayers, pinLayer, textLayer); }
public static GDSLayers parseLayerString(String string) { ArrayList<Integer> normalLayers = new ArrayList<Integer>(); int pinLayer = -1; int textLayer = -1; for(;;) { String trimmed = string.trim(); if (trimmed.length() == 0) break; int slashPos = trimmed.indexOf('/'); int endPos = trimmed.indexOf(','); if (endPos < 0) endPos = trimmed.length(); int number = TextUtils.atoi(trimmed); if (number != 0 || trimmed.equals("0")) { int type = 0; if (slashPos >= 0 && slashPos < endPos) type = TextUtils.atoi(trimmed.substring(slashPos+1)); char lastCh = trimmed.charAt(endPos-1); if (lastCh == 't') { textLayer = number | (type << 16); } else if (lastCh == 'p') { pinLayer = number | (type << 16); } else { Integer normalLayer = new Integer(number | (type << 16)); normalLayers.add(normalLayer); } if (endPos == trimmed.length()) break; } if (endPos < trimmed.length()) endPos++; string = trimmed.substring(endPos); } if (normalLayers.isEmpty() && pinLayer == -1 && textLayer == -1) return EMPTY; return new GDSLayers(normalLayers, pinLayer, textLayer); }
diff --git a/src/CustomOreGen/mod_CustomOreGen.java b/src/CustomOreGen/mod_CustomOreGen.java index cc5add8..230a67b 100644 --- a/src/CustomOreGen/mod_CustomOreGen.java +++ b/src/CustomOreGen/mod_CustomOreGen.java @@ -1,248 +1,248 @@ package CustomOreGen; import java.util.Iterator; import java.util.Random; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.NetClientHandler; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.NetServerHandler; import net.minecraft.network.packet.Packet250CustomPayload; import net.minecraft.network.packet.Packet3Chat; import net.minecraft.server.MinecraftServer; import net.minecraft.src.BaseMod; import net.minecraft.src.ModLoader; import net.minecraft.world.World; import net.minecraft.world.storage.WorldInfo; import CustomOreGen.CustomPacketPayload.PayloadType; import CustomOreGen.Client.ClientState; import CustomOreGen.Client.ClientState.WireframeRenderMode; import CustomOreGen.Server.ServerState; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class mod_CustomOreGen extends BaseMod { public String getVersion() { return "@VERSION@"; } public String getPriorities() { return "after:*;"; } public void load() { if (!CustomOreGenBase.hasFML()) { CustomOreGenBase.log = ModLoader.getLogger(); } if (!CustomOreGenBase.hasFML()) { ModLoader.setInGameHook(this, true, false); } CustomPacketPayload.registerChannels(this); } public void modsLoaded() { CustomOreGenBase.onModPostLoad(); boolean found = false; String failMods = null; for (BaseMod mod : ModLoader.getLoadedMods()) { if (mod == this) { found = true; } else if (found && mod != null) { failMods = (failMods == null ? "" : failMods + ", ") + mod.getName(); } } if (failMods == null) { CustomOreGenBase.log.finer("Confirmed that CustomOreGen has precedence during world generation"); } else { CustomOreGenBase.log.warning("The following mods force ModLoader to load them *after* CustomOreGen: " + failMods + ". Distributions may not behave as expected if they (1) target custom biomes from or (2) replace ores placed by these mods."); } } public void generateSurface(World world, Random rand, int blockX, int blockZ) { if (!CustomOreGenBase.hasFML()) { ServerState.checkIfServerChanged(MinecraftServer.getServer(), world.getWorldInfo()); ServerState.onPopulateChunk(world, rand, blockX / 16, blockZ / 16); } } public void generateNether(World world, Random rand, int blockX, int blockZ) { this.generateSurface(world, rand, blockX, blockZ); } @SideOnly(Side.CLIENT) public boolean onTickInGame(float partialTick, Minecraft minecraft) { if (CustomOreGenBase.hasFML()) { return false; } else { Minecraft mc = Minecraft.getMinecraft(); if (mc.isSingleplayer()) { ServerState.checkIfServerChanged(MinecraftServer.getServer(), (WorldInfo)null); } if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld)) { ClientState.onWorldChanged(mc.theWorld); } return true; } } @SideOnly(Side.CLIENT) public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet) { Minecraft mc = Minecraft.getMinecraft(); if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld)) { ClientState.onWorldChanged(mc.theWorld); } CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet); if (payload != null) { switch (payload.type) { case DebuggingGeometryData: ClientState.addDebuggingGeometry((GeometryData)payload.data); break; case DebuggingGeometryRenderMode: String strMode = (String)payload.data; if ("_DISABLE_".equals(strMode)) { ClientState.dgEnabled = false; return; } if (!CustomOreGenBase.hasForge()) { - handler.handleChat(new Packet3Chat("\u00a7cWarning: Minecraft Forge must be installed to view wireframes.")); + handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\"")); return; } if (strMode != null) { WireframeRenderMode idx = null; for (WireframeRenderMode mode : WireframeRenderMode.values()) { if (mode.name().equalsIgnoreCase(strMode)) { idx = mode; break; } } if (idx != null) { ClientState.dgRenderingMode = idx; } else { - handler.handleChat(new Packet3Chat("\u00a7cError: Invalid wireframe mode \'" + strMode + "\'")); + handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\"")); } } else { int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal(); var11 = (var11 + 1) % WireframeRenderMode.values().length; ClientState.dgRenderingMode = WireframeRenderMode.values()[var11]; } - handler.handleChat(new Packet3Chat("COG Client wireframe mode: " + ClientState.dgRenderingMode.name())); + handler.handleChat(new Packet3Chat("{text: \"COG Client wireframe mode: " + ClientState.dgRenderingMode.name() + "\"}")); break; case DebuggingGeometryReset: ClientState.clearDebuggingGeometry(); break; case MystcraftSymbolData: if (!mc.isSingleplayer()) { ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data); } break; case CommandResponse: mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data); break; default: throw new RuntimeException("Unhandled client packet type " + payload.type); } } } public void serverCustomPayload(NetServerHandler handler, Packet250CustomPayload packet) { World handlerWorld = handler.playerEntity == null ? null : handler.playerEntity.worldObj; ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo()); CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet); if (payload != null) { switch (payload.type) { case DebuggingGeometryRequest: GeometryData geometryData = null; if (handler.getPlayer().mcServer.getConfigurationManager().areCommandsAllowed(handler.getPlayer().username)) { geometryData = ServerState.getDebuggingGeometryData((GeometryRequestData)payload.data); } if (geometryData == null) { (new CustomPacketPayload(PayloadType.DebuggingGeometryRenderMode, "_DISABLE_")).sendToClient(handler); } else { (new CustomPacketPayload(PayloadType.DebuggingGeometryData, geometryData)).sendToClient(handler); } break; default: throw new RuntimeException("Unhandled server packet type " + payload.type); } } } public void onClientLogin(net.minecraft.entity.player.EntityPlayer player) { World handlerWorld = player == null ? null : player.worldObj; ServerState.checkIfServerChanged(MinecraftServer.getServer(), handlerWorld == null ? null : handlerWorld.getWorldInfo()); if (player != null) { ServerState.onClientLogin((EntityPlayerMP)player); } } }
false
true
public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet) { Minecraft mc = Minecraft.getMinecraft(); if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld)) { ClientState.onWorldChanged(mc.theWorld); } CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet); if (payload != null) { switch (payload.type) { case DebuggingGeometryData: ClientState.addDebuggingGeometry((GeometryData)payload.data); break; case DebuggingGeometryRenderMode: String strMode = (String)payload.data; if ("_DISABLE_".equals(strMode)) { ClientState.dgEnabled = false; return; } if (!CustomOreGenBase.hasForge()) { handler.handleChat(new Packet3Chat("\u00a7cWarning: Minecraft Forge must be installed to view wireframes.")); return; } if (strMode != null) { WireframeRenderMode idx = null; for (WireframeRenderMode mode : WireframeRenderMode.values()) { if (mode.name().equalsIgnoreCase(strMode)) { idx = mode; break; } } if (idx != null) { ClientState.dgRenderingMode = idx; } else { handler.handleChat(new Packet3Chat("\u00a7cError: Invalid wireframe mode \'" + strMode + "\'")); } } else { int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal(); var11 = (var11 + 1) % WireframeRenderMode.values().length; ClientState.dgRenderingMode = WireframeRenderMode.values()[var11]; } handler.handleChat(new Packet3Chat("COG Client wireframe mode: " + ClientState.dgRenderingMode.name())); break; case DebuggingGeometryReset: ClientState.clearDebuggingGeometry(); break; case MystcraftSymbolData: if (!mc.isSingleplayer()) { ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data); } break; case CommandResponse: mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data); break; default: throw new RuntimeException("Unhandled client packet type " + payload.type); } } }
public void clientCustomPayload(NetClientHandler handler, Packet250CustomPayload packet) { Minecraft mc = Minecraft.getMinecraft(); if (mc.theWorld != null && ClientState.hasWorldChanged(mc.theWorld)) { ClientState.onWorldChanged(mc.theWorld); } CustomPacketPayload payload = CustomPacketPayload.decodePacket(packet); if (payload != null) { switch (payload.type) { case DebuggingGeometryData: ClientState.addDebuggingGeometry((GeometryData)payload.data); break; case DebuggingGeometryRenderMode: String strMode = (String)payload.data; if ("_DISABLE_".equals(strMode)) { ClientState.dgEnabled = false; return; } if (!CustomOreGenBase.hasForge()) { handler.handleChat(new Packet3Chat("{text: \"\u00a7cWarning: Minecraft Forge must be installed to view wireframes.\"")); return; } if (strMode != null) { WireframeRenderMode idx = null; for (WireframeRenderMode mode : WireframeRenderMode.values()) { if (mode.name().equalsIgnoreCase(strMode)) { idx = mode; break; } } if (idx != null) { ClientState.dgRenderingMode = idx; } else { handler.handleChat(new Packet3Chat("{text: \"\u00a7cError: Invalid wireframe mode \'" + strMode + "\'\"")); } } else { int var11 = ClientState.dgRenderingMode == null ? 0 : ClientState.dgRenderingMode.ordinal(); var11 = (var11 + 1) % WireframeRenderMode.values().length; ClientState.dgRenderingMode = WireframeRenderMode.values()[var11]; } handler.handleChat(new Packet3Chat("{text: \"COG Client wireframe mode: " + ClientState.dgRenderingMode.name() + "\"}")); break; case DebuggingGeometryReset: ClientState.clearDebuggingGeometry(); break; case MystcraftSymbolData: if (!mc.isSingleplayer()) { ClientState.addMystcraftSymbol((MystcraftSymbolData)payload.data); } break; case CommandResponse: mc.ingameGUI.getChatGUI().printChatMessage((String)payload.data); break; default: throw new RuntimeException("Unhandled client packet type " + payload.type); } } }
diff --git a/hale/eu.esdihumboldt.hale.schemaprovider/src/eu/esdihumboldt/hale/schemaprovider/provider/ApacheSchemaProvider.java b/hale/eu.esdihumboldt.hale.schemaprovider/src/eu/esdihumboldt/hale/schemaprovider/provider/ApacheSchemaProvider.java index dc074ab01..bf8337f04 100644 --- a/hale/eu.esdihumboldt.hale.schemaprovider/src/eu/esdihumboldt/hale/schemaprovider/provider/ApacheSchemaProvider.java +++ b/hale/eu.esdihumboldt.hale.schemaprovider/src/eu/esdihumboldt/hale/schemaprovider/provider/ApacheSchemaProvider.java @@ -1,940 +1,940 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to this website: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to : http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2010. * * Component : HALE * Created on : Jun 3, 2009 -- 4:50:10 PM */ package eu.esdihumboldt.hale.schemaprovider.provider; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import javax.xml.namespace.QName; import javax.xml.transform.stream.StreamSource; import org.apache.ws.commons.schema.XmlSchema; import org.apache.ws.commons.schema.XmlSchemaAttribute; import org.apache.ws.commons.schema.XmlSchemaChoice; import org.apache.ws.commons.schema.XmlSchemaCollection; import org.apache.ws.commons.schema.XmlSchemaComplexContentExtension; import org.apache.ws.commons.schema.XmlSchemaComplexType; import org.apache.ws.commons.schema.XmlSchemaContent; import org.apache.ws.commons.schema.XmlSchemaContentModel; import org.apache.ws.commons.schema.XmlSchemaElement; import org.apache.ws.commons.schema.XmlSchemaExternal; import org.apache.ws.commons.schema.XmlSchemaInclude; import org.apache.ws.commons.schema.XmlSchemaObject; import org.apache.ws.commons.schema.XmlSchemaObjectCollection; import org.apache.ws.commons.schema.XmlSchemaParticle; import org.apache.ws.commons.schema.XmlSchemaSequence; import org.apache.ws.commons.schema.XmlSchemaSimpleContentExtension; import org.apache.ws.commons.schema.XmlSchemaSimpleType; import org.apache.ws.commons.schema.resolver.DefaultURIResolver; import org.apache.ws.commons.schema.resolver.URIResolver; import org.geotools.feature.NameImpl; import org.opengis.feature.type.AttributeType; import org.opengis.feature.type.FeatureType; import org.opengis.feature.type.Name; import de.cs3d.util.logging.AGroup; import de.cs3d.util.logging.AGroupFactory; import de.cs3d.util.logging.ALogger; import de.cs3d.util.logging.ALoggerFactory; import eu.esdihumboldt.hale.schemaprovider.AbstractSchemaProvider; import eu.esdihumboldt.hale.schemaprovider.HumboldtURIResolver; import eu.esdihumboldt.hale.schemaprovider.LogProgressIndicator; import eu.esdihumboldt.hale.schemaprovider.ProgressIndicator; import eu.esdihumboldt.hale.schemaprovider.Schema; import eu.esdihumboldt.hale.schemaprovider.SchemaProvider; import eu.esdihumboldt.hale.schemaprovider.model.AnonymousType; import eu.esdihumboldt.hale.schemaprovider.model.AttributeDefinition; import eu.esdihumboldt.hale.schemaprovider.model.SchemaElement; import eu.esdihumboldt.hale.schemaprovider.model.TypeDefinition; import eu.esdihumboldt.hale.schemaprovider.provider.internal.DependencyOrderedList; import eu.esdihumboldt.hale.schemaprovider.provider.internal.SchemaResult; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.AbstractElementAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.DefaultAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.DefaultResolveAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.ElementReferenceAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.ProgressURIResolver; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.SchemaAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.SchemaTypeAttribute; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.SchemaTypeResolver; import eu.esdihumboldt.hale.schemaprovider.provider.internal.apache.TypeUtil; /** * The main functionality of this class is to load an XML schema file (XSD) * and create a FeatureType collection. This implementation is based on the * Apache XmlSchema library (http://ws.apache.org/commons/XmlSchema/). It is * necessary use this library instead of the GeoTools Xml schema loader, because * the GeoTools version cannot handle GML 3.2 based files. * * @author Bernd Schneiders, Logica; Thorsten Reitz, Fraunhofer IGD; * Simon Templer, Fraunhofer IGD * @version $Id$ */ public class ApacheSchemaProvider extends AbstractSchemaProvider { /** * The log */ private static ALogger _log = ALoggerFactory.getLogger(ApacheSchemaProvider.class); private static final AGroup NO_DEFINITION = AGroupFactory.getGroup("No type definition found for elements"); /** * Default constructor */ public ApacheSchemaProvider() { super(); addSupportedFormat("xsd"); addSupportedFormat("gml"); addSupportedFormat("xml"); } /** * Extracts attribute definitions from a {@link XmlSchemaParticle}. * * @param elements local element definitions * @param importedElements imported element definitions * @param typeDef the definition of the declaring type * @param particle the particle * @param schemaTypes the schema types * * @return the list of attribute definitions */ private List<AttributeDefinition> getAttributesFromParticle(Map<Name, SchemaElement> elements, Map<Name, SchemaElement> importedElements, TypeDefinition typeDef, XmlSchemaParticle particle, SchemaTypeResolver schemaTypes) { List<AttributeDefinition> attributeResults = new ArrayList<AttributeDefinition>(); // particle: if (particle instanceof XmlSchemaSequence) { // <sequence> XmlSchemaSequence sequence = (XmlSchemaSequence)particle; for (int j = 0; j < sequence.getItems().getCount(); j++) { XmlSchemaObject object = sequence.getItems().getItem(j); if (object instanceof XmlSchemaElement) { // <element> AbstractElementAttribute attribute = getAttributeFromElement( (XmlSchemaElement) object, typeDef, elements, importedElements, schemaTypes); if (attribute != null) { attributeResults.add(attribute); } // </element> } } // </sequence> } else if (particle instanceof XmlSchemaChoice) { //FIXME how to correctly deal with this? for now we add all choices // <choice> XmlSchemaChoice choice = (XmlSchemaChoice) particle; for (int j = 0; j < choice.getItems().getCount(); j++) { XmlSchemaObject object = choice.getItems().getItem(j); if (object instanceof XmlSchemaElement) { // <element> AbstractElementAttribute attribute = getAttributeFromElement( (XmlSchemaElement) object, typeDef, elements, importedElements, schemaTypes); if (attribute != null) { attribute.setNillable(true); //XXX set nillable because its a choice attributeResults.add(attribute); } // </element> } } // </choice> } return attributeResults; } /** * Get an attribute from an element * * @param element the schema element * @param declaringType the definition of the declaring type * @param elements local element definitions * @param importedElements imported element definitions * @param schemaTypes the schema types * * @return an attribute definition or <code>null</code> */ private AbstractElementAttribute getAttributeFromElement( XmlSchemaElement element, TypeDefinition declaringType, Map<Name, SchemaElement> elements, Map<Name, SchemaElement> importedElements, SchemaTypeResolver schemaTypes) { if (element.getSchemaTypeName() != null) { // element referencing a type // <element name="ELEMENT_NAME" type="SCHEMA_TYPE_NAME" /> return new SchemaAttribute( declaringType, element.getName(), new NameImpl(element.getSchemaTypeName().getNamespaceURI(), element.getSchemaTypeName().getLocalPart()), element, schemaTypes); } else if (element.getRefName() != null) { // references another element // <element ref="REF_NAME" /> Name elementName = new NameImpl( element.getRefName().getNamespaceURI(), element.getRefName().getLocalPart()); // local element definition SchemaElement reference = elements.get(elementName); if (reference == null) { // imported element definition reference = importedElements.get(elementName); } if (reference == null) { _log.warn("Reference to element " + element.getRefName().getNamespaceURI() + "/" + element.getRefName().getLocalPart() +" not found"); return null; } else { return new ElementReferenceAttribute( declaringType, element.getName(), reference.getTypeName(), element, reference); } } else if (element.getSchemaType() != null) { // element w/o type or ref if (element.getSchemaType() instanceof XmlSchemaComplexType) { // <element ...> // <complexType> XmlSchemaComplexType complexType = (XmlSchemaComplexType) element.getSchemaType(); XmlSchemaContentModel model = complexType.getContentModel(); XmlSchemaParticle particle = complexType.getParticle(); if (model != null) { XmlSchemaContent content = model.getContent(); QName qname = null; if (content instanceof XmlSchemaComplexContentExtension) { // <complexContent> // <extension base="..."> qname = ((XmlSchemaComplexContentExtension)content).getBaseTypeName(); if (declaringType != null) { Name superTypeName = new NameImpl(qname.getNamespaceURI(), qname.getLocalPart()); // try to get the type definition of the super type TypeDefinition superType = TypeUtil.resolveAttributeType(superTypeName, schemaTypes); if (superType == null) { _log.error("Couldn't resolve super type: " + superTypeName.getNamespaceURI() + "/" + superTypeName.getLocalPart()); } // create an anonymous type that extends the super type Name anonymousName = new NameImpl(declaringType.getIdentifier() + "/" + element.getName(), superTypeName.getLocalPart() + "Extension"); TypeDefinition anonymousType = new AnonymousType(anonymousName, null, superType, (schemaTypes != null)?(schemaTypes.getSchemaLocation()):(null)); // add attributes to the anonymous type // adding the attributes will happen automatically when the AbstractSchemaAttribute is created getAttributes(elements, importedElements, anonymousType, complexType, schemaTypes); // add the anonymous type to the type map - needed for type resolution in SchemaAttribute // it's enough for it to be added to the imported types map if (schemaTypes != null) { schemaTypes.getImportedTypes().put(anonymousName, anonymousType); } // create an attribute with the anonymous type SchemaAttribute result = new SchemaAttribute(declaringType, element.getName(), anonymousName, element, schemaTypes); return result; } // </extension> // </complexContent> } else if (content instanceof XmlSchemaSimpleContentExtension) { // <simpleContent> // <extension base="..."> qname = ((XmlSchemaSimpleContentExtension)content).getBaseTypeName(); if (declaringType != null) { // create an anonymous type that extends the type referenced by qname // with additional attributes Name superTypeName = new NameImpl(qname.getNamespaceURI(), qname.getLocalPart()); // try to get the type definition of the super type TypeDefinition superType = TypeUtil.resolveAttributeType(superTypeName, schemaTypes); if (superType == null) { _log.error("Couldn't resolve super type: " + superTypeName.getNamespaceURI() + "/" + superTypeName.getLocalPart()); } // create an anonymous type that extends the super type Name anonymousName = new NameImpl(declaringType.getIdentifier() + "/" + element.getName(), superTypeName.getLocalPart() + "Extension"); // for now use the super attribute type, because attributes aren't added as attribute descriptors AttributeType attributeType = superType.getType(null); TypeDefinition anonymousType = new AnonymousType(anonymousName, attributeType, superType, (schemaTypes != null)?(schemaTypes.getSchemaLocation()):(null)); // add attributes to the anonymous type // adding the attributes will happen automatically when the AbstractSchemaAttribute is created getAttributes(elements, importedElements, anonymousType, complexType, schemaTypes); // add the anonymous type to the type map - needed for type resolution in SchemaAttribute // it's enough for it to be added to the imported types map if (schemaTypes != null) { schemaTypes.getImportedTypes().put(anonymousName, anonymousType); } // create an attribute with the anonymous type SchemaAttribute result = new SchemaAttribute(declaringType, element.getName(), anonymousName, element, schemaTypes); return result; } // </extension> // </simpleContent> } if (qname != null) { // return base type for dependency resolution return new SchemaAttribute( declaringType, element.getName(), new NameImpl(qname.getNamespaceURI(), qname.getLocalPart()), element, schemaTypes); } else { return null; } } else if (particle != null) { // this where we get when there is an anonymous complex type as property type if (declaringType == null) { // called only to get the type name for dependency resolution - not needed for anonymous types return null; } else { // create an anonymous type Name anonymousName = new NameImpl(declaringType.getIdentifier() + "/" + element.getName(), "AnonymousType"); TypeDefinition anonymousType = new AnonymousType(anonymousName, null, null, (schemaTypes != null)?(schemaTypes.getSchemaLocation()):(null)); // add attributes to the anonymous type // adding the attributes will happen automatically when the AbstractSchemaAttribute is created getAttributes(elements, importedElements, anonymousType, complexType, schemaTypes); // add the anonymous type to the type map - needed for type resolution in SchemaAttribute // it's enough for it to be added to the imported types map if (schemaTypes != null) { schemaTypes.getImportedTypes().put(anonymousName, anonymousType); } // create an attribute with the anonymous type SchemaAttribute result = new SchemaAttribute(declaringType, element.getName(), anonymousName, element, schemaTypes); return result; } } // </complexType> // </element> } else if (element.getSchemaType() instanceof XmlSchemaSimpleType) { // simple schema type TypeDefinition type = TypeUtil.resolveSimpleType(null, (XmlSchemaSimpleType) element.getSchemaType(), schemaTypes); if (type != null) { return new SchemaTypeAttribute( declaringType, element.getName(), element, type); } else { _log.error("Could not resolve type for element " + element.getName()); } } } return null; } /** * Find a super type name based on a complex type * * @param item the complex type defining a super type * * @return the name of the super type or <code>null</code> */ private Name getSuperTypeName(XmlSchemaComplexType item) { Name superType = null; XmlSchemaContentModel model = item.getContentModel(); if (model != null ) { XmlSchemaContent content = model.getContent(); if (content instanceof XmlSchemaComplexContentExtension) { if (((XmlSchemaComplexContentExtension)content).getBaseTypeName() != null) { superType = new NameImpl( ((XmlSchemaComplexContentExtension)content).getBaseTypeName().getNamespaceURI(), ((XmlSchemaComplexContentExtension)content).getBaseTypeName().getLocalPart()); } } else if (content instanceof XmlSchemaSimpleContentExtension) { if (((XmlSchemaSimpleContentExtension)content).getBaseTypeName() != null) { superType = new NameImpl( ((XmlSchemaSimpleContentExtension)content).getBaseTypeName().getNamespaceURI(), ((XmlSchemaSimpleContentExtension)content).getBaseTypeName().getLocalPart()); } } } return superType; } /** * @see SchemaProvider#loadSchema(java.net.URI, ProgressIndicator) */ public Schema loadSchema(URI location, ProgressIndicator progress) throws IOException { if (progress == null) { progress = new LogProgressIndicator(); } // use XML Schema to load schema with all its subschema to the memory InputStream is = null; URL locationURL; locationURL = location.toURL(); is = locationURL.openStream(); progress.setCurrentTask("Loading schema"); XmlSchema schema = null; XmlSchemaCollection schemaCol = new XmlSchemaCollection(); // Check if the file is located on web if (location.getHost() == null) { schemaCol.setSchemaResolver(new ProgressURIResolver(new HumboldtURIResolver(), progress)); schemaCol.setBaseUri(findBaseUri(location)); } else if (location.getScheme().equals("bundleresource")) { schemaCol.setSchemaResolver(new ProgressURIResolver(new HumboldtURIResolver(), progress)); schemaCol.setBaseUri(findBaseUri(location) + "/"); } else { URIResolver resolver = schemaCol.getSchemaResolver(); schemaCol.setSchemaResolver(new ProgressURIResolver((resolver == null)?(new DefaultURIResolver()):(resolver), progress)); } schema = schemaCol.read(new StreamSource(is), null); is.close(); String namespace = schema.getTargetNamespace(); if (namespace == null || namespace.isEmpty()) { // default to gml schema namespace = "http://www.opengis.net/gml"; } schema.setSourceURI(location.toString()); HashMap<String, SchemaResult> imports = new HashMap<String, SchemaResult>(); imports.put(location.toString(), null); SchemaResult schemaResult = loadSchema(location.toString(), schema, imports, progress); Map<String, SchemaElement> elements = new HashMap<String, SchemaElement>(); for (SchemaElement element : schemaResult.getElements().values()) { if (element.getType() != null) { if (element.getType().isComplexType()) { elements.put(element.getIdentifier(), element); } } else { _log.warn(NO_DEFINITION, "No type definition for element " + element.getElementName().getLocalPart()); } } return new Schema(elements, namespace, locationURL); } /** * Load the feature types defined by the given schema * * @param schemaLocation the schema location * @param schema the schema * @param imports the imports/includes that were already * loaded or where loading has been started * @param progress the progress indicator * @return the map of feature type names and types */ protected SchemaResult loadSchema(String schemaLocation, XmlSchema schema, Map<String, SchemaResult> imports, ProgressIndicator progress) { String namespace = schema.getTargetNamespace(); if (namespace == null || namespace.isEmpty()) { // default to gml schema namespace = "http://www.opengis.net/gml"; } // Map of type names / types for the result Map<Name, TypeDefinition> featureTypes = new HashMap<Name, TypeDefinition>(); // name mapping: element name -> type name Map<Name, SchemaElement> elements = new HashMap<Name, SchemaElement>(); // result SchemaResult result = new SchemaResult(featureTypes, elements); // type names for type definitions where is no element Set<String> schemaTypeNames = new HashSet<String>(); // the schema items XmlSchemaObjectCollection items = schema.getItems(); // first pass - find names for types for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); if (item instanceof XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement) item; // retrieve local name part of XmlSchemaElement and of // XmlSchemaComplexType to substitute name later on. Name typeName = null; if (element.getSchemaTypeName() != null) { typeName = new NameImpl( element.getSchemaTypeName().getNamespaceURI(), element.getSchemaTypeName().getLocalPart()); } else if (element.getQName() != null) { typeName = new NameImpl( element.getQName().getNamespaceURI(), element.getQName().getLocalPart()); } Name elementName = new NameImpl(namespace, element.getName()); // create schema element SchemaElement schemaElement = new SchemaElement(elementName, typeName, null); schemaElement.setLocation(schemaLocation); // get description String description = SchemaAttribute.getDescription(element); schemaElement.setDescription(description); // store element in map elements.put(elementName, schemaElement); } else if (item instanceof XmlSchemaComplexType) { schemaTypeNames.add(((XmlSchemaComplexType)item).getName()); } else if (item instanceof XmlSchemaSimpleType) { schemaTypeNames.add(((XmlSchemaSimpleType)item).getName()); } } // Set of include locations Set<String> includes = new HashSet<String>(); // handle imports XmlSchemaObjectCollection externalItems = schema.getIncludes(); if (externalItems.getCount() > 0) { _log.info("Loading includes and imports for schema at " + schemaLocation); } // add self to imports (allows resolving references to elements that are defined here) imports.put(schemaLocation, result); for (int i = 0; i < externalItems.getCount(); i++) { try { XmlSchemaExternal imp = (XmlSchemaExternal) externalItems.getItem(i); XmlSchema importedSchema = imp.getSchema(); String location = importedSchema.getSourceURI(); if (!(imports.containsKey(location))) { // only add schemas that were not already added imports.put(location, null); // place a marker in the map to prevent loading the location in the call to loadSchema imports.put(location, loadSchema(location, importedSchema, imports, progress)); } if (imp instanceof XmlSchemaInclude) { includes.add(location); } } catch (Throwable e) { _log.error("Error adding imported schema", e); } } _log.info("Creating types for schema at " + schemaLocation); progress.setCurrentTask("Analyzing schema " + namespace); // map for all imported types Map<Name, TypeDefinition> importedFeatureTypes = new HashMap<Name, TypeDefinition>(); // name mapping for imported types: element name -> type name Map<Name, SchemaElement> importedElements = new HashMap<Name, SchemaElement>(); // add imported types for (Entry<String, SchemaResult> entry : imports.entrySet()) { if (entry.getValue() != null) { if (includes.contains(entry.getKey())) { // is include, add to result featureTypes.putAll(entry.getValue().getTypes()); elements.putAll(entry.getValue().getElements()); } else { // is import, don't add to result importedFeatureTypes.putAll(entry.getValue().getTypes()); importedElements.putAll(entry.getValue().getElements()); } } } // schema type resolver combining the informations for resolving types SchemaTypeResolver typeResolver = new SchemaTypeResolver(featureTypes, importedFeatureTypes, schemaLocation); // Map of type names to definitions Map<Name, XmlSchemaObject> typeDefinitions = new HashMap<Name, XmlSchemaObject>(); // Dependency map for building the dependency list Map<Name, Set<Name>> dependencies = new HashMap<Name, Set<Name>>(); // 2nd pass - determine dependencies for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); String name = null; Set<Name> typeDependencies = null; // the type dependencies including the super type Name superTypeName = null; // the super type name if (item instanceof XmlSchemaComplexType) { name = ((XmlSchemaComplexType)item).getName(); // get the attribute type names typeDependencies = getAttributeTypeNames(elements, importedElements, (XmlSchemaComplexType) item); // get the name of the super type superTypeName = getSuperTypeName((XmlSchemaComplexType)item); if (superTypeName != null) { typeDependencies.add(superTypeName); } } else if (item instanceof XmlSchemaSimpleType) { name = ((XmlSchemaSimpleType)item).getName(); // union/list referencing dependencies typeDependencies = TypeUtil.getSimpleTypeDependencies(new NameImpl(namespace, name), (XmlSchemaSimpleType) item); } // if the item is a type we remember the type definition and determine its local dependencies if (name != null) { // determine the real type name Name typeName = new NameImpl(namespace, name); // determine the local dependency set Set<Name> localDependencies = new HashSet<Name>(); if (typeDependencies != null) { for (Name dependency : typeDependencies) { if (dependency.getNamespaceURI().equals(namespace) && ((!featureTypes.containsKey(dependency) && referencesType(elements, dependency)) || schemaTypeNames.contains(dependency.getLocalPart()))) { // local type, add to local dependencies localDependencies.add(dependency); } } } // add imported super types to the result set Name importName = superTypeName; TypeDefinition importType = null; while (importName != null && (importType = importedFeatureTypes.get(importName)) != null) { featureTypes.put(importName, importType); TypeDefinition superType = importType.getSuperType(); if (superType != null) { importName = superType.getName(); } else { importName = null; } } // remember type definition typeDefinitions.put(typeName, item); // store local dependencies in dependency map dependencies.put(typeName, localDependencies); } } // create dependency ordered list DependencyOrderedList<Name> typeNames = new DependencyOrderedList<Name>(dependencies); // 3rd pass: create feature types for (Name typeName : typeNames.getItems()) { XmlSchemaObject item = typeDefinitions.get(typeName); if (item == null) { _log.error("No definition for " + typeName.toString()); } else if (item instanceof XmlSchemaSimpleType) { // attribute type from simple schema types TypeDefinition simpleType = TypeUtil.resolveSimpleType( typeName, (XmlSchemaSimpleType) item, typeResolver); if (simpleType != null) { // create a simple type featureTypes.put(typeName, simpleType); } else { - _log.error("No attribute type generated for simple type " + typeName.toString()); + _log.warn("No attribute type generated for simple type " + typeName.toString()); } } else if (item instanceof XmlSchemaComplexType) { // determine the super type name Name superTypeName = getSuperTypeName((XmlSchemaComplexType) item); TypeDefinition superType = null; if (superTypeName != null) { // find super type superType = TypeUtil.resolveAttributeType(superTypeName, typeResolver); // create empty super type if it was not found if (superType == null) { superType = new TypeDefinition(superTypeName, null, null); superType.setLocation("Empty type generated by HALE"); superType.setAbstract(true); // add super type to feature map featureTypes.put(superTypeName, superType); } } // create type definition TypeDefinition typeDef = new TypeDefinition(typeName, null, superType); typeDef.setLocation(schemaLocation); // determine the defined attributes and add them to the declaring type List<AttributeDefinition> attributes = getAttributes( elements, importedElements, typeDef, // definition of the declaring type (XmlSchemaComplexType) item, typeResolver); // reuse the super type's attribute type where appropriate if (superType != null && superType.isAttributeTypeSet()) { // determine if any new elements have been added in the subtype boolean reuseBinding = true; // special case: super type is AbstractFeatureType but no FeatureType instance if (superType.isFeatureType() && !(superType.getType(null) instanceof FeatureType)) { reuseBinding = false; } Iterator<AttributeDefinition> it = attributes.iterator(); while (reuseBinding && it.hasNext()) { if (it.next().isElement()) { reuseBinding = false; } } if (reuseBinding) { // reuse attribute type typeDef.setType(superType.getType(null)); } } // set additional properties typeDef.setAbstract(((XmlSchemaComplexType) item).isAbstract()); // add type definition featureTypes.put(typeName, typeDef); } } // populate schema items with type definitions for (SchemaElement element : elements.values()) { TypeDefinition elementDef = featureTypes.get(element.getTypeName()); if (elementDef != null) { element.setType(elementDef); } else { elementDef = element.getType(); if (elementDef == null) { elementDef = TypeUtil.resolveAttributeType(element.getTypeName(), typeResolver); //TypeUtil.getXSType(element.getTypeName()); } if (elementDef == null) { //_log.warn("Couldn't find definition for element " + element.getDisplayName()); } else { element.setType(elementDef); } } } return result; } private boolean referencesType(Map<Name, SchemaElement> elements, Name dependency) { //elements.containsValue(dependency) //TODO //XXX for now, return false return false; } /** * Get the attributes for the given item * * @param elements map of element names to type names * @param importedElements map of element names to imported type names * @param typeDef the definition of the declaring type * @param item the complex type item * @param schemaTypes the schema types * * @return the attributes as a list of {@link SchemaAttribute}s */ private List<AttributeDefinition> getAttributes(Map<Name, SchemaElement> elements, Map<Name, SchemaElement> importedElements, TypeDefinition typeDef, XmlSchemaComplexType item, SchemaTypeResolver schemaTypes) { ArrayList<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); // item: // <complexType ...> XmlSchemaContentModel model = item.getContentModel(); if (model != null ) { XmlSchemaContent content = model.getContent(); if (content instanceof XmlSchemaComplexContentExtension) { // <complexContent> // <extension base="..."> XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension) content; // particle (e.g. sequence) if (extension.getParticle() != null) { XmlSchemaParticle particle = extension.getParticle(); attributes.addAll(getAttributesFromParticle(elements, importedElements, typeDef, particle, schemaTypes)); } // attributes XmlSchemaObjectCollection attributeCollection = extension.getAttributes(); if (attributeCollection != null) { attributes.addAll(getAttributesFromCollection(attributeCollection, typeDef, schemaTypes)); } // </extension> // </complexContent> } else if (content instanceof XmlSchemaSimpleContentExtension) { // <simpleContent> // <extension base="..."> XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension) content; // attributes XmlSchemaObjectCollection attributeCollection = extension.getAttributes(); if (attributeCollection != null) { attributes.addAll(getAttributesFromCollection(attributeCollection, typeDef, schemaTypes)); } // </extension> // </simpleContent> } } else if (item.getParticle() != null) { // no complex content (instead e.g. <sequence>) XmlSchemaComplexType complexType = item; // particle (e.g. sequence) XmlSchemaParticle particle = complexType.getParticle(); List<AttributeDefinition> tmp = getAttributesFromParticle(elements, importedElements, typeDef, particle, schemaTypes); if (tmp != null) { attributes.addAll(tmp); } // attributes XmlSchemaObjectCollection attributeCollection = complexType.getAttributes(); if (attributeCollection != null) { attributes.addAll(getAttributesFromCollection(attributeCollection, typeDef, schemaTypes)); } } return attributes; // </complexType> } private Collection<AttributeDefinition> getAttributesFromCollection( XmlSchemaObjectCollection attributeCollection, TypeDefinition declaringType, SchemaTypeResolver schemaTypes) { List<AttributeDefinition> attributeResults = new ArrayList<AttributeDefinition>(); for (int index = 0; index < attributeCollection.getCount(); index++) { XmlSchemaObject object = attributeCollection.getItem(index); if (object instanceof XmlSchemaAttribute) { // <attribute ... /> XmlSchemaAttribute attribute = (XmlSchemaAttribute) object; // create attributes QName typeName = attribute.getSchemaTypeName(); if (typeName != null) { attributeResults.add(new DefaultResolveAttribute( declaringType, new NameImpl(typeName.getNamespaceURI(), typeName.getLocalPart()), attribute, schemaTypes)); } else if (attribute.getSchemaType() != null) { if (declaringType != null) { QName name = attribute.getSchemaType().getQName(); Name attributeTypeName = (name != null)? (new NameImpl(name.getNamespaceURI(), name.getLocalPart())): (new NameImpl(declaringType.getName().getNamespaceURI() + "/" + declaringType.getName().getLocalPart(), "AnonymousAttribute" + index)); TypeDefinition attributeType = TypeUtil.resolveSimpleType( attributeTypeName, attribute.getSchemaType(), schemaTypes); attributeResults.add(new DefaultAttribute(declaringType, attributeTypeName, attribute, attributeType)); } } } } return attributeResults; } /** * Get the attributes type names for the given item * * @param elementTypeMap map of element names to type names * @param importedElementTypeMap map of element names to imported type names * @param item the complex type item * @return the attribute type names */ private Set<Name> getAttributeTypeNames(Map<Name, SchemaElement> elementTypeMap, Map<Name, SchemaElement> importedElementTypeMap, XmlSchemaComplexType item) { List<AttributeDefinition> attributes = getAttributes(elementTypeMap, importedElementTypeMap, null, item, null); Set<Name> typeNames = new HashSet<Name>(); for (AttributeDefinition def : attributes) { typeNames.add(def.getTypeName()); } return typeNames; } /** * Get the base URI for the given URI * * @param uri the URI * * @return the base URI as string */ private String findBaseUri(URI uri) { String baseUri = ""; baseUri = uri.toString(); if (baseUri.matches("^.*?\\/.+")) { baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")); } _log.info("Base URI for schemas to be used: " + baseUri); return baseUri; } }
true
true
protected SchemaResult loadSchema(String schemaLocation, XmlSchema schema, Map<String, SchemaResult> imports, ProgressIndicator progress) { String namespace = schema.getTargetNamespace(); if (namespace == null || namespace.isEmpty()) { // default to gml schema namespace = "http://www.opengis.net/gml"; } // Map of type names / types for the result Map<Name, TypeDefinition> featureTypes = new HashMap<Name, TypeDefinition>(); // name mapping: element name -> type name Map<Name, SchemaElement> elements = new HashMap<Name, SchemaElement>(); // result SchemaResult result = new SchemaResult(featureTypes, elements); // type names for type definitions where is no element Set<String> schemaTypeNames = new HashSet<String>(); // the schema items XmlSchemaObjectCollection items = schema.getItems(); // first pass - find names for types for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); if (item instanceof XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement) item; // retrieve local name part of XmlSchemaElement and of // XmlSchemaComplexType to substitute name later on. Name typeName = null; if (element.getSchemaTypeName() != null) { typeName = new NameImpl( element.getSchemaTypeName().getNamespaceURI(), element.getSchemaTypeName().getLocalPart()); } else if (element.getQName() != null) { typeName = new NameImpl( element.getQName().getNamespaceURI(), element.getQName().getLocalPart()); } Name elementName = new NameImpl(namespace, element.getName()); // create schema element SchemaElement schemaElement = new SchemaElement(elementName, typeName, null); schemaElement.setLocation(schemaLocation); // get description String description = SchemaAttribute.getDescription(element); schemaElement.setDescription(description); // store element in map elements.put(elementName, schemaElement); } else if (item instanceof XmlSchemaComplexType) { schemaTypeNames.add(((XmlSchemaComplexType)item).getName()); } else if (item instanceof XmlSchemaSimpleType) { schemaTypeNames.add(((XmlSchemaSimpleType)item).getName()); } } // Set of include locations Set<String> includes = new HashSet<String>(); // handle imports XmlSchemaObjectCollection externalItems = schema.getIncludes(); if (externalItems.getCount() > 0) { _log.info("Loading includes and imports for schema at " + schemaLocation); } // add self to imports (allows resolving references to elements that are defined here) imports.put(schemaLocation, result); for (int i = 0; i < externalItems.getCount(); i++) { try { XmlSchemaExternal imp = (XmlSchemaExternal) externalItems.getItem(i); XmlSchema importedSchema = imp.getSchema(); String location = importedSchema.getSourceURI(); if (!(imports.containsKey(location))) { // only add schemas that were not already added imports.put(location, null); // place a marker in the map to prevent loading the location in the call to loadSchema imports.put(location, loadSchema(location, importedSchema, imports, progress)); } if (imp instanceof XmlSchemaInclude) { includes.add(location); } } catch (Throwable e) { _log.error("Error adding imported schema", e); } } _log.info("Creating types for schema at " + schemaLocation); progress.setCurrentTask("Analyzing schema " + namespace); // map for all imported types Map<Name, TypeDefinition> importedFeatureTypes = new HashMap<Name, TypeDefinition>(); // name mapping for imported types: element name -> type name Map<Name, SchemaElement> importedElements = new HashMap<Name, SchemaElement>(); // add imported types for (Entry<String, SchemaResult> entry : imports.entrySet()) { if (entry.getValue() != null) { if (includes.contains(entry.getKey())) { // is include, add to result featureTypes.putAll(entry.getValue().getTypes()); elements.putAll(entry.getValue().getElements()); } else { // is import, don't add to result importedFeatureTypes.putAll(entry.getValue().getTypes()); importedElements.putAll(entry.getValue().getElements()); } } } // schema type resolver combining the informations for resolving types SchemaTypeResolver typeResolver = new SchemaTypeResolver(featureTypes, importedFeatureTypes, schemaLocation); // Map of type names to definitions Map<Name, XmlSchemaObject> typeDefinitions = new HashMap<Name, XmlSchemaObject>(); // Dependency map for building the dependency list Map<Name, Set<Name>> dependencies = new HashMap<Name, Set<Name>>(); // 2nd pass - determine dependencies for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); String name = null; Set<Name> typeDependencies = null; // the type dependencies including the super type Name superTypeName = null; // the super type name if (item instanceof XmlSchemaComplexType) { name = ((XmlSchemaComplexType)item).getName(); // get the attribute type names typeDependencies = getAttributeTypeNames(elements, importedElements, (XmlSchemaComplexType) item); // get the name of the super type superTypeName = getSuperTypeName((XmlSchemaComplexType)item); if (superTypeName != null) { typeDependencies.add(superTypeName); } } else if (item instanceof XmlSchemaSimpleType) { name = ((XmlSchemaSimpleType)item).getName(); // union/list referencing dependencies typeDependencies = TypeUtil.getSimpleTypeDependencies(new NameImpl(namespace, name), (XmlSchemaSimpleType) item); } // if the item is a type we remember the type definition and determine its local dependencies if (name != null) { // determine the real type name Name typeName = new NameImpl(namespace, name); // determine the local dependency set Set<Name> localDependencies = new HashSet<Name>(); if (typeDependencies != null) { for (Name dependency : typeDependencies) { if (dependency.getNamespaceURI().equals(namespace) && ((!featureTypes.containsKey(dependency) && referencesType(elements, dependency)) || schemaTypeNames.contains(dependency.getLocalPart()))) { // local type, add to local dependencies localDependencies.add(dependency); } } } // add imported super types to the result set Name importName = superTypeName; TypeDefinition importType = null; while (importName != null && (importType = importedFeatureTypes.get(importName)) != null) { featureTypes.put(importName, importType); TypeDefinition superType = importType.getSuperType(); if (superType != null) { importName = superType.getName(); } else { importName = null; } } // remember type definition typeDefinitions.put(typeName, item); // store local dependencies in dependency map dependencies.put(typeName, localDependencies); } } // create dependency ordered list DependencyOrderedList<Name> typeNames = new DependencyOrderedList<Name>(dependencies); // 3rd pass: create feature types for (Name typeName : typeNames.getItems()) { XmlSchemaObject item = typeDefinitions.get(typeName); if (item == null) { _log.error("No definition for " + typeName.toString()); } else if (item instanceof XmlSchemaSimpleType) { // attribute type from simple schema types TypeDefinition simpleType = TypeUtil.resolveSimpleType( typeName, (XmlSchemaSimpleType) item, typeResolver); if (simpleType != null) { // create a simple type featureTypes.put(typeName, simpleType); } else { _log.error("No attribute type generated for simple type " + typeName.toString()); } } else if (item instanceof XmlSchemaComplexType) { // determine the super type name Name superTypeName = getSuperTypeName((XmlSchemaComplexType) item); TypeDefinition superType = null; if (superTypeName != null) { // find super type superType = TypeUtil.resolveAttributeType(superTypeName, typeResolver); // create empty super type if it was not found if (superType == null) { superType = new TypeDefinition(superTypeName, null, null); superType.setLocation("Empty type generated by HALE"); superType.setAbstract(true); // add super type to feature map featureTypes.put(superTypeName, superType); } } // create type definition TypeDefinition typeDef = new TypeDefinition(typeName, null, superType); typeDef.setLocation(schemaLocation); // determine the defined attributes and add them to the declaring type List<AttributeDefinition> attributes = getAttributes( elements, importedElements, typeDef, // definition of the declaring type (XmlSchemaComplexType) item, typeResolver); // reuse the super type's attribute type where appropriate if (superType != null && superType.isAttributeTypeSet()) { // determine if any new elements have been added in the subtype boolean reuseBinding = true; // special case: super type is AbstractFeatureType but no FeatureType instance if (superType.isFeatureType() && !(superType.getType(null) instanceof FeatureType)) { reuseBinding = false; } Iterator<AttributeDefinition> it = attributes.iterator(); while (reuseBinding && it.hasNext()) { if (it.next().isElement()) { reuseBinding = false; } } if (reuseBinding) { // reuse attribute type typeDef.setType(superType.getType(null)); } } // set additional properties typeDef.setAbstract(((XmlSchemaComplexType) item).isAbstract()); // add type definition featureTypes.put(typeName, typeDef); } } // populate schema items with type definitions for (SchemaElement element : elements.values()) { TypeDefinition elementDef = featureTypes.get(element.getTypeName()); if (elementDef != null) { element.setType(elementDef); } else { elementDef = element.getType(); if (elementDef == null) { elementDef = TypeUtil.resolveAttributeType(element.getTypeName(), typeResolver); //TypeUtil.getXSType(element.getTypeName()); } if (elementDef == null) { //_log.warn("Couldn't find definition for element " + element.getDisplayName()); } else { element.setType(elementDef); } } } return result; }
protected SchemaResult loadSchema(String schemaLocation, XmlSchema schema, Map<String, SchemaResult> imports, ProgressIndicator progress) { String namespace = schema.getTargetNamespace(); if (namespace == null || namespace.isEmpty()) { // default to gml schema namespace = "http://www.opengis.net/gml"; } // Map of type names / types for the result Map<Name, TypeDefinition> featureTypes = new HashMap<Name, TypeDefinition>(); // name mapping: element name -> type name Map<Name, SchemaElement> elements = new HashMap<Name, SchemaElement>(); // result SchemaResult result = new SchemaResult(featureTypes, elements); // type names for type definitions where is no element Set<String> schemaTypeNames = new HashSet<String>(); // the schema items XmlSchemaObjectCollection items = schema.getItems(); // first pass - find names for types for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); if (item instanceof XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement) item; // retrieve local name part of XmlSchemaElement and of // XmlSchemaComplexType to substitute name later on. Name typeName = null; if (element.getSchemaTypeName() != null) { typeName = new NameImpl( element.getSchemaTypeName().getNamespaceURI(), element.getSchemaTypeName().getLocalPart()); } else if (element.getQName() != null) { typeName = new NameImpl( element.getQName().getNamespaceURI(), element.getQName().getLocalPart()); } Name elementName = new NameImpl(namespace, element.getName()); // create schema element SchemaElement schemaElement = new SchemaElement(elementName, typeName, null); schemaElement.setLocation(schemaLocation); // get description String description = SchemaAttribute.getDescription(element); schemaElement.setDescription(description); // store element in map elements.put(elementName, schemaElement); } else if (item instanceof XmlSchemaComplexType) { schemaTypeNames.add(((XmlSchemaComplexType)item).getName()); } else if (item instanceof XmlSchemaSimpleType) { schemaTypeNames.add(((XmlSchemaSimpleType)item).getName()); } } // Set of include locations Set<String> includes = new HashSet<String>(); // handle imports XmlSchemaObjectCollection externalItems = schema.getIncludes(); if (externalItems.getCount() > 0) { _log.info("Loading includes and imports for schema at " + schemaLocation); } // add self to imports (allows resolving references to elements that are defined here) imports.put(schemaLocation, result); for (int i = 0; i < externalItems.getCount(); i++) { try { XmlSchemaExternal imp = (XmlSchemaExternal) externalItems.getItem(i); XmlSchema importedSchema = imp.getSchema(); String location = importedSchema.getSourceURI(); if (!(imports.containsKey(location))) { // only add schemas that were not already added imports.put(location, null); // place a marker in the map to prevent loading the location in the call to loadSchema imports.put(location, loadSchema(location, importedSchema, imports, progress)); } if (imp instanceof XmlSchemaInclude) { includes.add(location); } } catch (Throwable e) { _log.error("Error adding imported schema", e); } } _log.info("Creating types for schema at " + schemaLocation); progress.setCurrentTask("Analyzing schema " + namespace); // map for all imported types Map<Name, TypeDefinition> importedFeatureTypes = new HashMap<Name, TypeDefinition>(); // name mapping for imported types: element name -> type name Map<Name, SchemaElement> importedElements = new HashMap<Name, SchemaElement>(); // add imported types for (Entry<String, SchemaResult> entry : imports.entrySet()) { if (entry.getValue() != null) { if (includes.contains(entry.getKey())) { // is include, add to result featureTypes.putAll(entry.getValue().getTypes()); elements.putAll(entry.getValue().getElements()); } else { // is import, don't add to result importedFeatureTypes.putAll(entry.getValue().getTypes()); importedElements.putAll(entry.getValue().getElements()); } } } // schema type resolver combining the informations for resolving types SchemaTypeResolver typeResolver = new SchemaTypeResolver(featureTypes, importedFeatureTypes, schemaLocation); // Map of type names to definitions Map<Name, XmlSchemaObject> typeDefinitions = new HashMap<Name, XmlSchemaObject>(); // Dependency map for building the dependency list Map<Name, Set<Name>> dependencies = new HashMap<Name, Set<Name>>(); // 2nd pass - determine dependencies for (int i = 0; i < items.getCount(); i++) { XmlSchemaObject item = items.getItem(i); String name = null; Set<Name> typeDependencies = null; // the type dependencies including the super type Name superTypeName = null; // the super type name if (item instanceof XmlSchemaComplexType) { name = ((XmlSchemaComplexType)item).getName(); // get the attribute type names typeDependencies = getAttributeTypeNames(elements, importedElements, (XmlSchemaComplexType) item); // get the name of the super type superTypeName = getSuperTypeName((XmlSchemaComplexType)item); if (superTypeName != null) { typeDependencies.add(superTypeName); } } else if (item instanceof XmlSchemaSimpleType) { name = ((XmlSchemaSimpleType)item).getName(); // union/list referencing dependencies typeDependencies = TypeUtil.getSimpleTypeDependencies(new NameImpl(namespace, name), (XmlSchemaSimpleType) item); } // if the item is a type we remember the type definition and determine its local dependencies if (name != null) { // determine the real type name Name typeName = new NameImpl(namespace, name); // determine the local dependency set Set<Name> localDependencies = new HashSet<Name>(); if (typeDependencies != null) { for (Name dependency : typeDependencies) { if (dependency.getNamespaceURI().equals(namespace) && ((!featureTypes.containsKey(dependency) && referencesType(elements, dependency)) || schemaTypeNames.contains(dependency.getLocalPart()))) { // local type, add to local dependencies localDependencies.add(dependency); } } } // add imported super types to the result set Name importName = superTypeName; TypeDefinition importType = null; while (importName != null && (importType = importedFeatureTypes.get(importName)) != null) { featureTypes.put(importName, importType); TypeDefinition superType = importType.getSuperType(); if (superType != null) { importName = superType.getName(); } else { importName = null; } } // remember type definition typeDefinitions.put(typeName, item); // store local dependencies in dependency map dependencies.put(typeName, localDependencies); } } // create dependency ordered list DependencyOrderedList<Name> typeNames = new DependencyOrderedList<Name>(dependencies); // 3rd pass: create feature types for (Name typeName : typeNames.getItems()) { XmlSchemaObject item = typeDefinitions.get(typeName); if (item == null) { _log.error("No definition for " + typeName.toString()); } else if (item instanceof XmlSchemaSimpleType) { // attribute type from simple schema types TypeDefinition simpleType = TypeUtil.resolveSimpleType( typeName, (XmlSchemaSimpleType) item, typeResolver); if (simpleType != null) { // create a simple type featureTypes.put(typeName, simpleType); } else { _log.warn("No attribute type generated for simple type " + typeName.toString()); } } else if (item instanceof XmlSchemaComplexType) { // determine the super type name Name superTypeName = getSuperTypeName((XmlSchemaComplexType) item); TypeDefinition superType = null; if (superTypeName != null) { // find super type superType = TypeUtil.resolveAttributeType(superTypeName, typeResolver); // create empty super type if it was not found if (superType == null) { superType = new TypeDefinition(superTypeName, null, null); superType.setLocation("Empty type generated by HALE"); superType.setAbstract(true); // add super type to feature map featureTypes.put(superTypeName, superType); } } // create type definition TypeDefinition typeDef = new TypeDefinition(typeName, null, superType); typeDef.setLocation(schemaLocation); // determine the defined attributes and add them to the declaring type List<AttributeDefinition> attributes = getAttributes( elements, importedElements, typeDef, // definition of the declaring type (XmlSchemaComplexType) item, typeResolver); // reuse the super type's attribute type where appropriate if (superType != null && superType.isAttributeTypeSet()) { // determine if any new elements have been added in the subtype boolean reuseBinding = true; // special case: super type is AbstractFeatureType but no FeatureType instance if (superType.isFeatureType() && !(superType.getType(null) instanceof FeatureType)) { reuseBinding = false; } Iterator<AttributeDefinition> it = attributes.iterator(); while (reuseBinding && it.hasNext()) { if (it.next().isElement()) { reuseBinding = false; } } if (reuseBinding) { // reuse attribute type typeDef.setType(superType.getType(null)); } } // set additional properties typeDef.setAbstract(((XmlSchemaComplexType) item).isAbstract()); // add type definition featureTypes.put(typeName, typeDef); } } // populate schema items with type definitions for (SchemaElement element : elements.values()) { TypeDefinition elementDef = featureTypes.get(element.getTypeName()); if (elementDef != null) { element.setType(elementDef); } else { elementDef = element.getType(); if (elementDef == null) { elementDef = TypeUtil.resolveAttributeType(element.getTypeName(), typeResolver); //TypeUtil.getXSType(element.getTypeName()); } if (elementDef == null) { //_log.warn("Couldn't find definition for element " + element.getDisplayName()); } else { element.setType(elementDef); } } } return result; }
diff --git a/ic2d-plugins-src/org.objectweb.proactive.ic2d.JMXmonitoring/src/org/objectweb/proactive/ic2d/jmxmonitoring/data/ProActiveNodeObject.java b/ic2d-plugins-src/org.objectweb.proactive.ic2d.JMXmonitoring/src/org/objectweb/proactive/ic2d/jmxmonitoring/data/ProActiveNodeObject.java index b8654a40d..d569b33f2 100644 --- a/ic2d-plugins-src/org.objectweb.proactive.ic2d.JMXmonitoring/src/org/objectweb/proactive/ic2d/jmxmonitoring/data/ProActiveNodeObject.java +++ b/ic2d-plugins-src/org.objectweb.proactive.ic2d.JMXmonitoring/src/org/objectweb/proactive/ic2d/jmxmonitoring/data/ProActiveNodeObject.java @@ -1,284 +1,286 @@ /* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2007 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ */ package org.objectweb.proactive.ic2d.jmxmonitoring.data; import java.util.ArrayList; import java.util.List; import javax.management.ObjectName; import org.objectweb.proactive.core.UniqueID; import org.objectweb.proactive.core.jmx.mbean.NodeWrapperMBean; import org.objectweb.proactive.core.jmx.naming.FactoryName; import org.objectweb.proactive.core.util.URIBuilder; import org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotification; import org.objectweb.proactive.ic2d.jmxmonitoring.util.MVCNotificationTag; import org.objectweb.proactive.ic2d.jmxmonitoring.util.State; /** * This class represents the model of a proactive node. * * @author vbodnart */ public final class ProActiveNodeObject extends AbstractData<RuntimeObject, ActiveObject> { /** * The parent runtime object */ private final RuntimeObject parent; /** * The virtual node that owns this node object */ private final VirtualNodeObject vnParent; /** * The url of this node object */ private final String url; // Warning: Don't use this variable directly, use getProxyNodeMBean(). private final NodeWrapperMBean proxyNodeMBean; public ProActiveNodeObject(final RuntimeObject parent, final String url, final ObjectName objectName, final VirtualNodeObject vnParent, final NodeWrapperMBean proxyNodeMBean) { // Call super constructor in order to specify a TreeMap<String, // AbstractData> for monitored children super(objectName); // new TreeMap<String, AbstractData>( // new ActiveObject.ActiveObjectComparator())); this.parent = parent; this.vnParent = vnParent; this.url = FactoryName.getCompleteUrl(url); this.proxyNodeMBean = proxyNodeMBean; } @Override public RuntimeObject getParent() { return this.parent; } /** * Returns the virtual node. * * @return the virtual node. */ public VirtualNodeObject getVirtualNode() { return this.vnParent; } /** * Gets a proxy for the MBean representing this Node. If the proxy does not * exist it creates it * * @return The reference on the proxy to the node mbean */ private NodeWrapperMBean getProxyNodeMBean() { return this.proxyNodeMBean; } /** * The destroy method of this class first destroys each children then * removes itself from its virtual node. */ @Override public void destroy() { for (final ActiveObject child : this.getMonitoredChildrenAsList()) { child.internalDestroy(); } this.monitoredChildren.clear(); // Fire notification super.notifyObservers(new MVCNotification(MVCNotificationTag.REMOVE_CHILDREN, null)); this.vnParent.removeChild(this); super.destroy(); } @Override public void explore() { if (super.isMonitored) { this.findActiveObjects(); } } @Override public String getKey() { return this.url; } @Override public String getType() { return "node object"; } /** * Returns the url of this object. * * @return An url. */ public String getUrl() { return this.url; } /** * Finds all active objects of this node. */ private void findActiveObjects() { final List<ObjectName> activeObjectNames = getProxyNodeMBean().getActiveObjects(); // The list that will contain all new children final List<ActiveObject> newChildren = new ArrayList<ActiveObject>(); for (final ObjectName aoObjectName : activeObjectNames) { // Get the ID property from the objectName final String aoID = aoObjectName.getKeyProperty(FactoryName.AO_ID_PROPERTY); // First check if the aoID is known if (super.getWorldObject().findActiveObject(aoID) != null) { continue; } // If the aoID is unknown create a new ActiveObject from the // aoObjectName - final ActiveObject newChild = ActiveObject.createActiveObjectFrom(aoObjectName, this); - super.monitoredChildren.put(aoID, newChild); - newChildren.add(newChild); + if (!super.monitoredChildren.containsKey(aoID)) { + final ActiveObject newChild = ActiveObject.createActiveObjectFrom(aoObjectName, this); + super.monitoredChildren.put(aoID, newChild); + newChildren.add(newChild); + } } // In order to avoid sending costly notifications to observers each time // this method is called // set this observable object to be changed only if there are new // children final int numberOfNewChildren = newChildren.size(); if (numberOfNewChildren > 0) { super.setChanged(); } // If no new children return silently if (super.countObservers() != 0) { // If only one child no need to refresh all children there is a // specific notification for that case if (numberOfNewChildren == 1) { // Fire add child notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILD, newChildren.get(0))); return; } // Fire add all children notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILDREN, newChildren)); } } /** * Called by * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.listener.RuntimeObjectListener} * on bodyCreated notification. * <p> * Adds a child active object if and only if the key (ie the string * representation of the unique id) is unknown. * * @param id * The UniqueID of the active object to add * @param className * The name of the reified object class */ public void addActiveObjectByID(final UniqueID id, final String className) { // Try to retrieve this active object by key final String key = id.toString(); ActiveObject activeObject = (ActiveObject) super.getChild(key); // If the active object is not known by this node if (activeObject == null) { // Check the world knows it activeObject = this.getParent().getWorldObject().findActiveObject(key); // if its unknown create one and add it to monitored children if (activeObject == null) { super.addChild(ActiveObject.createActiveObjectFrom(id, className, this)); } } } /** * Called by * {@link org.objectweb.proactive.ic2d.jmxmonitoring.data.listener.RuntimeObjectListener} * on bodyDestroyed notification. * <p> * removes a child active object if and only if the key (ie the string * representation of the unique id) is known. * * @param id * The UniqueID of the active object to add */ public void removeActiveObjectByID(final UniqueID id) { // Try to retrieve this active object by key final String key = id.getCanonString(); super.removeChild(super.getChild(key)); } @Override public String getName() { return URIBuilder.getNameFromURI(this.url); } @Override public String toString() { return "Node: " + this.url; } /** * Returns the virtual node name. * * @return the virtual node name. */ public String getVirtualNodeName() { return this.vnParent.getName(); } /** * Returns the Job Id. * * @return the Job Id. */ public String getJobId() { return this.vnParent.getJobID(); } /** * Used to highlight this node, in a virtual node. * * @param highlighted * true, or false */ public void setHighlight(boolean highlighted) { this.setChanged(); this.notifyObservers(new MVCNotification(MVCNotificationTag.STATE_CHANGED, highlighted ? State.HIGHLIGHTED : State.NOT_HIGHLIGHTED)); } public void notifyChanged() { this.setChanged(); this.notifyObservers(null); } }
true
true
private void findActiveObjects() { final List<ObjectName> activeObjectNames = getProxyNodeMBean().getActiveObjects(); // The list that will contain all new children final List<ActiveObject> newChildren = new ArrayList<ActiveObject>(); for (final ObjectName aoObjectName : activeObjectNames) { // Get the ID property from the objectName final String aoID = aoObjectName.getKeyProperty(FactoryName.AO_ID_PROPERTY); // First check if the aoID is known if (super.getWorldObject().findActiveObject(aoID) != null) { continue; } // If the aoID is unknown create a new ActiveObject from the // aoObjectName final ActiveObject newChild = ActiveObject.createActiveObjectFrom(aoObjectName, this); super.monitoredChildren.put(aoID, newChild); newChildren.add(newChild); } // In order to avoid sending costly notifications to observers each time // this method is called // set this observable object to be changed only if there are new // children final int numberOfNewChildren = newChildren.size(); if (numberOfNewChildren > 0) { super.setChanged(); } // If no new children return silently if (super.countObservers() != 0) { // If only one child no need to refresh all children there is a // specific notification for that case if (numberOfNewChildren == 1) { // Fire add child notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILD, newChildren.get(0))); return; } // Fire add all children notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILDREN, newChildren)); } }
private void findActiveObjects() { final List<ObjectName> activeObjectNames = getProxyNodeMBean().getActiveObjects(); // The list that will contain all new children final List<ActiveObject> newChildren = new ArrayList<ActiveObject>(); for (final ObjectName aoObjectName : activeObjectNames) { // Get the ID property from the objectName final String aoID = aoObjectName.getKeyProperty(FactoryName.AO_ID_PROPERTY); // First check if the aoID is known if (super.getWorldObject().findActiveObject(aoID) != null) { continue; } // If the aoID is unknown create a new ActiveObject from the // aoObjectName if (!super.monitoredChildren.containsKey(aoID)) { final ActiveObject newChild = ActiveObject.createActiveObjectFrom(aoObjectName, this); super.monitoredChildren.put(aoID, newChild); newChildren.add(newChild); } } // In order to avoid sending costly notifications to observers each time // this method is called // set this observable object to be changed only if there are new // children final int numberOfNewChildren = newChildren.size(); if (numberOfNewChildren > 0) { super.setChanged(); } // If no new children return silently if (super.countObservers() != 0) { // If only one child no need to refresh all children there is a // specific notification for that case if (numberOfNewChildren == 1) { // Fire add child notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILD, newChildren.get(0))); return; } // Fire add all children notification super.notifyObservers(new MVCNotification(MVCNotificationTag.ADD_CHILDREN, newChildren)); } }
diff --git a/pre-ingest/schema-mapping-tool/applet/src/at/nhmwien/schema_mapping_tool/converter/MODSConverter.java b/pre-ingest/schema-mapping-tool/applet/src/at/nhmwien/schema_mapping_tool/converter/MODSConverter.java index d7dd4701..d3086f6e 100644 --- a/pre-ingest/schema-mapping-tool/applet/src/at/nhmwien/schema_mapping_tool/converter/MODSConverter.java +++ b/pre-ingest/schema-mapping-tool/applet/src/at/nhmwien/schema_mapping_tool/converter/MODSConverter.java @@ -1,21 +1,21 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package at.nhmwien.schema_mapping_tool.converter; import java.io.File; import java.io.InputStream; /** * * @author wkoller */ public class MODSConverter { public static void convertToOLEF( File inputFile, File outputFile ) throws Exception { // Now load the XSL from the internal resources - InputStream xslFile = MODSConverter.class.getResourceAsStream( "resources/MODS2OLEF_v0.2.xsl" ); + InputStream xslFile = MODSConverter.class.getResourceAsStream( "resources/MODS2OLEF.xsl" ); XSLTransformer.transform(inputFile, outputFile, xslFile); } }
true
true
public static void convertToOLEF( File inputFile, File outputFile ) throws Exception { // Now load the XSL from the internal resources InputStream xslFile = MODSConverter.class.getResourceAsStream( "resources/MODS2OLEF_v0.2.xsl" ); XSLTransformer.transform(inputFile, outputFile, xslFile); }
public static void convertToOLEF( File inputFile, File outputFile ) throws Exception { // Now load the XSL from the internal resources InputStream xslFile = MODSConverter.class.getResourceAsStream( "resources/MODS2OLEF.xsl" ); XSLTransformer.transform(inputFile, outputFile, xslFile); }
diff --git a/org.reuseware.emftextedit/src/org/reuseware/emftextedit/codegen/TextParserGenerator.java b/org.reuseware.emftextedit/src/org/reuseware/emftextedit/codegen/TextParserGenerator.java index 87b6d0e9d..910465a83 100644 --- a/org.reuseware.emftextedit/src/org/reuseware/emftextedit/codegen/TextParserGenerator.java +++ b/org.reuseware.emftextedit/src/org/reuseware/emftextedit/codegen/TextParserGenerator.java @@ -1,867 +1,867 @@ package org.reuseware.emftextedit.codegen; import java.io.PrintWriter; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.LinkedList; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.BufferedOutputStream; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.ANTLRInputStream; import org.antlr.runtime.RecognitionException; import org.eclipse.emf.codegen.ecore.genmodel.GenClass; import org.eclipse.emf.codegen.ecore.genmodel.GenFeature; import org.eclipse.emf.codegen.ecore.genmodel.GenPackage; import org.eclipse.emf.common.util.BasicEList; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.EEnum; import org.reuseware.emftextedit.codegen.regex.ANTLRexpLexer; import org.reuseware.emftextedit.codegen.regex.ANTLRexpParser; import org.reuseware.emftextedit.concretesyntax.Choice; import org.reuseware.emftextedit.concretesyntax.CompoundDefinition; import org.reuseware.emftextedit.concretesyntax.ConcreteSyntax; import org.reuseware.emftextedit.concretesyntax.CsString; import org.reuseware.emftextedit.concretesyntax.DefinedPlaceholder; import org.reuseware.emftextedit.concretesyntax.DerivedPlaceholder; import org.reuseware.emftextedit.concretesyntax.Containment; import org.reuseware.emftextedit.concretesyntax.Definition; import org.reuseware.emftextedit.concretesyntax.LineBreak; import org.reuseware.emftextedit.concretesyntax.PLUS; import org.reuseware.emftextedit.concretesyntax.Cardinality; import org.reuseware.emftextedit.concretesyntax.QUESTIONMARK; import org.reuseware.emftextedit.concretesyntax.Rule; import org.reuseware.emftextedit.concretesyntax.Sequence; import org.reuseware.emftextedit.concretesyntax.Terminal; import org.reuseware.emftextedit.concretesyntax.WhiteSpaces; import org.reuseware.emftextedit.concretesyntax.TokenDefinition; import org.reuseware.emftextedit.concretesyntax.NewDefinedToken; import org.reuseware.emftextedit.concretesyntax.PreDefinedToken; import org.reuseware.emftextedit.concretesyntax.DecoratedToken; /** * The text parser generator maps from one or more conretesyntaxes (*.cs) and * one or more ecore gen-models to an ANTLR parser specification. * If the derived specification does not contain syntactical conflicts which * could break the ANTLR generation algorithm or the ANTLR parsing algorithm * (e.g. ambiguities in the cfg or in token definitions which are not checked by this generator) * it can be used to generate a text parser which allows to create metamodel * instances from plain text files. * * * @author skarol * */ public class TextParserGenerator extends BaseGenerator{ /** * The standard token type name (used when no userdefined tokentype is referenced * and no pre- and suffixes are given). */ public static final String STD_TOKEN_NAME = "TEXT"; private static final String STD_TOKEN_DEF = "('A'..'Z' | 'a'..'z' | '0'..'9' | '_' | '-' )+"; /** * The whitespace token definition. */ public static final String WS_TOKEN_NAME = "WS"; private static final String WS_TOKEN_DEF = "(' ' | '\\t' | '\\f')"; /** * The line break token definition. */ public static final String LB_TOKEN_NAME = "LB"; private static final String LB_TOKEN_DEF = "('\\r\\n' | '\\r' | '\\n')"; /** * The name prefix of derived tokendefinitions. * The full name later is constructed by DERIVED_TOKEN_NAME+_+PREFIXCODE+_+SUFFIXCODE. */ public static final String DERIVED_TOKEN_NAME= "QUOTED"; /** * These class/interface definitions bring automatically derived TokenDefinitions * and userdefined TokenDefinitions together. * * * @author skarol * */ public static interface InternalTokenDefinition{ public String getName(); public String getExpression(); //might be null public String getPrefix(); //might be null public String getSuffix(); //might be null public TokenDefinition getBaseDefinition(); public boolean isReferenced(); public boolean isDerived(); } private static class InternalTokenDefinitionImpl implements InternalTokenDefinition{ private String name; private String expression; private String prefix; private String suffix; private PreDefinedToken base; private boolean implicitlyReferenced; public InternalTokenDefinitionImpl(String name, String expression, String prefix, String suffix, PreDefinedToken base, boolean implicitlyReferenced){ this.name = name; this.expression = expression; this.prefix = prefix; this.suffix = suffix; this.base = base; this.implicitlyReferenced = implicitlyReferenced; } public String getName() { return name; } public String getExpression() { return expression; } public String getPrefix() { return prefix; } public String getSuffix() { return suffix; } public PreDefinedToken getBaseDefinition(){ return base; } public void setBaseDefinition(PreDefinedToken newBase){ base = newBase; } public boolean isReferenced(){ return base==null?implicitlyReferenced:!base.getAttributeReferences().isEmpty(); } public boolean isDerived(){ return true; } } private static class TokenDefinitionAdapter implements InternalTokenDefinition{ private NewDefinedToken adaptee; public TokenDefinitionAdapter(NewDefinedToken adaptee){ if(adaptee==null) throw new NullPointerException("Adaptee shouldnt be null!"); this.adaptee = adaptee; } public TokenDefinition getBaseDefinition() { return adaptee; } public String getExpression() { return adaptee.getRegex(); } public String getName() { return adaptee.getName(); } public String getPrefix() { if(adaptee instanceof DecoratedToken) return ((DecoratedToken)adaptee).getPrefix(); return null; } public String getSuffix() { if(adaptee instanceof DecoratedToken) return ((DecoratedToken)adaptee).getSuffix(); return null; } public boolean isReferenced(){ return !adaptee.getAttributeReferences().isEmpty(); } public boolean isDerived(){ return false; } } private ConcreteSyntax source; private String tokenResolverFactoryName; private Map<String,InternalTokenDefinition> derivedTokens; private Collection<InternalTokenDefinition> printedTokens; //Map to collect all (non-containment) references that will contain proxies after parsing. private Collection<GenFeature> proxyReferences; //TODO Mapping only for strings might possibly cause name clashes ... private Map<String, Collection<String>> genClasses2superNames; private Collection<GenClass> allGenClasses; private Map<DerivedPlaceholder,String> placeholder2TokenName; public TextParserGenerator(ConcreteSyntax cs, String csClassName,String csPackageName, String tokenResolverFactoryName){ super(csClassName,csPackageName); source = cs; this.tokenResolverFactoryName = tokenResolverFactoryName; } private void initCaches(){ proxyReferences = new LinkedList<GenFeature>(); derivedTokens = new HashMap<String,InternalTokenDefinition>(); placeholder2TokenName = new HashMap<DerivedPlaceholder,String>(); derivedTokens.put(LB_TOKEN_NAME,new InternalTokenDefinitionImpl(LB_TOKEN_NAME,LB_TOKEN_DEF,null,null,null,false)); derivedTokens.put(WS_TOKEN_NAME,new InternalTokenDefinitionImpl(WS_TOKEN_NAME,WS_TOKEN_DEF,null,null,null,false)); printedTokens = new LinkedList<InternalTokenDefinition>(); genClasses2superNames = new HashMap<String, Collection<String>>(); allGenClasses = new LinkedList<GenClass>(source.getPackage().getGenClasses()); for(GenPackage usedGP : source.getPackage().getGenModel().getUsedGenPackages()) { allGenClasses.addAll(usedGP.getGenClasses()); } for (GenClass genClass : allGenClasses) { HashSet<String> supertypes = new HashSet<String>(); for (EClass c : genClass.getEcoreClass().getEAllSuperTypes()) { supertypes.add(c.getName()); } this.genClasses2superNames.put(genClass.getEcoreClass().getName(), supertypes); } } public boolean generate(PrintWriter out){ initCaches(); EList<GenPackage> usedGenpackages = new BasicEList<GenPackage>(source.getPackage().getGenModel().getUsedGenPackages()); usedGenpackages.add(0,source.getPackage()); String csName = super.getResourceClassName(); out.println("grammar " + csName + ";"); out.println("options {superClass = EMFTextParserImpl; backtrack = true;}"); out.println(); //the lexer: package def. and error handling out.println("@lexer::header{"); out.println("package " + super.getResourcePackageName() + ";"); out.println(); out.println("}"); out.println(); out.println("@lexer::members{"); out.println("\tpublic java.util.List<RecognitionException> lexerExceptions = new java.util.ArrayList<RecognitionException>();"); out.println("\tpublic java.util.List<Integer> lexerExceptionsPosition = new java.util.ArrayList<Integer>();"); out.println(); out.println("\tpublic void reportError(RecognitionException e) {"); out.println("\t\tlexerExceptions.add(e);\n"); out.println("\t\tlexerExceptionsPosition.add(((ANTLRStringStream)input).index());"); out.println("\t}"); out.println("}"); //the parser: package def. and entry (doParse) method out.println("@header{"); out.println("package " + super.getResourcePackageName() + ";"); out.println(); printGenPackageImports(usedGenpackages,out); printDefaultImports(out); out.println("}"); out.println(); out.println("@members{"); out.println("\tprivate TokenResolverFactory tokenResolverFactory = new " + tokenResolverFactoryName +"();"); out.println(); out.println("\tprotected EObject doParse() throws RecognitionException {"); out.println("\t\t((" + csName + "Lexer)getTokenStream().getTokenSource()).lexerExceptions = lexerExceptions;"); //required because the lexer class can not be subclassed out.println("\t\t((" + csName + "Lexer)getTokenStream().getTokenSource()).lexerExceptionsPosition = lexerExceptionsPosition;"); //required because the lexer class can not be subclassed out.println("\t\treturn start();" ); out.println("\t}"); out.println("}"); out.println(); printStartRule(out); EList<GenClass> eClassesWithSyntax = new BasicEList<GenClass>(); Map<GenClass,Collection<Terminal>> eClassesReferenced = new HashMap<GenClass,Collection<Terminal>>(); printGrammarRules(out,eClassesWithSyntax,eClassesReferenced); printImplicitChoiceRules(out,eClassesWithSyntax,eClassesReferenced); printTokenDefinitions(out); return this.getOccuredProblems()==null; } private void printStartRule(PrintWriter out){ //do the start symbol rule out.println("start"); out.println("returns [ EObject element = null]"); out.println(": "); int count = 0; for(Iterator<GenClass> i = source.getStartSymbols().iterator(); i.hasNext(); ) { GenClass aStart = i.next(); out.println("c" + count + " = " + getLowerCase(aStart.getName()) + "{ element = c" + count + "; }"); if (i.hasNext()) out.println("\t| "); count++; } out.println(); out.println(";"); out.println(); } private void printGrammarRules(PrintWriter out,EList<GenClass> eClassesWithSyntax, Map<GenClass,Collection<Terminal>> eClassesReferenced){ for(Rule rule : source.getAllRules()) { String ruleName = rule.getMetaclass().getName(); GenPackage genPackage = rule.getMetaclass().getGenPackage(); out.print(getLowerCase(ruleName)); out.println(" returns [" + ruleName + " element = null]"); out.println("@init{"); out.println("\telement = " + genPackage.getPrefix() + "Factory.eINSTANCE.create" + rule.getMetaclass().getName() + "();"); out.println("}"); out.println(":"); printChoice(rule.getDefinition(),rule,out,0,eClassesReferenced,proxyReferences,"\t"); Collection<GenClass> subClasses = GeneratorUtil.getSubClassesWithCS(rule.getMetaclass(),source.getAllRules()); if(!subClasses.isEmpty()){ out.println("\t|//derived choice rules for sub-classes: "); printSubClassChoices(out,subClasses); out.println(); } out.println(";"); out.println(); eClassesWithSyntax.add(rule.getMetaclass()); } } private int printChoice(Choice choice, Rule rule, PrintWriter out, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced, Collection<GenFeature> proxyReferences, String indent) { Iterator<Sequence> it = choice.getOptions().iterator(); while(it.hasNext()){ Sequence seq = it.next(); count = printSequence(seq, rule, out, count, eClassesReferenced, proxyReferences, indent); if(it.hasNext()){ out.println(); out.print(indent); out.println("|"); } } //out.println(); return count; } private int printSequence(Sequence sequence, Rule rule, PrintWriter out, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced, Collection<GenFeature> proxyReferences, String indent) { Iterator<Definition> it = sequence.getParts().iterator(); while(it.hasNext()){ Definition def = it.next(); if(def instanceof LineBreak || def instanceof WhiteSpaces) continue; String cardinality = computeCardinalityString(def.getCardinality()); if(cardinality!=null){ out.println(indent+"("); indent += "\t"; } if(def instanceof CompoundDefinition){ CompoundDefinition compoundDef = (CompoundDefinition) def; out.println(indent+"("); count = printChoice(compoundDef.getDefinitions(), rule,out, count, eClassesReferenced, proxyReferences, indent+"\t"); out.print(indent+")"); } else if(def instanceof CsString){ CsString terminal = (CsString) def; out.print(indent+"'" + terminal.getValue().replaceAll("'", "\\\\'") + "'"); } else{ assert def instanceof Terminal; count = printTerminal((Terminal)def,rule,out,count,eClassesReferenced,proxyReferences,indent); } if(cardinality!=null){ indent = indent.substring(1); out.println(); out.print(indent+")"+cardinality); } out.println(); } return count; } private int printTerminal(Terminal terminal,Rule rule,PrintWriter out, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced, Collection<GenFeature> proxyReferences, String indent){ final EStructuralFeature sf = terminal.getFeature().getEcoreFeature(); final String ident = "a" + count; final String proxyIdent = "proxy"; String expressionToBeSet = null; String resolvements = ""; out.print(indent); out.print(ident + " = "); if(terminal instanceof Containment){ assert ((EReference)sf).isContainment(); out.print(getLowerCase(sf.getEType().getName())); if(!(terminal.getFeature().getEcoreFeature() instanceof EAttribute)){ //remember which classes are referenced to add choice rules for these classes later if (!eClassesReferenced.keySet().contains(terminal.getFeature().getTypeGenClass())) { eClassesReferenced.put(terminal.getFeature().getTypeGenClass(),new HashSet<Terminal>()); } eClassesReferenced.get(terminal.getFeature().getTypeGenClass()).add(terminal); } expressionToBeSet = ident; } else { String tokenName = null; if(terminal instanceof DerivedPlaceholder){ DerivedPlaceholder placeholder = (DerivedPlaceholder)terminal; InternalTokenDefinition definition = deriveTokenDefinition(placeholder.getPrefix(),placeholder.getSuffix()); tokenName = definition.getName(); placeholder2TokenName.put(placeholder,tokenName); } else{ assert terminal instanceof DefinedPlaceholder; DefinedPlaceholder placeholder = (DefinedPlaceholder)terminal; tokenName = placeholder.getToken().getName(); } out.print(tokenName); String targetTypeName = null; String resolvedIdent = "resolved"; String preResolved = resolvedIdent+"Object"; String resolverIdent = resolvedIdent+"Resolver"; resolvements += "TokenResolver " +resolverIdent +" = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"; resolvements += "Object " + preResolved + " ="+resolverIdent+".resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += "if(" + preResolved + "==null)throw new TokenConversionException("+ident+","+resolverIdent+".getErrorMessage());"; if(sf instanceof EReference){ targetTypeName = "String"; expressionToBeSet = proxyIdent; //a subtype that can be instantiated as a proxy GenClass instanceType = terminal.getFeature().getTypeGenClass(); String proxyTypeName = null; String genPackagePrefix = null; if(instanceType.isAbstract()||instanceType.isInterface()){ for(GenClass instanceCand : allGenClasses){ Collection<String> supertypes = genClasses2superNames.get(instanceCand.getEcoreClass().getName()); if (!instanceCand.isAbstract()&&!instanceCand.isInterface()&&supertypes.contains(instanceType.getEcoreClass().getName())) { genPackagePrefix = instanceCand.getGenPackage().getPrefix(); proxyTypeName = instanceCand.getName(); break; } } } else{ proxyTypeName = instanceType.getName(); genPackagePrefix = instanceType.getGenPackage().getPrefix(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") "+preResolved+";"; //resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") tokenResolverFactory.createTokenResolver(\"" + tokenName + "\").resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += proxyTypeName + " " + expressionToBeSet + " = " + genPackagePrefix + "Factory.eINSTANCE.create" + proxyTypeName + "();" - + "((InternalEObject)" + expressionToBeSet + ").eSetProxyURI((resource.getURI()==null?URI.create(\"dummy\"):resource.getURI()).appendFragment(" + resolvedIdent + ")); "; + + "\nif (resource.getURI() != null) {\n\t((InternalEObject)" + expressionToBeSet + ").eSetProxyURI(resource.getURI().appendFragment(" + resolvedIdent + "));\n}\n"; //remember where proxies have to be resolved proxyReferences.add(terminal.getFeature()); } else{ EAttribute attr = (EAttribute)sf; if(attr.getEType() instanceof EEnum){ EEnum enumType = (EEnum)attr.getEType(); targetTypeName = enumType.getName(); } else{ targetTypeName = attr.getEAttributeType().getInstanceClassName(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + getObjectTypeName(targetTypeName) + ")" + preResolved + ";"; expressionToBeSet = "resolved"; } } out.print("{"); out.print(resolvements); if(sf.getUpperBound()==1){ out.print("element.set" + cap(sf.getName()) + "(" + expressionToBeSet +"); "); } else{ //TODO Warning, if a value is used twice. //whatever... out.print("element.get" + cap(sf.getName()) + "().add(" + expressionToBeSet +"); "); } if(terminal instanceof Containment){ out.print("getResource().setElementCharStart(element, getResource().getElementCharStart(" + ident + ")); "); out.print("getResource().setElementCharEnd(element, getResource().getElementCharEnd(" + ident + ")); "); out.print("getResource().setElementColumn(element, getResource().getElementColumn(" + ident + ")); "); out.print("getResource().setElementLine(element, getResource().getElementLine(" + ident + "));"); }else{ out.print("getResource().setElementCharStart(element, ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(element, ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(element, " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(element, " + ident + ".getLine()); "); if(sf instanceof EReference){ //additionally set position information for the proxy instance out.print("getResource().setElementCharStart(" + proxyIdent + ", ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(" + proxyIdent + ", ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(" + proxyIdent + ", " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(" + proxyIdent + ", " + ident + ".getLine()); "); } } out.print("}"); return ++count; } private void printImplicitChoiceRules(PrintWriter out, EList<GenClass> eClassesWithSyntax, Map<GenClass,Collection<Terminal>> eClassesReferenced){ for(GenClass referencedClass : eClassesReferenced.keySet()) { if(!cointainsEqualByName(eClassesWithSyntax,referencedClass)) { //rule not explicitly defined in CS: most likely a choice rule in the AS Collection<GenClass> subClasses = GeneratorUtil.getSubClassesWithCS(referencedClass,source.getAllRules()); if (subClasses.isEmpty()) { String message = "Referenced class '"+referencedClass.getName()+"' has no defined concrete Syntax."; for(Terminal terminal:eClassesReferenced.get(referencedClass)){ addProblem(new GenerationProblem(message,terminal)); } } else { out.println(getLowerCase(referencedClass.getName())); out.println("returns [" + referencedClass.getName() + " element = null]"); out.println(":"); printSubClassChoices(out,subClasses); out.println(); out.println(";"); out.println(); //add import .... shouldnt it already be there? //GenPackage p = referencedClass.getGenPackage(); //s.insert(importIdx, "import " + ( p.getBasePackage()==null?"": p.getBasePackage() + "." )+ p.getEcorePackage().getName() + "." + referencedClass.getName() + ";\n"); //referenced class now has syntax eClassesWithSyntax.add(referencedClass); } } } } private void printSubClassChoices(PrintWriter out, Collection<GenClass> subClasses){ int count = 0; for(Iterator<GenClass> i = subClasses.iterator(); i.hasNext(); ) { GenClass subRef = i.next(); out.print("\tc" + count + " = " + getLowerCase(subRef.getName()) + "{ element = c" + count + "; }"); if (i.hasNext()) out.println("\t|"); count++; } } private boolean cointainsEqualByName(EList<GenClass> list, GenClass o){ for(GenClass entry:list){ EClass entryClass = entry.getEcoreClass(); EClass oClass = o.getEcoreClass(); if(entryClass.getName().equals(oClass.getName())&&entryClass.getEPackage().getNsURI().equals(oClass.getEPackage().getNsURI())){ return true; } } return false; } /** * <p>Derives a Tokendefinition from the given prefix and suffix char. If the suffix is valued -1, * a standard Definition using the static values STD_TOKEN_NAME and STD_TOKEN_DEF will be created and registered * (if not yet been done) and returned. If additionally a prefix is given, the tokens name will be the conjunction * of the value STD_TOKEN_NAME, "_", "prefix", "_". The resulting regular expression is constructed by prepending * the prefix to the value STD_TOKEN_DEF. </p> * <p> * If suffix is given a Tokendefinition, matching the given prefix (if there) first and than matching all characters, * excepting the suffix, is created and returned. The name of this definition is the conjunction of the value * in DERIVED_TOKEN_NAME, "_", prefix, "_" and suffix. </p> * * @param pref * @param suff * @return */ private InternalTokenDefinition deriveTokenDefinition(String pref, String suff){ String derivedTokenName = null; if(suff!=null&&suff.length()>0){ String derivedExpression = null; if(pref!=null&&pref.length()>0){ derivedTokenName = DERIVED_TOKEN_NAME + "_" + deriveCodeSequence(pref) + "_" + deriveCodeSequence(suff); if(!derivedTokens.containsKey(derivedTokenName)){ derivedExpression = "(~('"+ escapeLiteralChars(suff) +"')|('\\\\''"+escapeLiteralChars(suff)+"'))*"; InternalTokenDefinition result = new InternalTokenDefinitionImpl(derivedTokenName,derivedExpression,pref,suff,null,true); derivedTokens.put(derivedTokenName,result); } } else{ derivedTokenName = DERIVED_TOKEN_NAME + "_" + "_" + deriveCodeSequence(suff); if(!derivedTokens.containsKey(derivedTokenName)){ derivedExpression = "(~('"+ escapeLiteralChars(suff) +"')|( '\\\\' '"+escapeLiteralChars(suff)+"' ))* '"; InternalTokenDefinition result = new InternalTokenDefinitionImpl(derivedTokenName,derivedExpression,null,suff,null,true); derivedTokens.put(derivedTokenName,result); } } } else{ if(pref!=null&&pref.length()>0){ String derivedExpression = null; derivedTokenName = STD_TOKEN_NAME + "_" + deriveCodeSequence(pref) + "_"; if(!derivedTokens.containsKey(derivedTokenName)){ derivedExpression = STD_TOKEN_DEF; InternalTokenDefinition result = new InternalTokenDefinitionImpl(derivedTokenName,derivedExpression,pref,null,null,true); derivedTokens.put(derivedTokenName,result); } } else{ derivedTokenName = STD_TOKEN_NAME; if(!derivedTokens.containsKey(derivedTokenName)){ InternalTokenDefinition result = new InternalTokenDefinitionImpl(derivedTokenName,STD_TOKEN_DEF,null,null,null,true); derivedTokens.put(derivedTokenName,result); } } } return derivedTokens.get(derivedTokenName); } private String deriveCodeSequence(String original){ char[] chars = original.toCharArray(); String result = ""; for(int i=0;i<chars.length;i++){ if(chars[i]<10) result += "0"; result += (int)chars[i]; } return result; } private String escapeLiteralChar(char candidate){ String result = ""; switch (candidate){ case '\'': case '\\': result += "\\"; default: result += candidate; } return result; } /** * Used to escape prefix/suffix strings (surrounded by "'" in ANTLR). * */ private String escapeLiteralChars(String candidate){ StringBuffer escaped = new StringBuffer(); char[] chars = candidate.toCharArray(); for(int i=0;i<chars.length;i++){ escaped.append(escapeLiteralChar(chars[i])); } return escaped.toString(); } private void printTokenDefinitions(PrintWriter out){ Set<String> processedTokenNames = new HashSet<String>(); Collection<TokenDefinition> userDefinedTokens = source.getTokens(); for(TokenDefinition def:userDefinedTokens){ if(def.getName().charAt(0)<'A'||def.getName().charAt(0)>'Z'){ addProblem(new GenerationProblem("Token names must start with capital letter.",def)); continue; } if(processedTokenNames.contains(def.getName().toLowerCase())){ addProblem(new GenerationProblem("Tokenname already in use (ignoring case).",def)); continue; } if(def instanceof NewDefinedToken){ InternalTokenDefinition defAdapter = new TokenDefinitionAdapter((NewDefinedToken)def); if(!checkANTLRRegex(defAdapter)){ continue; } printToken(defAdapter,out); processedTokenNames.add(defAdapter.getName().toLowerCase()); printedTokens.add(defAdapter); } else if(def instanceof PreDefinedToken){ if(derivedTokens.get(def.getName())!=null){ InternalTokenDefinition defAdapter = derivedTokens.remove(def.getName()); printToken(defAdapter,out); processedTokenNames.add(defAdapter.getName().toLowerCase()); printedTokens.add(defAdapter); } else{ addProblem(new GenerationProblem("Token is neither predefined nor derived.",def)); } } } //finally process untouched derived definitions for(String tokenName:derivedTokens.keySet()){ InternalTokenDefinition def = derivedTokens.get(tokenName); printToken(def,out); processedTokenNames.add(tokenName.toLowerCase()); printedTokens.add(def); } } private void printToken(InternalTokenDefinition def, PrintWriter out){ out.println(def.getName()); out.println(":"); out.print("\t"); if(def.getPrefix()!=null && def.getPrefix().length()>0){ String regex = "('" + escapeLiteralChars(def.getPrefix()) + "')"; out.print(regex); } out.print(def.getExpression()); if(def.getSuffix()!=null && def.getPrefix().length()>0){ String regex = "('" + escapeLiteralChars(def.getSuffix()) + "')"; out.print(regex); } out.println(def.isReferenced()?"":"{ channel=99; }"); out.println(";"); } private void printGenPackageImports(Collection<GenPackage> usedGenpackages, PrintWriter out){ for(GenPackage p:usedGenpackages){ out.println("//+++++++++++++++++++++++imports for "+p.getQualifiedPackageName()+" begin++++++++++++++++++++++"); for(GenClass genClass : p.getGenClasses()) { if(genClass.getEcoreClass().getName()==null){ out.println("//No ecore class for genClass: "+genClass.getName()); }else{ out.println("import " + genClass.getQualifiedInterfaceName() + ";"); out.println("//Implementation: "+genClass.getQualifiedClassName()); } } String usedPackagePrefix = p.getBasePackage()==null?"":(p.getBasePackage() + "."); out.println("import " + usedPackagePrefix + p.getEcorePackage().getName() + ".*;"); out.println("import " + usedPackagePrefix + p.getEcorePackage().getName() + ".impl.*;"); } } private void printDefaultImports(PrintWriter out){ out.println("import org.reuseware.emftextedit.resource.*;"); out.println("import org.reuseware.emftextedit.resource.impl.*;"); out.println("import org.eclipse.emf.ecore.EObject;"); out.println("import org.eclipse.emf.ecore.InternalEObject;"); out.println("import org.eclipse.emf.common.util.URI;"); } /** * @return The tokendefinitions which were printed during last * execution for printing token resolvers. */ public Collection<InternalTokenDefinition> getPrintedTokenDefinitions(){ return printedTokens; } /** * @return All features which will be replaced with a proxy during a parse * and therefore need proxy resolvers. */ public Collection<GenFeature> getProxyReferences(){ return proxyReferences; } /** * * @return A mapping between derived Placeholders and Tokennames */ public Map<DerivedPlaceholder,String> getPlaceHolderTokenMapping(){ return placeholder2TokenName; } private String computeCardinalityString(Cardinality card){ if(card==null) return null; else if(card instanceof PLUS) return "+"; else if(card instanceof QUESTIONMARK) return "?"; else return "*"; } private boolean checkANTLRRegex(InternalTokenDefinition def){ ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintWriter w = new PrintWriter(new BufferedOutputStream(out)); w.print(def.getExpression()); w.flush(); w.close(); try{ ANTLRexpLexer l = new ANTLRexpLexer(new ANTLRInputStream(new ByteArrayInputStream(out.toByteArray()))); ANTLRexpParser p = new ANTLRexpParser(new CommonTokenStream(l)); p.root(); if(!p.recExceptions.isEmpty()){ for(RecognitionException e:p.recExceptions){ String message = l.getErrorMessage(e,l.getTokenNames()); if(message==null||message.equals("")) message = p.getErrorMessage(e,p.getTokenNames()); addProblem(new GenerationProblem(message,def.getBaseDefinition())); } return false; } }catch(Exception e){ addProblem(new GenerationProblem(e.getMessage(),def.getBaseDefinition())); return false; } return true; } }
true
true
private int printTerminal(Terminal terminal,Rule rule,PrintWriter out, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced, Collection<GenFeature> proxyReferences, String indent){ final EStructuralFeature sf = terminal.getFeature().getEcoreFeature(); final String ident = "a" + count; final String proxyIdent = "proxy"; String expressionToBeSet = null; String resolvements = ""; out.print(indent); out.print(ident + " = "); if(terminal instanceof Containment){ assert ((EReference)sf).isContainment(); out.print(getLowerCase(sf.getEType().getName())); if(!(terminal.getFeature().getEcoreFeature() instanceof EAttribute)){ //remember which classes are referenced to add choice rules for these classes later if (!eClassesReferenced.keySet().contains(terminal.getFeature().getTypeGenClass())) { eClassesReferenced.put(terminal.getFeature().getTypeGenClass(),new HashSet<Terminal>()); } eClassesReferenced.get(terminal.getFeature().getTypeGenClass()).add(terminal); } expressionToBeSet = ident; } else { String tokenName = null; if(terminal instanceof DerivedPlaceholder){ DerivedPlaceholder placeholder = (DerivedPlaceholder)terminal; InternalTokenDefinition definition = deriveTokenDefinition(placeholder.getPrefix(),placeholder.getSuffix()); tokenName = definition.getName(); placeholder2TokenName.put(placeholder,tokenName); } else{ assert terminal instanceof DefinedPlaceholder; DefinedPlaceholder placeholder = (DefinedPlaceholder)terminal; tokenName = placeholder.getToken().getName(); } out.print(tokenName); String targetTypeName = null; String resolvedIdent = "resolved"; String preResolved = resolvedIdent+"Object"; String resolverIdent = resolvedIdent+"Resolver"; resolvements += "TokenResolver " +resolverIdent +" = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"; resolvements += "Object " + preResolved + " ="+resolverIdent+".resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += "if(" + preResolved + "==null)throw new TokenConversionException("+ident+","+resolverIdent+".getErrorMessage());"; if(sf instanceof EReference){ targetTypeName = "String"; expressionToBeSet = proxyIdent; //a subtype that can be instantiated as a proxy GenClass instanceType = terminal.getFeature().getTypeGenClass(); String proxyTypeName = null; String genPackagePrefix = null; if(instanceType.isAbstract()||instanceType.isInterface()){ for(GenClass instanceCand : allGenClasses){ Collection<String> supertypes = genClasses2superNames.get(instanceCand.getEcoreClass().getName()); if (!instanceCand.isAbstract()&&!instanceCand.isInterface()&&supertypes.contains(instanceType.getEcoreClass().getName())) { genPackagePrefix = instanceCand.getGenPackage().getPrefix(); proxyTypeName = instanceCand.getName(); break; } } } else{ proxyTypeName = instanceType.getName(); genPackagePrefix = instanceType.getGenPackage().getPrefix(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") "+preResolved+";"; //resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") tokenResolverFactory.createTokenResolver(\"" + tokenName + "\").resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += proxyTypeName + " " + expressionToBeSet + " = " + genPackagePrefix + "Factory.eINSTANCE.create" + proxyTypeName + "();" + "((InternalEObject)" + expressionToBeSet + ").eSetProxyURI((resource.getURI()==null?URI.create(\"dummy\"):resource.getURI()).appendFragment(" + resolvedIdent + ")); "; //remember where proxies have to be resolved proxyReferences.add(terminal.getFeature()); } else{ EAttribute attr = (EAttribute)sf; if(attr.getEType() instanceof EEnum){ EEnum enumType = (EEnum)attr.getEType(); targetTypeName = enumType.getName(); } else{ targetTypeName = attr.getEAttributeType().getInstanceClassName(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + getObjectTypeName(targetTypeName) + ")" + preResolved + ";"; expressionToBeSet = "resolved"; } } out.print("{"); out.print(resolvements); if(sf.getUpperBound()==1){ out.print("element.set" + cap(sf.getName()) + "(" + expressionToBeSet +"); "); } else{ //TODO Warning, if a value is used twice. //whatever... out.print("element.get" + cap(sf.getName()) + "().add(" + expressionToBeSet +"); "); } if(terminal instanceof Containment){ out.print("getResource().setElementCharStart(element, getResource().getElementCharStart(" + ident + ")); "); out.print("getResource().setElementCharEnd(element, getResource().getElementCharEnd(" + ident + ")); "); out.print("getResource().setElementColumn(element, getResource().getElementColumn(" + ident + ")); "); out.print("getResource().setElementLine(element, getResource().getElementLine(" + ident + "));"); }else{ out.print("getResource().setElementCharStart(element, ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(element, ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(element, " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(element, " + ident + ".getLine()); "); if(sf instanceof EReference){ //additionally set position information for the proxy instance out.print("getResource().setElementCharStart(" + proxyIdent + ", ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(" + proxyIdent + ", ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(" + proxyIdent + ", " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(" + proxyIdent + ", " + ident + ".getLine()); "); } } out.print("}"); return ++count; }
private int printTerminal(Terminal terminal,Rule rule,PrintWriter out, int count,Map<GenClass,Collection<Terminal>> eClassesReferenced, Collection<GenFeature> proxyReferences, String indent){ final EStructuralFeature sf = terminal.getFeature().getEcoreFeature(); final String ident = "a" + count; final String proxyIdent = "proxy"; String expressionToBeSet = null; String resolvements = ""; out.print(indent); out.print(ident + " = "); if(terminal instanceof Containment){ assert ((EReference)sf).isContainment(); out.print(getLowerCase(sf.getEType().getName())); if(!(terminal.getFeature().getEcoreFeature() instanceof EAttribute)){ //remember which classes are referenced to add choice rules for these classes later if (!eClassesReferenced.keySet().contains(terminal.getFeature().getTypeGenClass())) { eClassesReferenced.put(terminal.getFeature().getTypeGenClass(),new HashSet<Terminal>()); } eClassesReferenced.get(terminal.getFeature().getTypeGenClass()).add(terminal); } expressionToBeSet = ident; } else { String tokenName = null; if(terminal instanceof DerivedPlaceholder){ DerivedPlaceholder placeholder = (DerivedPlaceholder)terminal; InternalTokenDefinition definition = deriveTokenDefinition(placeholder.getPrefix(),placeholder.getSuffix()); tokenName = definition.getName(); placeholder2TokenName.put(placeholder,tokenName); } else{ assert terminal instanceof DefinedPlaceholder; DefinedPlaceholder placeholder = (DefinedPlaceholder)terminal; tokenName = placeholder.getToken().getName(); } out.print(tokenName); String targetTypeName = null; String resolvedIdent = "resolved"; String preResolved = resolvedIdent+"Object"; String resolverIdent = resolvedIdent+"Resolver"; resolvements += "TokenResolver " +resolverIdent +" = tokenResolverFactory.createTokenResolver(\"" + tokenName + "\");"; resolvements += "Object " + preResolved + " ="+resolverIdent+".resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += "if(" + preResolved + "==null)throw new TokenConversionException("+ident+","+resolverIdent+".getErrorMessage());"; if(sf instanceof EReference){ targetTypeName = "String"; expressionToBeSet = proxyIdent; //a subtype that can be instantiated as a proxy GenClass instanceType = terminal.getFeature().getTypeGenClass(); String proxyTypeName = null; String genPackagePrefix = null; if(instanceType.isAbstract()||instanceType.isInterface()){ for(GenClass instanceCand : allGenClasses){ Collection<String> supertypes = genClasses2superNames.get(instanceCand.getEcoreClass().getName()); if (!instanceCand.isAbstract()&&!instanceCand.isInterface()&&supertypes.contains(instanceType.getEcoreClass().getName())) { genPackagePrefix = instanceCand.getGenPackage().getPrefix(); proxyTypeName = instanceCand.getName(); break; } } } else{ proxyTypeName = instanceType.getName(); genPackagePrefix = instanceType.getGenPackage().getPrefix(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") "+preResolved+";"; //resolvements += targetTypeName + " " + resolvedIdent + " = (" + targetTypeName + ") tokenResolverFactory.createTokenResolver(\"" + tokenName + "\").resolve(" +ident+ ".getText(),element.eClass().getEStructuralFeature(\"" + sf.getName() + "\"),element,getResource());"; resolvements += proxyTypeName + " " + expressionToBeSet + " = " + genPackagePrefix + "Factory.eINSTANCE.create" + proxyTypeName + "();" + "\nif (resource.getURI() != null) {\n\t((InternalEObject)" + expressionToBeSet + ").eSetProxyURI(resource.getURI().appendFragment(" + resolvedIdent + "));\n}\n"; //remember where proxies have to be resolved proxyReferences.add(terminal.getFeature()); } else{ EAttribute attr = (EAttribute)sf; if(attr.getEType() instanceof EEnum){ EEnum enumType = (EEnum)attr.getEType(); targetTypeName = enumType.getName(); } else{ targetTypeName = attr.getEAttributeType().getInstanceClassName(); } resolvements += targetTypeName + " " + resolvedIdent + " = (" + getObjectTypeName(targetTypeName) + ")" + preResolved + ";"; expressionToBeSet = "resolved"; } } out.print("{"); out.print(resolvements); if(sf.getUpperBound()==1){ out.print("element.set" + cap(sf.getName()) + "(" + expressionToBeSet +"); "); } else{ //TODO Warning, if a value is used twice. //whatever... out.print("element.get" + cap(sf.getName()) + "().add(" + expressionToBeSet +"); "); } if(terminal instanceof Containment){ out.print("getResource().setElementCharStart(element, getResource().getElementCharStart(" + ident + ")); "); out.print("getResource().setElementCharEnd(element, getResource().getElementCharEnd(" + ident + ")); "); out.print("getResource().setElementColumn(element, getResource().getElementColumn(" + ident + ")); "); out.print("getResource().setElementLine(element, getResource().getElementLine(" + ident + "));"); }else{ out.print("getResource().setElementCharStart(element, ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(element, ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(element, " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(element, " + ident + ".getLine()); "); if(sf instanceof EReference){ //additionally set position information for the proxy instance out.print("getResource().setElementCharStart(" + proxyIdent + ", ((CommonToken)" + ident + ").getStartIndex()); "); out.print("getResource().setElementCharEnd(" + proxyIdent + ", ((CommonToken)" + ident + ").getStopIndex()); "); out.print("getResource().setElementColumn(" + proxyIdent + ", " + ident + ".getCharPositionInLine()); "); out.print("getResource().setElementLine(" + proxyIdent + ", " + ident + ".getLine()); "); } } out.print("}"); return ++count; }
diff --git a/src/main/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/ComputerOwnerHelper.java b/src/main/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/ComputerOwnerHelper.java index da365c5..00a4309 100644 --- a/src/main/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/ComputerOwnerHelper.java +++ b/src/main/java/com/synopsys/arc/jenkins/plugins/ownership/nodes/ComputerOwnerHelper.java @@ -1,71 +1,71 @@ /* * The MIT License * * Copyright 2013 Oleg Nenashev <[email protected]>, Synopsys Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.synopsys.arc.jenkins.plugins.ownership.nodes; import com.synopsys.arc.jenkins.plugins.ownership.OwnershipDescription; import com.synopsys.arc.jenkins.plugins.ownership.util.AbstractOwnershipHelper; import hudson.model.Computer; import hudson.model.Node; import hudson.model.User; import java.io.IOException; import java.util.Collection; /** * Provides ownership helper for {@link Computer}. * The class implements a wrapper of {@link NodeOwnerHelper}. * @author Oleg Nenashev <[email protected]>, Synopsys Inc. */ public class ComputerOwnerHelper extends AbstractOwnershipHelper<Computer> { static final ComputerOwnerHelper Instance = new ComputerOwnerHelper(); public static ComputerOwnerHelper getInstance() { return Instance; } @Override public OwnershipDescription getOwnershipDescription(Computer item) { Node node = item.getNode(); return node != null ? NodeOwnerHelper.Instance.getOwnershipDescription(node) : OwnershipDescription.DISABLED_DESCR; // No node - no ownership } @Override public Collection<User> getPossibleOwners(Computer computer) { Node node = computer.getNode(); return node != null ? NodeOwnerHelper.Instance.getPossibleOwners(node) : EMPTY_USERS_COLLECTION; } public static void setOwnership(Computer computer, OwnershipDescription descr) throws IOException { Node node = computer.getNode(); if (node == null) { throw new IOException("Cannot set ownership. Probably, the node has been renamed or deleted."); } - ComputerOwnerHelper.setOwnership(computer, descr); + NodeOwnerHelper.setOwnership(node, descr); } }
true
true
public static void setOwnership(Computer computer, OwnershipDescription descr) throws IOException { Node node = computer.getNode(); if (node == null) { throw new IOException("Cannot set ownership. Probably, the node has been renamed or deleted."); } ComputerOwnerHelper.setOwnership(computer, descr); }
public static void setOwnership(Computer computer, OwnershipDescription descr) throws IOException { Node node = computer.getNode(); if (node == null) { throw new IOException("Cannot set ownership. Probably, the node has been renamed or deleted."); } NodeOwnerHelper.setOwnership(node, descr); }
diff --git a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/ResponsePromise.java b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/ResponsePromise.java index fac86c9..7b2db60 100644 --- a/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/ResponsePromise.java +++ b/CornerstoneCommon/src/main/java/com/paxxis/cornerstone/common/ResponsePromise.java @@ -1,107 +1,108 @@ /* * Copyright 2010 the original author or authors. * Copyright 2009 Paxxis Technology LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.paxxis.cornerstone.common; import com.paxxis.cornerstone.base.ResponseMessage; /** * A response promise which is an abstraction over a DataLatch that enforces type safety * and provides the ability for clients of services to set reasonable timeouts. Response promises * are failfast by default meaning if for any reason a valid response cannot be returned then a * runtime exception is thrown. */ public class ResponsePromise<RESP extends ResponseMessage<?>> extends DataLatch<RESP> { private long timeout; private boolean failfast; private RuntimeException exception; public ResponsePromise() { this(10000, true); } public ResponsePromise(long timeout) { this(timeout, true); } public ResponsePromise(long timeout, boolean failfast) { this.timeout = timeout; this.failfast = failfast; } public RESP getResponse(long timeout, boolean failfast) { RESP response = (RESP) waitForObject(timeout, failfast); - if (response.isError()) { + //our response maybe null if failfast is false + if (response != null && response.isError()) { this.exception = new ResponseException(response); } if (failfast && this.exception != null) { throw this.exception; } return response; } public RESP getResponse(long timeout) { return getResponse(timeout, this.failfast); } public RESP getResponse(boolean failfast) { return getResponse(this.timeout, failfast); } public RESP getResponse() { return getResponse(this.timeout, this.failfast); } public boolean hasResponse() { return hasObject(); } @Override public synchronized RuntimeException getException() { if (this.exception != null) { return this.exception; } return super.getException(); } /** * Enforce the timeout value provided at construct time */ @Override public RESP waitForObject() { return getResponse(this.timeout, this.failfast); } /** * Enforce the failfast value provided at construct time */ @Override public RESP waitForObject(long timeout) { return getResponse(timeout, this.failfast); } /** * Enforce the failfast value provided at construct time */ @Override public RESP waitForObject(boolean failfast) { return getResponse(this.timeout, failfast); } }
true
true
public RESP getResponse(long timeout, boolean failfast) { RESP response = (RESP) waitForObject(timeout, failfast); if (response.isError()) { this.exception = new ResponseException(response); } if (failfast && this.exception != null) { throw this.exception; } return response; }
public RESP getResponse(long timeout, boolean failfast) { RESP response = (RESP) waitForObject(timeout, failfast); //our response maybe null if failfast is false if (response != null && response.isError()) { this.exception = new ResponseException(response); } if (failfast && this.exception != null) { throw this.exception; } return response; }
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java index 91d563f476..fd7d35938f 100644 --- a/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java +++ b/lucene/core/src/test/org/apache/lucene/index/TestConcurrentMergeScheduler.java @@ -1,324 +1,327 @@ package org.apache.lucene.index; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.TextField; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.store.MockDirectoryWrapper; import org.apache.lucene.util.LuceneTestCase; import org.apache.lucene.util._TestUtil; public class TestConcurrentMergeScheduler extends LuceneTestCase { private class FailOnlyOnFlush extends MockDirectoryWrapper.Failure { boolean doFail; boolean hitExc; @Override public void setDoFail() { this.doFail = true; hitExc = false; } @Override public void clearDoFail() { this.doFail = false; } @Override public void eval(MockDirectoryWrapper dir) throws IOException { if (doFail && isTestThread()) { boolean isDoFlush = false; boolean isClose = false; StackTraceElement[] trace = new Exception().getStackTrace(); for (int i = 0; i < trace.length; i++) { if ("flush".equals(trace[i].getMethodName())) { isDoFlush = true; } if ("close".equals(trace[i].getMethodName())) { isClose = true; } } if (isDoFlush && !isClose && random().nextBoolean()) { hitExc = true; throw new IOException(Thread.currentThread().getName() + ": now failing during flush"); } } } } // Make sure running BG merges still work fine even when // we are hitting exceptions during flushing. public void testFlushExceptions() throws IOException { MockDirectoryWrapper directory = newMockDirectory(); FailOnlyOnFlush failure = new FailOnlyOnFlush(); directory.failOn(failure); IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())).setMaxBufferedDocs(2)); Document doc = new Document(); Field idField = newStringField("id", "", Field.Store.YES); doc.add(idField); int extraCount = 0; for(int i=0;i<10;i++) { if (VERBOSE) { System.out.println("TEST: iter=" + i); } for(int j=0;j<20;j++) { idField.setStringValue(Integer.toString(i*20+j)); writer.addDocument(doc); } // must cycle here because sometimes the merge flushes // the doc we just added and so there's nothing to // flush, and we don't hit the exception while(true) { writer.addDocument(doc); failure.setDoFail(); try { writer.flush(true, true); if (failure.hitExc) { fail("failed to hit IOException"); } extraCount++; } catch (IOException ioe) { if (VERBOSE) { ioe.printStackTrace(System.out); } failure.clearDoFail(); break; } } assertEquals(20*(i+1)+extraCount, writer.numDocs()); } writer.close(); IndexReader reader = DirectoryReader.open(directory); assertEquals(200+extraCount, reader.numDocs()); reader.close(); directory.close(); } // Test that deletes committed after a merge started and // before it finishes, are correctly merged back: public void testDeleteMerging() throws IOException { Directory directory = newDirectory(); LogDocMergePolicy mp = new LogDocMergePolicy(); // Force degenerate merging so we can get a mix of // merging of segments with and without deletes at the // start: mp.setMinMergeDocs(1000); IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random())) .setMergePolicy(mp)); Document doc = new Document(); Field idField = newStringField("id", "", Field.Store.YES); doc.add(idField); for(int i=0;i<10;i++) { if (VERBOSE) { System.out.println("\nTEST: cycle"); } for(int j=0;j<100;j++) { idField.setStringValue(Integer.toString(i*100+j)); writer.addDocument(doc); } int delID = i; while(delID < 100*(1+i)) { if (VERBOSE) { System.out.println("TEST: del " + delID); } writer.deleteDocuments(new Term("id", ""+delID)); delID += 10; } writer.commit(); } writer.close(); IndexReader reader = DirectoryReader.open(directory); // Verify that we did not lose any deletes... assertEquals(450, reader.numDocs()); reader.close(); directory.close(); } public void testNoExtraFiles() throws IOException { Directory directory = newDirectory(); IndexWriter writer = new IndexWriter(directory, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random())) .setMaxBufferedDocs(2)); for(int iter=0;iter<7;iter++) { if (VERBOSE) { System.out.println("TEST: iter=" + iter); } for(int j=0;j<21;j++) { Document doc = new Document(); doc.add(newTextField("content", "a b c", Field.Store.NO)); writer.addDocument(doc); } writer.close(); TestIndexWriter.assertNoUnreferencedFiles(directory, "testNoExtraFiles"); // Reopen writer = new IndexWriter(directory, newIndexWriterConfig( TEST_VERSION_CURRENT, new MockAnalyzer(random())) .setOpenMode(OpenMode.APPEND).setMaxBufferedDocs(2)); } writer.close(); directory.close(); } public void testNoWaitClose() throws IOException { Directory directory = newDirectory(); Document doc = new Document(); Field idField = newStringField("id", "", Field.Store.YES); doc.add(idField); IndexWriter writer = new IndexWriter( directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())). setMaxBufferedDocs(2). setMergePolicy(newLogMergePolicy(100)) ); for(int iter=0;iter<10;iter++) { for(int j=0;j<201;j++) { idField.setStringValue(Integer.toString(iter*201+j)); writer.addDocument(doc); } int delID = iter*201; for(int j=0;j<20;j++) { writer.deleteDocuments(new Term("id", Integer.toString(delID))); delID += 5; } // Force a bunch of merge threads to kick off so we // stress out aborting them on close: ((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(3); writer.addDocument(doc); writer.commit(); writer.close(false); IndexReader reader = DirectoryReader.open(directory); assertEquals((1+iter)*182, reader.numDocs()); reader.close(); // Reopen writer = new IndexWriter( directory, newIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())). setOpenMode(OpenMode.APPEND). setMergePolicy(newLogMergePolicy(100)) ); } writer.close(); directory.close(); } // LUCENE-4544 public void testMaxMergeCount() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); final int maxMergeCount = _TestUtil.nextInt(random(), 1, 5); final int maxMergeThreads = _TestUtil.nextInt(random(), 1, maxMergeCount); final CountDownLatch enoughMergesWaiting = new CountDownLatch(maxMergeCount); final AtomicInteger runningMergeCount = new AtomicInteger(0); final AtomicBoolean failed = new AtomicBoolean(); if (VERBOSE) { System.out.println("TEST: maxMergeCount=" + maxMergeCount + " maxMergeThreads=" + maxMergeThreads); } ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler() { @Override protected void doMerge(MergePolicy.OneMerge merge) throws IOException { try { // Stall all incoming merges until we see // maxMergeCount: int count = runningMergeCount.incrementAndGet(); try { assertTrue("count=" + count + " vs maxMergeCount=" + maxMergeCount, count <= maxMergeCount); enoughMergesWaiting.countDown(); // Stall this merge until we see exactly // maxMergeCount merges waiting while (true) { if (enoughMergesWaiting.await(10, TimeUnit.MILLISECONDS) || failed.get()) { break; } } // Then sleep a bit to give a chance for the bug // (too many pending merges) to appear: Thread.sleep(20); super.doMerge(merge); } finally { runningMergeCount.decrementAndGet(); } } catch (Throwable t) { failed.set(true); writer.mergeFinish(merge); throw new RuntimeException(t); } } }; + if (maxMergeThreads > cms.getMaxMergeCount()) { + cms.setMaxMergeCount(maxMergeCount); + } cms.setMaxThreadCount(maxMergeThreads); cms.setMaxMergeCount(maxMergeCount); iwc.setMergeScheduler(cms); iwc.setMaxBufferedDocs(2); TieredMergePolicy tmp = new TieredMergePolicy(); iwc.setMergePolicy(tmp); tmp.setMaxMergeAtOnce(2); tmp.setSegmentsPerTier(2); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(newField("field", "field", TextField.TYPE_NOT_STORED)); while(enoughMergesWaiting.getCount() != 0 && !failed.get()) { for(int i=0;i<10;i++) { w.addDocument(doc); } } w.close(false); dir.close(); } }
true
true
public void testMaxMergeCount() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); final int maxMergeCount = _TestUtil.nextInt(random(), 1, 5); final int maxMergeThreads = _TestUtil.nextInt(random(), 1, maxMergeCount); final CountDownLatch enoughMergesWaiting = new CountDownLatch(maxMergeCount); final AtomicInteger runningMergeCount = new AtomicInteger(0); final AtomicBoolean failed = new AtomicBoolean(); if (VERBOSE) { System.out.println("TEST: maxMergeCount=" + maxMergeCount + " maxMergeThreads=" + maxMergeThreads); } ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler() { @Override protected void doMerge(MergePolicy.OneMerge merge) throws IOException { try { // Stall all incoming merges until we see // maxMergeCount: int count = runningMergeCount.incrementAndGet(); try { assertTrue("count=" + count + " vs maxMergeCount=" + maxMergeCount, count <= maxMergeCount); enoughMergesWaiting.countDown(); // Stall this merge until we see exactly // maxMergeCount merges waiting while (true) { if (enoughMergesWaiting.await(10, TimeUnit.MILLISECONDS) || failed.get()) { break; } } // Then sleep a bit to give a chance for the bug // (too many pending merges) to appear: Thread.sleep(20); super.doMerge(merge); } finally { runningMergeCount.decrementAndGet(); } } catch (Throwable t) { failed.set(true); writer.mergeFinish(merge); throw new RuntimeException(t); } } }; cms.setMaxThreadCount(maxMergeThreads); cms.setMaxMergeCount(maxMergeCount); iwc.setMergeScheduler(cms); iwc.setMaxBufferedDocs(2); TieredMergePolicy tmp = new TieredMergePolicy(); iwc.setMergePolicy(tmp); tmp.setMaxMergeAtOnce(2); tmp.setSegmentsPerTier(2); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(newField("field", "field", TextField.TYPE_NOT_STORED)); while(enoughMergesWaiting.getCount() != 0 && !failed.get()) { for(int i=0;i<10;i++) { w.addDocument(doc); } } w.close(false); dir.close(); }
public void testMaxMergeCount() throws Exception { Directory dir = newDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(random())); final int maxMergeCount = _TestUtil.nextInt(random(), 1, 5); final int maxMergeThreads = _TestUtil.nextInt(random(), 1, maxMergeCount); final CountDownLatch enoughMergesWaiting = new CountDownLatch(maxMergeCount); final AtomicInteger runningMergeCount = new AtomicInteger(0); final AtomicBoolean failed = new AtomicBoolean(); if (VERBOSE) { System.out.println("TEST: maxMergeCount=" + maxMergeCount + " maxMergeThreads=" + maxMergeThreads); } ConcurrentMergeScheduler cms = new ConcurrentMergeScheduler() { @Override protected void doMerge(MergePolicy.OneMerge merge) throws IOException { try { // Stall all incoming merges until we see // maxMergeCount: int count = runningMergeCount.incrementAndGet(); try { assertTrue("count=" + count + " vs maxMergeCount=" + maxMergeCount, count <= maxMergeCount); enoughMergesWaiting.countDown(); // Stall this merge until we see exactly // maxMergeCount merges waiting while (true) { if (enoughMergesWaiting.await(10, TimeUnit.MILLISECONDS) || failed.get()) { break; } } // Then sleep a bit to give a chance for the bug // (too many pending merges) to appear: Thread.sleep(20); super.doMerge(merge); } finally { runningMergeCount.decrementAndGet(); } } catch (Throwable t) { failed.set(true); writer.mergeFinish(merge); throw new RuntimeException(t); } } }; if (maxMergeThreads > cms.getMaxMergeCount()) { cms.setMaxMergeCount(maxMergeCount); } cms.setMaxThreadCount(maxMergeThreads); cms.setMaxMergeCount(maxMergeCount); iwc.setMergeScheduler(cms); iwc.setMaxBufferedDocs(2); TieredMergePolicy tmp = new TieredMergePolicy(); iwc.setMergePolicy(tmp); tmp.setMaxMergeAtOnce(2); tmp.setSegmentsPerTier(2); IndexWriter w = new IndexWriter(dir, iwc); Document doc = new Document(); doc.add(newField("field", "field", TextField.TYPE_NOT_STORED)); while(enoughMergesWaiting.getCount() != 0 && !failed.get()) { for(int i=0;i<10;i++) { w.addDocument(doc); } } w.close(false); dir.close(); }
diff --git a/src/main/java/loci/slim/colorizer/ThreeColorColorize.java b/src/main/java/loci/slim/colorizer/ThreeColorColorize.java index 33dc176..85f7e71 100644 --- a/src/main/java/loci/slim/colorizer/ThreeColorColorize.java +++ b/src/main/java/loci/slim/colorizer/ThreeColorColorize.java @@ -1,91 +1,96 @@ // // ThreeColorColorize.java // /* SLIMPlugin for combined spectral-lifetime image analysis. Copyright (c) 2010, UW-Madison LOCI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the UW-Madison LOCI nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package loci.slim.colorizer; import java.awt.Color; /** * Colorizes data based on a sequence of three colors. * * <dl><dt><b>Source code:</b></dt> * <dd><a href="http://dev.loci.wisc.edu/trac/software/browser/trunk/projects/slim-plugin/src/main/java/loci/slim/colorizer/ThreeColorColorize.java">Trac</a>, * <a href="http://dev.loci.wisc.edu/svn/software/trunk/projects/slim-plugin/src/main/java/loci/slim/colorizer/ThreeColorColorize.java">SVN</a></dd></dl> * * @author Aivar Grislis */ public class ThreeColorColorize extends MultiColorColorize implements IColorize { Color m_color1; Color m_color2; Color m_color3; /** * Constructor. Specifies the sequence of three colors. * * @param color1 * @param color2 * @param color3 */ public ThreeColorColorize(Color color1, Color color2, Color color3) { m_color1 = color1; m_color2 = color2; m_color3 = color3; } /** * Colorizes a data value. * * @param start value associated with starting color * @param stop value associated with ending color * @param value to colorize * @return interpolated Color value */ public Color colorize(double start, double stop, double value) { Color returnColor = Color.BLACK; if (value > 0.0) { if (value >= start && value <= stop) { double range = stop - start; - value -= start; - if (value < (range / 2.0)) { - returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range); + if (0.0 == range) { + returnColor = m_color2; } else { - returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range); + value -= start; + if (value < (range / 2.0)) { + returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range); + } + else { + returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range); + } } } } return returnColor; } }
false
true
public Color colorize(double start, double stop, double value) { Color returnColor = Color.BLACK; if (value > 0.0) { if (value >= start && value <= stop) { double range = stop - start; value -= start; if (value < (range / 2.0)) { returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range); } else { returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range); } } } return returnColor; }
public Color colorize(double start, double stop, double value) { Color returnColor = Color.BLACK; if (value > 0.0) { if (value >= start && value <= stop) { double range = stop - start; if (0.0 == range) { returnColor = m_color2; } else { value -= start; if (value < (range / 2.0)) { returnColor = interpolateColor(m_color1, m_color2, 2.0 * value / range); } else { returnColor = interpolateColor(m_color2, m_color3, 2.0 * (value - (range / 2.0)) / range); } } } } return returnColor; }
diff --git a/build-info-extractor-gradle/src/main/java/org/jfrog/build/ArtifactoryPluginUtils.java b/build-info-extractor-gradle/src/main/java/org/jfrog/build/ArtifactoryPluginUtils.java index 53460c9..a09f602 100644 --- a/build-info-extractor-gradle/src/main/java/org/jfrog/build/ArtifactoryPluginUtils.java +++ b/build-info-extractor-gradle/src/main/java/org/jfrog/build/ArtifactoryPluginUtils.java @@ -1,66 +1,66 @@ /* * Copyright (C) 2010 JFrog Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jfrog.build; import org.gradle.StartParameter; import org.gradle.api.Project; import java.util.Map; /** * Utility class for the Artifactory-Gradle plugin. * * @author Tomer Cohen */ public class ArtifactoryPluginUtils { /** * Get a property, this method will search for a property in our defined hierarchy.<br/> <ol><li>First search for * the property as a system property, if found return it.</li> <li>Second search for the property in the Gradle * {@link org.gradle.StartParameter#getProjectProperties} container and if found there, then return it.</li> * <li>Third search for the property in {@link org.gradle.api.Project#property(String)}</li> <li>if not found, * search upwards in the project hierarchy until reach the root project.</li> <li> if not found at all in this * hierarchy return null</li></ol> * * @param propertyName The property name to search. * @param project The starting project from where to start the property search. * @return The property value if found, {@code null} otherwise. */ public static String getProperty(String propertyName, Project project) { if (System.getProperty(propertyName) != null) { return System.getProperty(propertyName); } StartParameter startParameter = project.getGradle().getStartParameter(); Map<String, String> projectProperties = startParameter.getProjectProperties(); if (projectProperties != null) { String propertyValue = projectProperties.get(propertyName); if (propertyValue != null) { return propertyValue; } } if (project.hasProperty(propertyName)) { - return (String) project.property(propertyName); + return project.property(propertyName).toString(); } else { project = project.getParent(); if (project == null) { return null; } else { return getProperty(propertyName, project); } } } }
true
true
public static String getProperty(String propertyName, Project project) { if (System.getProperty(propertyName) != null) { return System.getProperty(propertyName); } StartParameter startParameter = project.getGradle().getStartParameter(); Map<String, String> projectProperties = startParameter.getProjectProperties(); if (projectProperties != null) { String propertyValue = projectProperties.get(propertyName); if (propertyValue != null) { return propertyValue; } } if (project.hasProperty(propertyName)) { return (String) project.property(propertyName); } else { project = project.getParent(); if (project == null) { return null; } else { return getProperty(propertyName, project); } } }
public static String getProperty(String propertyName, Project project) { if (System.getProperty(propertyName) != null) { return System.getProperty(propertyName); } StartParameter startParameter = project.getGradle().getStartParameter(); Map<String, String> projectProperties = startParameter.getProjectProperties(); if (projectProperties != null) { String propertyValue = projectProperties.get(propertyName); if (propertyValue != null) { return propertyValue; } } if (project.hasProperty(propertyName)) { return project.property(propertyName).toString(); } else { project = project.getParent(); if (project == null) { return null; } else { return getProperty(propertyName, project); } } }
diff --git a/src/plugins/spelling/src/java/org/jivesoftware/spellchecker/SpellcheckerPreferenceDialog.java b/src/plugins/spelling/src/java/org/jivesoftware/spellchecker/SpellcheckerPreferenceDialog.java index 39cb283b..8348284a 100644 --- a/src/plugins/spelling/src/java/org/jivesoftware/spellchecker/SpellcheckerPreferenceDialog.java +++ b/src/plugins/spelling/src/java/org/jivesoftware/spellchecker/SpellcheckerPreferenceDialog.java @@ -1,110 +1,110 @@ package org.jivesoftware.spellchecker; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JPanel; import org.jivesoftware.spark.component.VerticalFlowLayout; public class SpellcheckerPreferenceDialog extends JPanel implements ActionListener { private static final long serialVersionUID = -1836601903928057855L; private JCheckBox spellcheckingEnabled = new JCheckBox(); private JCheckBox autospellcheckingEnabled = new JCheckBox(); private JComboBox spellLanguages = new JComboBox(); private JPanel spellPanel = new JPanel(); private Locale[] locales; ArrayList<String> languages; public SpellcheckerPreferenceDialog(ArrayList<String> languages) { this.languages = languages; locales = Locale.getAvailableLocales(); spellPanel.setLayout(new GridBagLayout()); spellcheckingEnabled.setText(SpellcheckerResource.getString("preference.spellcheckingEnabled")); spellcheckingEnabled.addActionListener(this); autospellcheckingEnabled.setText(SpellcheckerResource.getString("preference.autoSpellcheckingEnabled")); for (int i = 0; i < languages.size(); i++) { for (final Locale locale : locales) { if (locale.toString().equals(languages.get(i))) { String label = locale.getDisplayLanguage(Locale.getDefault()); if (locale.getDisplayCountry(locale) != null && locale.getDisplayCountry(locale).trim().length() > 0) { label = label + "-" + locale.getDisplayCountry(locale).trim(); } spellLanguages.addItem(label); } } } spellPanel.add(spellcheckingEnabled, new GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(autospellcheckingEnabled, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(spellLanguages, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); setLayout(new VerticalFlowLayout()); - spellPanel.setBorder(BorderFactory.createTitledBorder("Spellchecking")); + spellPanel.setBorder(BorderFactory.createTitledBorder(SpellcheckerResource.getString("title.spellchecker"))); add(spellPanel); } public void updateUI(boolean enable) { if (enable) { autospellcheckingEnabled.setEnabled(true); spellLanguages.setEnabled(true); } else { autospellcheckingEnabled.setEnabled(false); spellLanguages.setEnabled(false); } } public void setSpellCheckingEnabled(boolean enable) { spellcheckingEnabled.setSelected(enable); updateUI(enable); } public String getSelectedLanguage() { return languages.get(spellLanguages.getSelectedIndex()); } public void setSelectedLanguage(String language) { spellLanguages.setSelectedIndex(languages.indexOf(language)); } public void setAutoSpellCheckingEnabled(boolean enable) { autospellcheckingEnabled.setSelected(enable); } public boolean isSpellCheckingEnabled() { return spellcheckingEnabled.isSelected(); } public boolean isAutoSpellCheckingEnabled() { return autospellcheckingEnabled.isSelected(); } public void actionPerformed(ActionEvent event) { updateUI(spellcheckingEnabled.isSelected()); } }
true
true
public SpellcheckerPreferenceDialog(ArrayList<String> languages) { this.languages = languages; locales = Locale.getAvailableLocales(); spellPanel.setLayout(new GridBagLayout()); spellcheckingEnabled.setText(SpellcheckerResource.getString("preference.spellcheckingEnabled")); spellcheckingEnabled.addActionListener(this); autospellcheckingEnabled.setText(SpellcheckerResource.getString("preference.autoSpellcheckingEnabled")); for (int i = 0; i < languages.size(); i++) { for (final Locale locale : locales) { if (locale.toString().equals(languages.get(i))) { String label = locale.getDisplayLanguage(Locale.getDefault()); if (locale.getDisplayCountry(locale) != null && locale.getDisplayCountry(locale).trim().length() > 0) { label = label + "-" + locale.getDisplayCountry(locale).trim(); } spellLanguages.addItem(label); } } } spellPanel.add(spellcheckingEnabled, new GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(autospellcheckingEnabled, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(spellLanguages, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); setLayout(new VerticalFlowLayout()); spellPanel.setBorder(BorderFactory.createTitledBorder("Spellchecking")); add(spellPanel); }
public SpellcheckerPreferenceDialog(ArrayList<String> languages) { this.languages = languages; locales = Locale.getAvailableLocales(); spellPanel.setLayout(new GridBagLayout()); spellcheckingEnabled.setText(SpellcheckerResource.getString("preference.spellcheckingEnabled")); spellcheckingEnabled.addActionListener(this); autospellcheckingEnabled.setText(SpellcheckerResource.getString("preference.autoSpellcheckingEnabled")); for (int i = 0; i < languages.size(); i++) { for (final Locale locale : locales) { if (locale.toString().equals(languages.get(i))) { String label = locale.getDisplayLanguage(Locale.getDefault()); if (locale.getDisplayCountry(locale) != null && locale.getDisplayCountry(locale).trim().length() > 0) { label = label + "-" + locale.getDisplayCountry(locale).trim(); } spellLanguages.addItem(label); } } } spellPanel.add(spellcheckingEnabled, new GridBagConstraints(0, 0, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(autospellcheckingEnabled, new GridBagConstraints(0, 1, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); spellPanel.add(spellLanguages, new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0)); setLayout(new VerticalFlowLayout()); spellPanel.setBorder(BorderFactory.createTitledBorder(SpellcheckerResource.getString("title.spellchecker"))); add(spellPanel); }
diff --git a/tools/src/XJavac.java b/tools/src/XJavac.java index 75a59d01d..72d10d75d 100644 --- a/tools/src/XJavac.java +++ b/tools/src/XJavac.java @@ -1,150 +1,151 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.xerces.util; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Project; import org.apache.tools.ant.types.Path; import org.apache.tools.ant.util.JavaEnvUtils; import org.apache.tools.ant.taskdefs.Javac; import java.lang.StringBuffer; import java.util.Properties; import java.util.Locale; /** * The implementation of the javac compiler for JDK 1.4 and above * * The purpose of this task is to diagnose whether we're * running on a 1.4 or above JVM; if we are, to * set up the bootclasspath such that the build will * succeed; if we aren't, then invoke the Javac12 * task. * * @author Neil Graham, IBM */ public class XJavac extends Javac { /** * Run the compilation. * * @exception BuildException if the compilation has problems. */ public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also - // for Apple, HP, SableVM, Kaffe and Blackdown: a Linux port of Sun Java + // for Apple, HP, FreeBSD, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || - (vendor.indexOf("SABLE") >= 0)) { + (vendor.indexOf("SABLE") >= 0) || + (vendor.indexOf("FREEBSD") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); } /** * Creates bootclasspath for IBM JDK 1.4 and above. */ private Path createIBMJDKBootclasspath() { Path bcp = createBootclasspath(); String javaHome = System.getProperty("java.home"); StringBuffer bcpMember = new StringBuffer(); bcpMember.append(javaHome).append("/lib/charsets.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/core.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/vm.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/java.util.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/rt.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/graphics.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/javaws.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/jaws.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/security.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/server.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/JawBridge.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/gskikm.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ibmjceprovider.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/indicim.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/jaccess.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/ldapsec.jar:"); bcp.createPathElement().setPath(bcpMember.toString()); bcpMember.replace(javaHome.length(), bcpMember.length(), "/lib/ext/oldcertpath.jar"); bcp.createPathElement().setPath(bcpMember.toString()); return bcp; } /** * Checks whether the JDK version is 1.4 or higher. If it's not * JDK 1.4 we check whether we're on a future JDK by checking * that we're not on JDKs 1.0, 1.1, 1.2 or 1.3. This check by * exclusion should future proof this task from new versions of * Ant which are aware of higher JDK versions. * * @return true if the JDK version is 1.4 or higher. */ private boolean isJDK14OrHigher() { final String version = JavaEnvUtils.getJavaVersion(); return version.equals(JavaEnvUtils.JAVA_1_4) || (!version.equals(JavaEnvUtils.JAVA_1_3) && !version.equals(JavaEnvUtils.JAVA_1_2) && !version.equals(JavaEnvUtils.JAVA_1_1) && !version.equals(JavaEnvUtils.JAVA_1_0)); } }
false
true
public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also // for Apple, HP, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || (vendor.indexOf("SABLE") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); }
public void execute() throws BuildException { if(isJDK14OrHigher()) { // maybe the right one; check vendor: // by checking system properties: Properties props = null; try { props = System.getProperties(); } catch (Exception e) { throw new BuildException("unable to determine java vendor because could not access system properties!"); } // this is supposed to be provided by all JVM's from time immemorial String vendor = ((String)props.get("java.vendor")).toUpperCase(Locale.ENGLISH); if (vendor.indexOf("IBM") >= 0) { // we're on an IBM 1.4 or higher; fiddle with the bootclasspath. setBootclasspath(createIBMJDKBootclasspath()); } // need to do special things for Sun too and also // for Apple, HP, FreeBSD, SableVM, Kaffe and Blackdown: a Linux port of Sun Java else if( (vendor.indexOf("SUN") >= 0) || (vendor.indexOf("BLACKDOWN") >= 0) || (vendor.indexOf("APPLE") >= 0) || (vendor.indexOf("HEWLETT-PACKARD") >= 0) || (vendor.indexOf("KAFFE") >= 0) || (vendor.indexOf("SABLE") >= 0) || (vendor.indexOf("FREEBSD") >= 0)) { // we're on an SUN 1.4 or higher; fiddle with the bootclasspath. // since we can't eviscerate XML-related info here, // we must use the classpath Path bcp = createBootclasspath(); Path clPath = getClasspath(); bcp.append(clPath); String currBCP = (String)props.get("sun.boot.class.path"); Path currBCPath = new Path(null); currBCPath.createPathElement().setPath(currBCP); bcp.append(currBCPath); setBootclasspath(bcp); } } // now just do the normal thing: super.execute(); }
diff --git a/plugin/src/main/java/org/burgers/elasticsearch/plugin/ElasticSearchMojo.java b/plugin/src/main/java/org/burgers/elasticsearch/plugin/ElasticSearchMojo.java index 79536eb..2f790db 100644 --- a/plugin/src/main/java/org/burgers/elasticsearch/plugin/ElasticSearchMojo.java +++ b/plugin/src/main/java/org/burgers/elasticsearch/plugin/ElasticSearchMojo.java @@ -1,17 +1,17 @@ package org.burgers.elasticsearch.plugin; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; /** * Starts Elasticsearch. * @goal run * @requiresProject false */ public class ElasticSearchMojo extends AbstractMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { - System.out.println("I'm running!!!"); + getLog().info("Starting Elasticsearch"); } }
true
true
public void execute() throws MojoExecutionException, MojoFailureException { System.out.println("I'm running!!!"); }
public void execute() throws MojoExecutionException, MojoFailureException { getLog().info("Starting Elasticsearch"); }
diff --git a/trunk/Line_Wars/src/linewars/gamestate/mapItems/Projectile.java b/trunk/Line_Wars/src/linewars/gamestate/mapItems/Projectile.java index 07f4155..c466a53 100644 --- a/trunk/Line_Wars/src/linewars/gamestate/mapItems/Projectile.java +++ b/trunk/Line_Wars/src/linewars/gamestate/mapItems/Projectile.java @@ -1,177 +1,179 @@ package linewars.gamestate.mapItems; import linewars.gamestate.GameState; import linewars.gamestate.Lane; import linewars.gamestate.Player; import linewars.gamestate.Position; import linewars.gamestate.Transformation; import linewars.gamestate.mapItems.strategies.impact.ImpactStrategy; import linewars.gamestate.mapItems.strategies.targeting.TargetingStrategy; import linewars.gamestate.shapes.Shape; /** * * @author , Connor Schenck * * This class represents a projectile. It knows how the projectile collides * with map items and what it should do upon impact. It is a map item. */ public strictfp class Projectile extends MapItemAggregate { private ProjectileDefinition definition; private ImpactStrategy iStrat; private TargetingStrategy tStrat; private Lane lane; private double durability; private Shape tempBody = null; /** * Creates a projectile at transformation t with definition def, * collision strategy cs, and impact strategy is. Sets its container * to l. * * @param t the transformation this projectile starts at * @param def the definition that created this projectile * @param cs the collision strategy for this projectile * @param is the impact strategy for this projectile * @param l the lane that this projectile is in */ public Projectile(Transformation t, ProjectileDefinition def, Player owner, GameState gameState) { super(t, def, gameState, owner); definition = def; iStrat = def.getImpactStratConfig().createStrategy(this); durability = def.getBaseDurability(); tStrat = def.getTargetingStratConfig().createStrategy(this); } public void setLane(Lane l) { lane = l; } public Lane getLane() { return lane; } public double getDurability() { return durability; } public void setDurability(double d) { durability = d; if(durability <= 0) this.setState(MapItemState.Dead); } /** * This method moves the projetile forward at a constant velocity, checks for collisions, * and calls its impact strategy on those collisions. */ public void move() { //make sure we're not already dead if(this.getState().equals(MapItemState.Dead)) return; //first check to see if this projectile is outside the lane double pointRatio = lane.getClosestPointRatio(this.getPosition()); Transformation t = lane.getPosition(pointRatio); if(this.getPosition().distanceSquared(t.getPosition()) > Math.pow(lane.getWidth()/2, 2) || pointRatio >= 1.0 || pointRatio <= 0.0) { this.setState(MapItemState.Dead); return; } Transformation target = tStrat.getTarget(); Position change = target.getPosition().subtract(this.getPosition()); tempBody = this.getBody().stretch(new Transformation(change, target.getRotation())); //this is the raw list of items colliding with this projetile's path MapItem[] rawCollisions = lane.getCollisions(this); + if(rawCollisions.length > 0) + System.out.println(rawCollisions.length + " stuff"); tempBody = null; //this list will be the list of how far along that path each map item is double[] scores = new double[rawCollisions.length]; //the negative sine of the angle that the path was rotated by from 0 rads double sine = -change.getY(); //the negative cosine of the angle that the path was rotated by from 0 rads double cosine = -change.getX(); //calculate the x coordinate of each map item relative to this projectile and rotated //"back" from how this projetile's path was rotated. This will define the order in which //the projectile hit each map item for(int i = 0; i < scores.length; i++) { Position p = rawCollisions[i].getPosition().subtract(this.getPosition()); scores[i] = cosine*p.getX() - sine*p.getY(); } MapItem[] collisions = new MapItem[scores.length]; //since this list will never be that big, its ok to use selection sort for(int i = 0; i < collisions.length; i++) { int smallest = 0; for(int j = 1; j < collisions.length; j++) if(scores[j] < scores[smallest]) smallest = j; collisions[i] = rawCollisions[smallest]; scores[smallest] = Double.MAX_VALUE; } //move the projectile before calling the impact strategy so that the impact strategy may move the projectile this.setTransformation(target); //there's no need to call the collision strategy, it was taken into account when calculating collision for(int i = 0; i < collisions.length && !this.getState().equals(MapItemState.Dead); i++) iStrat.handleImpact(collisions[i]); } @Override public MapItemDefinition<? extends MapItem> getDefinition() { return definition; } /** * * @return the impact strategy of this projetile */ public ImpactStrategy getImpactStrategy() { return iStrat; } @Override public boolean isCollidingWith(MapItem m) { if(tempBody == null) return super.isCollidingWith(m); else { if(!m.getCollisionStrategy().canCollideWith(this)) return false; else return tempBody.isCollidingWith(m.getBody()); } } @Override public boolean equals(Object o){ if(o == null) return false; if(!(o instanceof Projectile)) return false; Projectile other = (Projectile) o; if(!other.getBody().equals(getBody())) return false; //TODO test other things in here return true; } @Override protected void setDefinition(MapItemDefinition<? extends MapItem> def) { definition = (ProjectileDefinition) def; } }
true
true
public void move() { //make sure we're not already dead if(this.getState().equals(MapItemState.Dead)) return; //first check to see if this projectile is outside the lane double pointRatio = lane.getClosestPointRatio(this.getPosition()); Transformation t = lane.getPosition(pointRatio); if(this.getPosition().distanceSquared(t.getPosition()) > Math.pow(lane.getWidth()/2, 2) || pointRatio >= 1.0 || pointRatio <= 0.0) { this.setState(MapItemState.Dead); return; } Transformation target = tStrat.getTarget(); Position change = target.getPosition().subtract(this.getPosition()); tempBody = this.getBody().stretch(new Transformation(change, target.getRotation())); //this is the raw list of items colliding with this projetile's path MapItem[] rawCollisions = lane.getCollisions(this); tempBody = null; //this list will be the list of how far along that path each map item is double[] scores = new double[rawCollisions.length]; //the negative sine of the angle that the path was rotated by from 0 rads double sine = -change.getY(); //the negative cosine of the angle that the path was rotated by from 0 rads double cosine = -change.getX(); //calculate the x coordinate of each map item relative to this projectile and rotated //"back" from how this projetile's path was rotated. This will define the order in which //the projectile hit each map item for(int i = 0; i < scores.length; i++) { Position p = rawCollisions[i].getPosition().subtract(this.getPosition()); scores[i] = cosine*p.getX() - sine*p.getY(); } MapItem[] collisions = new MapItem[scores.length]; //since this list will never be that big, its ok to use selection sort for(int i = 0; i < collisions.length; i++) { int smallest = 0; for(int j = 1; j < collisions.length; j++) if(scores[j] < scores[smallest]) smallest = j; collisions[i] = rawCollisions[smallest]; scores[smallest] = Double.MAX_VALUE; } //move the projectile before calling the impact strategy so that the impact strategy may move the projectile this.setTransformation(target); //there's no need to call the collision strategy, it was taken into account when calculating collision for(int i = 0; i < collisions.length && !this.getState().equals(MapItemState.Dead); i++) iStrat.handleImpact(collisions[i]); }
public void move() { //make sure we're not already dead if(this.getState().equals(MapItemState.Dead)) return; //first check to see if this projectile is outside the lane double pointRatio = lane.getClosestPointRatio(this.getPosition()); Transformation t = lane.getPosition(pointRatio); if(this.getPosition().distanceSquared(t.getPosition()) > Math.pow(lane.getWidth()/2, 2) || pointRatio >= 1.0 || pointRatio <= 0.0) { this.setState(MapItemState.Dead); return; } Transformation target = tStrat.getTarget(); Position change = target.getPosition().subtract(this.getPosition()); tempBody = this.getBody().stretch(new Transformation(change, target.getRotation())); //this is the raw list of items colliding with this projetile's path MapItem[] rawCollisions = lane.getCollisions(this); if(rawCollisions.length > 0) System.out.println(rawCollisions.length + " stuff"); tempBody = null; //this list will be the list of how far along that path each map item is double[] scores = new double[rawCollisions.length]; //the negative sine of the angle that the path was rotated by from 0 rads double sine = -change.getY(); //the negative cosine of the angle that the path was rotated by from 0 rads double cosine = -change.getX(); //calculate the x coordinate of each map item relative to this projectile and rotated //"back" from how this projetile's path was rotated. This will define the order in which //the projectile hit each map item for(int i = 0; i < scores.length; i++) { Position p = rawCollisions[i].getPosition().subtract(this.getPosition()); scores[i] = cosine*p.getX() - sine*p.getY(); } MapItem[] collisions = new MapItem[scores.length]; //since this list will never be that big, its ok to use selection sort for(int i = 0; i < collisions.length; i++) { int smallest = 0; for(int j = 1; j < collisions.length; j++) if(scores[j] < scores[smallest]) smallest = j; collisions[i] = rawCollisions[smallest]; scores[smallest] = Double.MAX_VALUE; } //move the projectile before calling the impact strategy so that the impact strategy may move the projectile this.setTransformation(target); //there's no need to call the collision strategy, it was taken into account when calculating collision for(int i = 0; i < collisions.length && !this.getState().equals(MapItemState.Dead); i++) iStrat.handleImpact(collisions[i]); }
diff --git a/CocoNuestro/src/compilationunit/GenFinal.java b/CocoNuestro/src/compilationunit/GenFinal.java index 2d6eaa3..a35faa2 100644 --- a/CocoNuestro/src/compilationunit/GenFinal.java +++ b/CocoNuestro/src/compilationunit/GenFinal.java @@ -1,190 +1,192 @@ package compilationunit; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; public class GenFinal { BufferedWriter bw; File archiEscri=null; String temporal; String operacion,op1,op2,op3; String etiquetasputs=""; int num_param_actual = 0; int c_etiqueta; public GenFinal(LinkedList<tupla_Tercetos> colaTercetos, Tablas tabla, String fichero) { int desp_total; //variable para el desplazamiento total de las tablas de simbolos archiEscri= new File(fichero); tupla_Tercetos tupla_actual; String terceto_actual; TablaSimbolos ambito_actual; //cola para ir metiendo los metodos a los que se llama LinkedList<String> colaMetodos = new LinkedList<String> (); Simbolo simbolo; TablaSimbolos tabla_aux; c_etiqueta = 0; System.out.println("Comienza la fase de generacion de codigo objeto"); //preparamos el fichero que contendra el codigo objeto try { bw= new BufferedWriter(new FileWriter(fichero)); } catch (IOException e) { System.out.println("Error fichero de salida para Codigo Objeto."); } //inicializamos el codigo objeto y lo dejamos todo preparado para leer los //tercetos del main try { bw.write("ORG 0\n"); // Inicializamos la pila al maximo puesto que es decreciente // y la guardamos en el puntero de pila bw.write ("MOVE #65535, .SP\n"); bw.write ("MOVE .SP, .IX\n"); /* creamos el RA de la clase que contiene el metodo principal, dejando * hueco para todos sus atributos, despues guardamos el IX, que apuntará * al primer atributo de la clase que contiene el metodo main * para luego poder acceder cogiendo el desplazamiento de la tabla * de simbolos */ tabla_aux = tabla.GetAmbitoGlobal(); //buscamos la tabla de la clase del metodo principal desp_total = tabla_aux.GetDesplazamiento(); //cogemos el desp de la tabla de simbolos global bw.write ("ADD #-" + desp_total + ", .SP\n"); //sumamos desp_total de la tabla de simbolos padre al SP System.out.println("guarrilla"); bw.write("MOVE .A, .SP\n"); //actualizamos SP bw.write("PUSH .IX\n"); //guardamos el IX para saber donde empiezan los atributos de la tabla de simbolos padre bw.write ("MOVE .SP, .IX\n"); //actualizamos IX //Vamos a buscar el main para que el PC //Si el analisis semantico ha validado el codigo, dentro del ambito global deberia estar el objeto main simbolo = tabla_aux.GetSimbolo("main"); String etiqueta_main; etiqueta_main = simbolo.GetEtiqueta(); bw.write("CALL /" + etiqueta_main + " ; VAMOS AL MAIN\n"); bw.write("POP .IX ; Recuperamos el marco de pila\n"); bw.write("MOVE .IX, .SP\n"); bw.write("HALT ;Cuando se vuelva del Main se terminara la ejecucion\n"); // ProcesarTercetos(colaTercetos, tabla); /* * Bucle para imprimir toda la cola de tercetos! */ System.out.println("-----------------------------------"); System.out.println("Elementos de la lista "+colaTercetos); + System.out.println("Tamano de la lista:"+colaTercetos.size()); //Iterator it2 = a.iterator(); Iterator<tupla_Tercetos> it = colaTercetos.iterator(); while (it.hasNext()) { //this.separar(it.next().GetTerceto()); - System.out.println("Terceto: "+it.next().GetTerceto()); + tupla_actual = it.next(); + System.out.println("Terceto: "+tupla_actual.GetTerceto()); System.out.println("Tabla:"+tabla.GetAmbitoGlobal().GetDesplazamiento()); - System.out.println("Desplazamiento de la tabla para temp:"+it.next().GetAmbitoActual().GetDesplazamiento()); + System.out.println("Desplazamiento de la tabla para temp:"+tupla_actual.GetAmbitoActual().GetDesplazamiento()); //System.out.println("Ambito_actual: "+it.next().GetAmbitoActual()); } System.out.println("-----------------------------------"); // Importante! sino no se guarda nada en el fichero! bw.close(); } catch (IOException e) { System.out.println("Tranquilo vaquero"); } } private void ProcesarTercetos(LinkedList<tupla_Tercetos> colaTercetos, Tablas tabla) { while (!colaTercetos.isEmpty()) { String terceto_actual; tupla_Tercetos tupla_actual; tupla_actual = colaTercetos.removeFirst(); terceto_actual = tupla_actual.GetTerceto(); TablaSimbolos ambitoterceto = tupla_actual.GetAmbitoActual(); this.separar(terceto_actual); //Esto se para el terceto en sus operandos if (operacion.compareTo("ASIGNACION") == 0) EjecutarAsignacion(op1, op2, ambitoterceto); // this.traducir(tabla); } try { /*bw.write("mens1: DATA \"Introduzca el numero:\" \n"); bw.write("eol: DATA \"\\n\"\n"+etiquetasputs); bw.write("valor_falso: DATA \"FALSE\"\n"); bw.write("valor_verdad: DATA \"TRUE\"\n"); bw.write("cadena_get: RES 1\n"); */ bw.close(); } catch (IOException e) { // TODO } } //*********************************************************************************************** private void EjecutarAsignacion(String op1, String op2, TablaSimbolos ambito_terceto) { try { Simbolo simbolo_op1 = ambito_terceto.GetSimbolo(op1); int op2ent = Integer.parseInt(op2); bw.write("ADD .IX, " + simbolo_op1.GetDesplazamiento() + "\n");//Tenemos en A la direccion donde dejamos el resultado de la asignacion bw.write("MOVE .A, R5\n"); bw.write("MOVE "+ op2 + ", [.A]\n"); bw.close(); } catch (IOException e) { // TODO } } private void separar(String linea) { int u= linea.indexOf(","); this.operacion=linea.substring(0,u); //cogemos la operación linea=linea.substring(u+1); u= linea.indexOf(","); op1=linea.substring(0,u); linea=linea.substring(u+1); u= linea.indexOf(","); op2=linea.substring(0,u); linea=linea.substring(u+1); op3=linea.substring(0,linea.indexOf("\n")); } public void traducir(Tablas tabla) { } }
false
true
public GenFinal(LinkedList<tupla_Tercetos> colaTercetos, Tablas tabla, String fichero) { int desp_total; //variable para el desplazamiento total de las tablas de simbolos archiEscri= new File(fichero); tupla_Tercetos tupla_actual; String terceto_actual; TablaSimbolos ambito_actual; //cola para ir metiendo los metodos a los que se llama LinkedList<String> colaMetodos = new LinkedList<String> (); Simbolo simbolo; TablaSimbolos tabla_aux; c_etiqueta = 0; System.out.println("Comienza la fase de generacion de codigo objeto"); //preparamos el fichero que contendra el codigo objeto try { bw= new BufferedWriter(new FileWriter(fichero)); } catch (IOException e) { System.out.println("Error fichero de salida para Codigo Objeto."); } //inicializamos el codigo objeto y lo dejamos todo preparado para leer los //tercetos del main try { bw.write("ORG 0\n"); // Inicializamos la pila al maximo puesto que es decreciente // y la guardamos en el puntero de pila bw.write ("MOVE #65535, .SP\n"); bw.write ("MOVE .SP, .IX\n"); /* creamos el RA de la clase que contiene el metodo principal, dejando * hueco para todos sus atributos, despues guardamos el IX, que apuntará * al primer atributo de la clase que contiene el metodo main * para luego poder acceder cogiendo el desplazamiento de la tabla * de simbolos */ tabla_aux = tabla.GetAmbitoGlobal(); //buscamos la tabla de la clase del metodo principal desp_total = tabla_aux.GetDesplazamiento(); //cogemos el desp de la tabla de simbolos global bw.write ("ADD #-" + desp_total + ", .SP\n"); //sumamos desp_total de la tabla de simbolos padre al SP System.out.println("guarrilla"); bw.write("MOVE .A, .SP\n"); //actualizamos SP bw.write("PUSH .IX\n"); //guardamos el IX para saber donde empiezan los atributos de la tabla de simbolos padre bw.write ("MOVE .SP, .IX\n"); //actualizamos IX //Vamos a buscar el main para que el PC //Si el analisis semantico ha validado el codigo, dentro del ambito global deberia estar el objeto main simbolo = tabla_aux.GetSimbolo("main"); String etiqueta_main; etiqueta_main = simbolo.GetEtiqueta(); bw.write("CALL /" + etiqueta_main + " ; VAMOS AL MAIN\n"); bw.write("POP .IX ; Recuperamos el marco de pila\n"); bw.write("MOVE .IX, .SP\n"); bw.write("HALT ;Cuando se vuelva del Main se terminara la ejecucion\n"); // ProcesarTercetos(colaTercetos, tabla); /* * Bucle para imprimir toda la cola de tercetos! */ System.out.println("-----------------------------------"); System.out.println("Elementos de la lista "+colaTercetos); //Iterator it2 = a.iterator(); Iterator<tupla_Tercetos> it = colaTercetos.iterator(); while (it.hasNext()) { //this.separar(it.next().GetTerceto()); System.out.println("Terceto: "+it.next().GetTerceto()); System.out.println("Tabla:"+tabla.GetAmbitoGlobal().GetDesplazamiento()); System.out.println("Desplazamiento de la tabla para temp:"+it.next().GetAmbitoActual().GetDesplazamiento()); //System.out.println("Ambito_actual: "+it.next().GetAmbitoActual()); } System.out.println("-----------------------------------"); // Importante! sino no se guarda nada en el fichero! bw.close(); } catch (IOException e) { System.out.println("Tranquilo vaquero"); } }
public GenFinal(LinkedList<tupla_Tercetos> colaTercetos, Tablas tabla, String fichero) { int desp_total; //variable para el desplazamiento total de las tablas de simbolos archiEscri= new File(fichero); tupla_Tercetos tupla_actual; String terceto_actual; TablaSimbolos ambito_actual; //cola para ir metiendo los metodos a los que se llama LinkedList<String> colaMetodos = new LinkedList<String> (); Simbolo simbolo; TablaSimbolos tabla_aux; c_etiqueta = 0; System.out.println("Comienza la fase de generacion de codigo objeto"); //preparamos el fichero que contendra el codigo objeto try { bw= new BufferedWriter(new FileWriter(fichero)); } catch (IOException e) { System.out.println("Error fichero de salida para Codigo Objeto."); } //inicializamos el codigo objeto y lo dejamos todo preparado para leer los //tercetos del main try { bw.write("ORG 0\n"); // Inicializamos la pila al maximo puesto que es decreciente // y la guardamos en el puntero de pila bw.write ("MOVE #65535, .SP\n"); bw.write ("MOVE .SP, .IX\n"); /* creamos el RA de la clase que contiene el metodo principal, dejando * hueco para todos sus atributos, despues guardamos el IX, que apuntará * al primer atributo de la clase que contiene el metodo main * para luego poder acceder cogiendo el desplazamiento de la tabla * de simbolos */ tabla_aux = tabla.GetAmbitoGlobal(); //buscamos la tabla de la clase del metodo principal desp_total = tabla_aux.GetDesplazamiento(); //cogemos el desp de la tabla de simbolos global bw.write ("ADD #-" + desp_total + ", .SP\n"); //sumamos desp_total de la tabla de simbolos padre al SP System.out.println("guarrilla"); bw.write("MOVE .A, .SP\n"); //actualizamos SP bw.write("PUSH .IX\n"); //guardamos el IX para saber donde empiezan los atributos de la tabla de simbolos padre bw.write ("MOVE .SP, .IX\n"); //actualizamos IX //Vamos a buscar el main para que el PC //Si el analisis semantico ha validado el codigo, dentro del ambito global deberia estar el objeto main simbolo = tabla_aux.GetSimbolo("main"); String etiqueta_main; etiqueta_main = simbolo.GetEtiqueta(); bw.write("CALL /" + etiqueta_main + " ; VAMOS AL MAIN\n"); bw.write("POP .IX ; Recuperamos el marco de pila\n"); bw.write("MOVE .IX, .SP\n"); bw.write("HALT ;Cuando se vuelva del Main se terminara la ejecucion\n"); // ProcesarTercetos(colaTercetos, tabla); /* * Bucle para imprimir toda la cola de tercetos! */ System.out.println("-----------------------------------"); System.out.println("Elementos de la lista "+colaTercetos); System.out.println("Tamano de la lista:"+colaTercetos.size()); //Iterator it2 = a.iterator(); Iterator<tupla_Tercetos> it = colaTercetos.iterator(); while (it.hasNext()) { //this.separar(it.next().GetTerceto()); tupla_actual = it.next(); System.out.println("Terceto: "+tupla_actual.GetTerceto()); System.out.println("Tabla:"+tabla.GetAmbitoGlobal().GetDesplazamiento()); System.out.println("Desplazamiento de la tabla para temp:"+tupla_actual.GetAmbitoActual().GetDesplazamiento()); //System.out.println("Ambito_actual: "+it.next().GetAmbitoActual()); } System.out.println("-----------------------------------"); // Importante! sino no se guarda nada en el fichero! bw.close(); } catch (IOException e) { System.out.println("Tranquilo vaquero"); } }
diff --git a/TwitterRest/src/matz/UserTimelines.java b/TwitterRest/src/matz/UserTimelines.java index 0fdb1e6..55633a2 100644 --- a/TwitterRest/src/matz/UserTimelines.java +++ b/TwitterRest/src/matz/UserTimelines.java @@ -1,151 +1,151 @@ package matz; import java.io.*; import twitter4j.Paging; import twitter4j.ResponseList; import twitter4j.Status; import twitter4j.TwitterException; import twitter4j.json.DataObjectFactory; public class UserTimelines extends TwitterRest { private static boolean testPaging = false; public final static String testPagingOption = "-t"; private static int timeLineAuthHead = 1; private static int timeLineAuthTail; private static int fullSizeTimeLine = 200; private static int testSizeTimeLine = 5; private static void setTimeLineAuthTail() { timeLineAuthTail = OAuthList.length - 1; } private static Paging setPaging(File thisUsersCurr) throws Exception { Paging paging = new Paging(); paging.setCount(testPaging? testSizeTimeLine : fullSizeTimeLine); if(thisUsersCurr.exists()) { BufferedReader cbr = new BufferedReader(new InputStreamReader(new FileInputStream(thisUsersCurr))); String curr = cbr.readLine(); paging.setSinceId(Long.parseLong(curr)); cbr.close(); } return paging; } public static boolean findAvailableAuth() { /*if (authAvailabilityCheck()) return true; int groundId = currentAuthId; int nextId = (currentAuthId == timeLineAuthTail)? timeLineAuthHead : currentAuthId + 1; //twitter = buildTwitterIns((groundId == timeLineAuthTail) ? timeLineAuthHead : groundId + 1); while(!authAvailabilityCheck(nextId)) { nextId = (nextId == timeLineAuthTail)? timeLineAuthHead : nextId + 1; if (nextId == groundId) return false; }*/ if (!authAvailabilityCheck()) { int nextId = (currentAuthId == timeLineAuthTail)? timeLineAuthHead : currentAuthId + 1; twitter = buildTwitterIns(nextId); saveAuthInfo(); if (!authAvailabilityCheck()) return false; } return true; } public static void main(String[] args) { - loadAuthInfo(); + OAuthList = loadAuthInfo(); setTimeLineAuthTail(); for (String arg : args) { if (arg == testPagingOption) testPaging = true; } try { //userList loading BufferedReader ulbr = new BufferedReader(new InputStreamReader(new FileInputStream(userListFile))); String userid = new String(); while((userid = ulbr.readLine()) != null) { if (!userList.contains(userid)) userList.add(userid); } ulbr.close(); //userDir if(!userDir.isDirectory()) userDir.mkdir(); } catch (FileNotFoundException e) { //ignore } catch (IOException e) { e.printStackTrace(); } //Twitter twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init try { //for every recorded users, get their recent tweets for (String id : userList) { while (!findAvailableAuth()) { sleepUntilReset(); } File thisUsersFile = new File(userDir,id + ".txt"); File thisUsersCurr = new File(userDir,id + ".curr.txt"); long userIdLong = Long.parseLong(id); long maxid = 1; Paging paging = setPaging(thisUsersCurr); ResponseList<Status> timeLine = null; try { timeLine = twitter.getUserTimeline(userIdLong, paging); } catch (TwitterException twe) { /* for private users, accessing their timeline will return you 401: Not Authorized error. * capture 401 and just continue it. * there are some other statuses which could halt the script, you should handle them. */ int statusCode = twe.getStatusCode(); if (statusCode == STATUS_UNAUTHORIZED || statusCode == STATUS_NOT_FOUND) { callCount(currentAuthId); continue; } else if (statusCode == STATUS_BAD_GATEWAY || statusCode == STATUS_SERVICE_UNAVAILABLE) { sleepUntilReset(authLimitWindow); } else if (statusCode == STATUS_TOO_MANY_REQUESTS || statusCode == STATUS_ENHANCE_YOUR_CALM) { int secondsUntilReset = twe.getRateLimitStatus().getSecondsUntilReset(); // getSecondsUntilReset returns seconds until limit reset in Integer long retryAfter = (long)(secondsUntilReset * 1000); if (secondsUntilReset <= 0) retryAfter = authLimitWindow; retryAfter += authRetryMargin; sleepUntilReset(retryAfter); } else { twe.printStackTrace(); throw twe; } timeLine = twitter.getUserTimeline(userIdLong, paging); } callCount(currentAuthId); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersFile, true))); for (Status status : timeLine) { long tmpid = status.getId(); maxid = (tmpid > maxid)? tmpid : maxid; String rawJSON = DataObjectFactory.getRawJSON(status); bw.write(rawJSON); bw.newLine(); } bw.close(); BufferedWriter cbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersCurr))); cbw.write(Long.toString(maxid)); cbw.close(); System.out.println(thisUsersFile); //break; } } catch (Exception e) { saveAuthInfo(); e.printStackTrace(); } saveAuthInfo(); System.out.println("Done."); } }
true
true
public static void main(String[] args) { loadAuthInfo(); setTimeLineAuthTail(); for (String arg : args) { if (arg == testPagingOption) testPaging = true; } try { //userList loading BufferedReader ulbr = new BufferedReader(new InputStreamReader(new FileInputStream(userListFile))); String userid = new String(); while((userid = ulbr.readLine()) != null) { if (!userList.contains(userid)) userList.add(userid); } ulbr.close(); //userDir if(!userDir.isDirectory()) userDir.mkdir(); } catch (FileNotFoundException e) { //ignore } catch (IOException e) { e.printStackTrace(); } //Twitter twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init try { //for every recorded users, get their recent tweets for (String id : userList) { while (!findAvailableAuth()) { sleepUntilReset(); } File thisUsersFile = new File(userDir,id + ".txt"); File thisUsersCurr = new File(userDir,id + ".curr.txt"); long userIdLong = Long.parseLong(id); long maxid = 1; Paging paging = setPaging(thisUsersCurr); ResponseList<Status> timeLine = null; try { timeLine = twitter.getUserTimeline(userIdLong, paging); } catch (TwitterException twe) { /* for private users, accessing their timeline will return you 401: Not Authorized error. * capture 401 and just continue it. * there are some other statuses which could halt the script, you should handle them. */ int statusCode = twe.getStatusCode(); if (statusCode == STATUS_UNAUTHORIZED || statusCode == STATUS_NOT_FOUND) { callCount(currentAuthId); continue; } else if (statusCode == STATUS_BAD_GATEWAY || statusCode == STATUS_SERVICE_UNAVAILABLE) { sleepUntilReset(authLimitWindow); } else if (statusCode == STATUS_TOO_MANY_REQUESTS || statusCode == STATUS_ENHANCE_YOUR_CALM) { int secondsUntilReset = twe.getRateLimitStatus().getSecondsUntilReset(); // getSecondsUntilReset returns seconds until limit reset in Integer long retryAfter = (long)(secondsUntilReset * 1000); if (secondsUntilReset <= 0) retryAfter = authLimitWindow; retryAfter += authRetryMargin; sleepUntilReset(retryAfter); } else { twe.printStackTrace(); throw twe; } timeLine = twitter.getUserTimeline(userIdLong, paging); } callCount(currentAuthId); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersFile, true))); for (Status status : timeLine) { long tmpid = status.getId(); maxid = (tmpid > maxid)? tmpid : maxid; String rawJSON = DataObjectFactory.getRawJSON(status); bw.write(rawJSON); bw.newLine(); } bw.close(); BufferedWriter cbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersCurr))); cbw.write(Long.toString(maxid)); cbw.close(); System.out.println(thisUsersFile); //break; } } catch (Exception e) { saveAuthInfo(); e.printStackTrace(); } saveAuthInfo(); System.out.println("Done."); }
public static void main(String[] args) { OAuthList = loadAuthInfo(); setTimeLineAuthTail(); for (String arg : args) { if (arg == testPagingOption) testPaging = true; } try { //userList loading BufferedReader ulbr = new BufferedReader(new InputStreamReader(new FileInputStream(userListFile))); String userid = new String(); while((userid = ulbr.readLine()) != null) { if (!userList.contains(userid)) userList.add(userid); } ulbr.close(); //userDir if(!userDir.isDirectory()) userDir.mkdir(); } catch (FileNotFoundException e) { //ignore } catch (IOException e) { e.printStackTrace(); } //Twitter twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init twitter = buildTwitterIns(timeLineAuthHead); //matz_0001, init try { //for every recorded users, get their recent tweets for (String id : userList) { while (!findAvailableAuth()) { sleepUntilReset(); } File thisUsersFile = new File(userDir,id + ".txt"); File thisUsersCurr = new File(userDir,id + ".curr.txt"); long userIdLong = Long.parseLong(id); long maxid = 1; Paging paging = setPaging(thisUsersCurr); ResponseList<Status> timeLine = null; try { timeLine = twitter.getUserTimeline(userIdLong, paging); } catch (TwitterException twe) { /* for private users, accessing their timeline will return you 401: Not Authorized error. * capture 401 and just continue it. * there are some other statuses which could halt the script, you should handle them. */ int statusCode = twe.getStatusCode(); if (statusCode == STATUS_UNAUTHORIZED || statusCode == STATUS_NOT_FOUND) { callCount(currentAuthId); continue; } else if (statusCode == STATUS_BAD_GATEWAY || statusCode == STATUS_SERVICE_UNAVAILABLE) { sleepUntilReset(authLimitWindow); } else if (statusCode == STATUS_TOO_MANY_REQUESTS || statusCode == STATUS_ENHANCE_YOUR_CALM) { int secondsUntilReset = twe.getRateLimitStatus().getSecondsUntilReset(); // getSecondsUntilReset returns seconds until limit reset in Integer long retryAfter = (long)(secondsUntilReset * 1000); if (secondsUntilReset <= 0) retryAfter = authLimitWindow; retryAfter += authRetryMargin; sleepUntilReset(retryAfter); } else { twe.printStackTrace(); throw twe; } timeLine = twitter.getUserTimeline(userIdLong, paging); } callCount(currentAuthId); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersFile, true))); for (Status status : timeLine) { long tmpid = status.getId(); maxid = (tmpid > maxid)? tmpid : maxid; String rawJSON = DataObjectFactory.getRawJSON(status); bw.write(rawJSON); bw.newLine(); } bw.close(); BufferedWriter cbw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(thisUsersCurr))); cbw.write(Long.toString(maxid)); cbw.close(); System.out.println(thisUsersFile); //break; } } catch (Exception e) { saveAuthInfo(); e.printStackTrace(); } saveAuthInfo(); System.out.println("Done."); }
diff --git a/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java b/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java index 8ec8974a..42f5a438 100644 --- a/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java +++ b/gson/src/main/java/com/google/gson/internal/bind/ReflectiveTypeAdapterFactory.java @@ -1,210 +1,210 @@ /* * Copyright (C) 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal.bind; import com.google.gson.FieldNamingStrategy; import com.google.gson.Gson; import com.google.gson.JsonSyntaxException; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.annotations.SerializedName; import com.google.gson.internal.$Gson$Types; import com.google.gson.internal.ConstructorConstructor; import com.google.gson.internal.Excluder; import com.google.gson.internal.ObjectConstructor; import com.google.gson.internal.Primitives; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.Type; import java.util.LinkedHashMap; import java.util.Map; /** * Type adapter that reflects over the fields and methods of a class. */ public final class ReflectiveTypeAdapterFactory implements TypeAdapterFactory { private final ConstructorConstructor constructorConstructor; private final FieldNamingStrategy fieldNamingPolicy; private final Excluder excluder; public ReflectiveTypeAdapterFactory(ConstructorConstructor constructorConstructor, FieldNamingStrategy fieldNamingPolicy, Excluder excluder) { this.constructorConstructor = constructorConstructor; this.fieldNamingPolicy = fieldNamingPolicy; this.excluder = excluder; } public boolean excludeField(Field f, boolean serialize) { return !excluder.excludeClass(f.getType(), serialize) && !excluder.excludeField(f, serialize); } private String getFieldName(Field f) { SerializedName serializedName = f.getAnnotation(SerializedName.class); return serializedName == null ? fieldNamingPolicy.translateName(f) : serializedName.value(); } public <T> TypeAdapter<T> create(Gson gson, final TypeToken<T> type) { Class<? super T> raw = type.getRawType(); if (!Object.class.isAssignableFrom(raw)) { return null; // it's a primitive! } ObjectConstructor<T> constructor = constructorConstructor.getConstructor(type); return new Adapter<T>(constructor, getBoundFields(gson, type, raw)); } private ReflectiveTypeAdapterFactory.BoundField createBoundField( final Gson context, final Field field, final String name, final TypeToken<?> fieldType, boolean serialize, boolean deserialize) { final boolean isPrimitive = Primitives.isPrimitive(fieldType.getRawType()); // special casing primitives here saves ~5% on Android... return new ReflectiveTypeAdapterFactory.BoundField(name, serialize, deserialize) { final TypeAdapter<?> typeAdapter = context.getAdapter(fieldType); @SuppressWarnings({"unchecked", "rawtypes"}) // the type adapter and field type always agree @Override void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException { Object fieldValue = field.get(value); TypeAdapter t = new TypeAdapterRuntimeTypeWrapper(context, this.typeAdapter, fieldType.getType()); t.write(writer, fieldValue); } @Override void read(JsonReader reader, Object value) throws IOException, IllegalAccessException { Object fieldValue = typeAdapter.read(reader); if (fieldValue != null || !isPrimitive) { field.set(value, fieldValue); } } }; } private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); - AccessibleObject.setAccessible(fields, true); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } + field.setAccessible(true); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; } static abstract class BoundField { final String name; final boolean serialized; final boolean deserialized; protected BoundField(String name, boolean serialized, boolean deserialized) { this.name = name; this.serialized = serialized; this.deserialized = deserialized; } abstract void write(JsonWriter writer, Object value) throws IOException, IllegalAccessException; abstract void read(JsonReader reader, Object value) throws IOException, IllegalAccessException; } public final class Adapter<T> extends TypeAdapter<T> { private final ObjectConstructor<T> constructor; private final Map<String, BoundField> boundFields; private Adapter(ObjectConstructor<T> constructor, Map<String, BoundField> boundFields) { this.constructor = constructor; this.boundFields = boundFields; } @Override public T read(JsonReader in) throws IOException { if (in.peek() == JsonToken.NULL) { in.nextNull(); return null; } T instance = constructor.construct(); // TODO: null out the other fields? try { in.beginObject(); while (in.hasNext()) { String name = in.nextName(); BoundField field = boundFields.get(name); if (field == null || !field.deserialized) { // TODO: define a better policy in.skipValue(); } else { field.read(in, instance); } } } catch (IllegalStateException e) { throw new JsonSyntaxException(e); } catch (IllegalAccessException e) { throw new AssertionError(e); } in.endObject(); return instance; } @Override public void write(JsonWriter out, T value) throws IOException { if (value == null) { out.nullValue(); // TODO: better policy here? return; } out.beginObject(); try { for (BoundField boundField : boundFields.values()) { if (boundField.serialized) { out.name(boundField.name); boundField.write(out, value); } } } catch (IllegalAccessException e) { throw new AssertionError(); } out.endObject(); } } }
false
true
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); AccessibleObject.setAccessible(fields, true); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; }
private Map<String, BoundField> getBoundFields(Gson context, TypeToken<?> type, Class<?> raw) { Map<String, BoundField> result = new LinkedHashMap<String, BoundField>(); if (raw.isInterface()) { return result; } Type declaredType = type.getType(); while (raw != Object.class) { Field[] fields = raw.getDeclaredFields(); for (Field field : fields) { boolean serialize = excludeField(field, true); boolean deserialize = excludeField(field, false); if (!serialize && !deserialize) { continue; } field.setAccessible(true); Type fieldType = $Gson$Types.resolve(type.getType(), raw, field.getGenericType()); BoundField boundField = createBoundField(context, field, getFieldName(field), TypeToken.get(fieldType), serialize, deserialize); BoundField previous = result.put(boundField.name, boundField); if (previous != null) { throw new IllegalArgumentException(declaredType + " declares multiple JSON fields named " + previous.name); } } type = TypeToken.get($Gson$Types.resolve(type.getType(), raw, raw.getGenericSuperclass())); raw = type.getRawType(); } return result; }
diff --git a/src/cz/muni/stanse/callgraph/CallGraph.java b/src/cz/muni/stanse/callgraph/CallGraph.java index 3861f93..625c8a4 100644 --- a/src/cz/muni/stanse/callgraph/CallGraph.java +++ b/src/cz/muni/stanse/callgraph/CallGraph.java @@ -1,208 +1,208 @@ /* * CallGraph.java * * Licensed under GPLv2. */ package cz.muni.stanse.callgraph; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.dom4j.Element; import org.jgrapht.DirectedGraph; import org.jgrapht.alg.StrongConnectivityInspector; import org.jgrapht.graph.DefaultDirectedGraph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.DirectedMultigraph; import org.jgrapht.graph.DirectedSubgraph; /** * Represents a call graph of the given set of function definitions * @author xstastn */ public class CallGraph { /** * Map representing the call graph. Procedures are specified by the String * representation of their name. */ private Map<String, List<String>> callingNames = new HashMap<String, List<String>>(); private static Logger logger = Logger.getLogger(CallGraph.class); /** * Multigraph is generated, if true. */ private boolean isMultiGraph = false; /** * Creates a new instance of CallGraph * * @param functionDefinitions The function of which the CG will be made */ public CallGraph(List<Element> functionDefinitions, boolean isMultigraph) { this.isMultiGraph = isMultigraph; for(int i=0; i<functionDefinitions.size(); i++) { - String functionName = ((Element)functionDefinitions.get(i).selectSingleNode("declarator/id")).getText(); + String functionName = ((Element)functionDefinitions.get(i).selectSingleNode("declarator/descendant-or-self::id")).getText(); Set<Element> children = new HashSet<Element>(); Collection list = functionDefinitions.get(i).selectNodes(".//functionCall"); children.addAll(list); List<String> childrenNames = new ArrayList<String>(); for(Element oneNode : children) { if(isMultiGraph || !childrenNames.contains(oneNode.node(0).getText())) { childrenNames.add(oneNode.node(0).getText()); } } if(callingNames.containsKey(functionName)) { childrenNames.addAll((Collection<String>) callingNames.get(functionName)); } callingNames.put(functionName, childrenNames); } } public CallGraph(List<Element> functionDefinitions) { this(functionDefinitions, false); } /** * Get the DirectedGraph representation for the actual call graph * @return directed graph of the actual call graph */ public DirectedGraph generateDirectedGraph() { DirectedGraph<String, DefaultEdge> graph; if(isMultiGraph) { graph = new DirectedMultigraph<String, DefaultEdge>(DefaultEdge.class); } else { graph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); } for(String functionDefinition : callingNames.keySet()) { graph.addVertex(functionDefinition); } for(String functionDefinition : callingNames.keySet()) { for(String called : callingNames.get(functionDefinition)) { if(!graph.vertexSet().contains(called)) { graph.addVertex(called); } DefaultEdge addEdge = graph.addEdge(functionDefinition, called); } } return graph; } /** * Get list of strongly connected subgaphs for the actual call graph * @return list of the strongly connected directed subgraphs */ public List<DirectedSubgraph<String, DefaultEdge>> stronglyConnected() { StrongConnectivityInspector inspector = new StrongConnectivityInspector(generateDirectedGraph()); return inspector.stronglyConnectedSubgraphs(); } /** * Generate dot source code for single directed graph * @param graph Directed graph to be transformed to dot * @return Standalone dot source */ public static String directedGraphToDot(DirectedGraph<String, DefaultEdge> graph) { String retString = "digraph stronglyConnected { \n"; retString += directedGraphToDotBody(graph); return retString + "\n}"; } /** * Generate body of the dot source code (vertices and egdes) for * the specified directed graph * * @param graph Directed graph to be transformed to dot * @return Part of the dot source */ private static String directedGraphToDotBody(DirectedGraph<String, DefaultEdge> graph) { String retString = ""; for(String vertex : graph.vertexSet()) { retString += "\""+vertex+"\"" + "\n"; } for(DefaultEdge edge : graph.edgeSet()) { retString += "\""+graph.getEdgeSource(edge) + "\" -> \"" + graph.getEdgeTarget(edge) + "\";\n"; } return retString; } /** * Represent directed subgraphs of a graph in dot format. Subgraphs are * boxed in clusters. * @param parentGraph Parent graph of the subgraphs * @param subgraphs List of the subgraphs of the parent graph * @return String representing the dot source code */ public static String directedSubgraphsToDot(DirectedGraph<String, DefaultEdge> parentGraph, List<DirectedSubgraph<String, DefaultEdge>> subgraphs) { String retString = "digraph stronglyConnected { \n "; retString += directedGraphToDotBody(parentGraph); int i=1; for(DirectedSubgraph<String, DefaultEdge> subgraph : subgraphs) { retString += "subgraph \"cluster_subset"+ i + "\" { label=\"Component "+ i + "\" \n"; for(String vertex : subgraph.vertexSet()) { retString += " \"" + vertex + "\"; "; } retString += " } \n"; i++; } retString += " } \n"; logger.debug(retString); return retString; } public String toString() { String result = new String(); for(String function : callingNames.keySet()) { result += "==================\n" +function + "\n"; result += "Calling these: \n"; for(String called : callingNames.get(function)) { result += " > "+ called + "\n"; } } return result; } public String toDot() { String result = "digraph CallGraph { \n"; for(String function : callingNames.keySet()) { for(String called : callingNames.get(function)) { result += "\""+function + "\" -> \""+ called + "\"\n"; } } result += "} \n"; logger.debug("CallGraph dot source code: "+ result); return result; } }
true
true
public CallGraph(List<Element> functionDefinitions, boolean isMultigraph) { this.isMultiGraph = isMultigraph; for(int i=0; i<functionDefinitions.size(); i++) { String functionName = ((Element)functionDefinitions.get(i).selectSingleNode("declarator/id")).getText(); Set<Element> children = new HashSet<Element>(); Collection list = functionDefinitions.get(i).selectNodes(".//functionCall"); children.addAll(list); List<String> childrenNames = new ArrayList<String>(); for(Element oneNode : children) { if(isMultiGraph || !childrenNames.contains(oneNode.node(0).getText())) { childrenNames.add(oneNode.node(0).getText()); } } if(callingNames.containsKey(functionName)) { childrenNames.addAll((Collection<String>) callingNames.get(functionName)); } callingNames.put(functionName, childrenNames); } }
public CallGraph(List<Element> functionDefinitions, boolean isMultigraph) { this.isMultiGraph = isMultigraph; for(int i=0; i<functionDefinitions.size(); i++) { String functionName = ((Element)functionDefinitions.get(i).selectSingleNode("declarator/descendant-or-self::id")).getText(); Set<Element> children = new HashSet<Element>(); Collection list = functionDefinitions.get(i).selectNodes(".//functionCall"); children.addAll(list); List<String> childrenNames = new ArrayList<String>(); for(Element oneNode : children) { if(isMultiGraph || !childrenNames.contains(oneNode.node(0).getText())) { childrenNames.add(oneNode.node(0).getText()); } } if(callingNames.containsKey(functionName)) { childrenNames.addAll((Collection<String>) callingNames.get(functionName)); } callingNames.put(functionName, childrenNames); } }
diff --git a/src/no/runsafe/nchat/command/ReplyCommand.java b/src/no/runsafe/nchat/command/ReplyCommand.java index 5969a10..3f95cde 100644 --- a/src/no/runsafe/nchat/command/ReplyCommand.java +++ b/src/no/runsafe/nchat/command/ReplyCommand.java @@ -1,47 +1,47 @@ package no.runsafe.nchat.command; import no.runsafe.framework.command.RunsafeCommand; import no.runsafe.framework.server.player.RunsafePlayer; import no.runsafe.nchat.Constants; import no.runsafe.nchat.handlers.WhisperHandler; import org.apache.commons.lang.StringUtils; public class ReplyCommand extends RunsafeCommand { public ReplyCommand(WhisperHandler whisperHandler) { super("reply", "message"); this.whisperHandler = whisperHandler; } @Override public String requiredPermission() { return "runsafe.nchat.whisper"; } @Override public String OnExecute(RunsafePlayer executor, String[] args) { RunsafePlayer whisperer = this.whisperHandler.getLastWhisperedBy(executor); if (whisperer != null) { if (this.whisperHandler.canWhisper(executor, whisperer)) { String message = StringUtils.join(args, " ", 0, args.length); this.whisperHandler.sendWhisper(executor, whisperer, message); } else - executor.sendMessage(Constants.WHISPER_TARGET_OFFLINE); + executor.sendMessage(String.format(Constants.WHISPER_TARGET_OFFLINE, whisperer.getPrettyName())); } else { executor.sendMessage(Constants.WHISPER_NO_REPLY_TARGET); } return null; } private WhisperHandler whisperHandler; }
true
true
public String OnExecute(RunsafePlayer executor, String[] args) { RunsafePlayer whisperer = this.whisperHandler.getLastWhisperedBy(executor); if (whisperer != null) { if (this.whisperHandler.canWhisper(executor, whisperer)) { String message = StringUtils.join(args, " ", 0, args.length); this.whisperHandler.sendWhisper(executor, whisperer, message); } else executor.sendMessage(Constants.WHISPER_TARGET_OFFLINE); } else { executor.sendMessage(Constants.WHISPER_NO_REPLY_TARGET); } return null; }
public String OnExecute(RunsafePlayer executor, String[] args) { RunsafePlayer whisperer = this.whisperHandler.getLastWhisperedBy(executor); if (whisperer != null) { if (this.whisperHandler.canWhisper(executor, whisperer)) { String message = StringUtils.join(args, " ", 0, args.length); this.whisperHandler.sendWhisper(executor, whisperer, message); } else executor.sendMessage(String.format(Constants.WHISPER_TARGET_OFFLINE, whisperer.getPrettyName())); } else { executor.sendMessage(Constants.WHISPER_NO_REPLY_TARGET); } return null; }
diff --git a/src/jogl/classes/jogamp/opengl/GLContextImpl.java b/src/jogl/classes/jogamp/opengl/GLContextImpl.java index e279c0423..98b9ede36 100644 --- a/src/jogl/classes/jogamp/opengl/GLContextImpl.java +++ b/src/jogl/classes/jogamp/opengl/GLContextImpl.java @@ -1,1920 +1,1920 @@ /* * Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved. * Copyright (c) 2010 JogAmp Community. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistribution of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistribution in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Sun Microsystems, Inc. or the names of * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN * MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR * ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR * DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, * ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF * SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed or intended for use * in the design, construction, operation or maintenance of any nuclear * facility. * * Sun gratefully acknowledges that this software was originally authored * and developed by Kenneth Bradley Russell and Christopher John Kline. */ package jogamp.opengl; import java.nio.ByteBuffer; import java.nio.IntBuffer; import java.util.HashMap; import java.util.Map; import com.jogamp.common.os.DynamicLookupHelper; import com.jogamp.common.os.Platform; import com.jogamp.common.util.ReflectionUtil; import com.jogamp.common.util.VersionNumber; import com.jogamp.common.util.locks.RecursiveLock; import com.jogamp.gluegen.runtime.FunctionAddressResolver; import com.jogamp.gluegen.runtime.ProcAddressTable; import com.jogamp.gluegen.runtime.opengl.GLNameResolver; import com.jogamp.gluegen.runtime.opengl.GLProcAddressResolver; import com.jogamp.opengl.GLExtensions; import com.jogamp.opengl.GLRendererQuirks; import javax.media.nativewindow.AbstractGraphicsConfiguration; import javax.media.nativewindow.AbstractGraphicsDevice; import javax.media.nativewindow.NativeSurface; import javax.media.opengl.GL; import javax.media.opengl.GL2ES2; import javax.media.opengl.GL2GL3; import javax.media.opengl.GLCapabilitiesImmutable; import javax.media.opengl.GLContext; import javax.media.opengl.GLDebugListener; import javax.media.opengl.GLDebugMessage; import javax.media.opengl.GLDrawable; import javax.media.opengl.GLException; import javax.media.opengl.GLPipelineFactory; import javax.media.opengl.GLProfile; public abstract class GLContextImpl extends GLContext { /** * Context full qualified name: display_type + display_connection + major + minor + ctp. * This is the key for all cached GL ProcAddressTables, etc, to support multi display/device setups. */ private String contextFQN; private int additionalCtxCreationFlags; // Cache of the functions that are available to be called at the current // moment in time protected ExtensionAvailabilityCache extensionAvailability; // Table that holds the addresses of the native C-language entry points for // OpenGL functions. private ProcAddressTable glProcAddressTable; private String glRenderer; private String glRendererLowerCase; private String glVersion; // Tracks creation and initialization of buffer objects to avoid // repeated glGet calls upon glMapBuffer operations private GLBufferSizeTracker bufferSizeTracker; // Singleton - Set by GLContextShareSet private final GLBufferStateTracker bufferStateTracker = new GLBufferStateTracker(); private final GLStateTracker glStateTracker = new GLStateTracker(); private GLDebugMessageHandler glDebugHandler = null; private final int[] boundFBOTarget = new int[] { 0, 0 }; // { draw, read } private int defaultVAO = 0; protected GLDrawableImpl drawable; protected GLDrawableImpl drawableRead; protected GL gl; protected static final Object mappedContextTypeObjectLock; protected static final HashMap<String, ExtensionAvailabilityCache> mappedExtensionAvailabilityCache; protected static final HashMap<String, ProcAddressTable> mappedGLProcAddress; protected static final HashMap<String, ProcAddressTable> mappedGLXProcAddress; static { mappedContextTypeObjectLock = new Object(); mappedExtensionAvailabilityCache = new HashMap<String, ExtensionAvailabilityCache>(); mappedGLProcAddress = new HashMap<String, ProcAddressTable>(); mappedGLXProcAddress = new HashMap<String, ProcAddressTable>(); } public static void shutdownImpl() { mappedExtensionAvailabilityCache.clear(); mappedGLProcAddress.clear(); mappedGLXProcAddress.clear(); } public GLContextImpl(GLDrawableImpl drawable, GLContext shareWith) { super(); if (shareWith != null) { GLContextShareSet.registerSharing(this, shareWith); } GLContextShareSet.synchronizeBufferObjectSharing(shareWith, this); this.drawable = drawable; if(null != drawable) { drawable.associateContext(this, true); } this.drawableRead = drawable; this.glDebugHandler = new GLDebugMessageHandler(this); } @Override protected void resetStates() { // Because we don't know how many other contexts we might be // sharing with (and it seems too complicated to implement the // GLObjectTracker's ref/unref scheme for the buffer-related // optimizations), simply clear the cache of known buffers' sizes // when we destroy contexts if (bufferSizeTracker != null) { bufferSizeTracker.clearCachedBufferSizes(); } if (bufferStateTracker != null) { // <init> bufferStateTracker.clearBufferObjectState(); } if (glStateTracker != null) { // <init> glStateTracker.clearStates(false); } extensionAvailability = null; glProcAddressTable = null; gl = null; contextFQN = null; additionalCtxCreationFlags = 0; glRenderer = ""; glRendererLowerCase = glRenderer; if (boundFBOTarget != null) { // <init> boundFBOTarget[0] = 0; // draw boundFBOTarget[1] = 0; // read } super.resetStates(); } @Override public final GLDrawable setGLReadDrawable(GLDrawable read) { if(!isGLReadDrawableAvailable()) { throw new GLException("Setting read drawable feature not available"); } final boolean lockHeld = lock.isOwner(Thread.currentThread()); if(lockHeld) { release(); } else if(lock.isLockedByOtherThread()) { // still could glitch .. throw new GLException("GLContext current by other thread ("+lock.getOwner()+"), operation not allowed."); } final GLDrawable old = drawableRead; drawableRead = ( null != read ) ? (GLDrawableImpl) read : drawable; if(lockHeld) { makeCurrent(); } return old; } @Override public final GLDrawable getGLReadDrawable() { return drawableRead; } @Override public final GLDrawable setGLDrawable(GLDrawable readWrite, boolean setWriteOnly) { if( drawable == readWrite && ( setWriteOnly || drawableRead == readWrite ) ) { return drawable; // no change. } final Thread currentThread = Thread.currentThread(); final boolean lockHeld = lock.isOwner(currentThread); if(lockHeld) { release(); } else if(lock.isLockedByOtherThread()) { // still could glitch .. throw new GLException("GLContext current by other thread "+lock.getOwner().getName()+", operation not allowed on this thread "+currentThread.getName()); } if( !setWriteOnly || drawableRead == drawable ) { // if !setWriteOnly || !explicitReadDrawable drawableRead = (GLDrawableImpl) readWrite; } final GLDrawableImpl old = drawable; if( null != old ) { old.associateContext(this, false); } drawableRetargeted |= null != drawable && readWrite != drawable; drawable = (GLDrawableImpl) readWrite ; if( null != drawable ) { drawable.associateContext(this, true); if( lockHeld ) { makeCurrent(); } } return old; } @Override public final GLDrawable getGLDrawable() { return drawable; } public final GLDrawableImpl getDrawableImpl() { return (GLDrawableImpl) getGLDrawable(); } @Override public final GL getGL() { return gl; } @Override public GL setGL(GL gl) { if(DEBUG) { String sgl1 = (null!=this.gl)?this.gl.getClass().getSimpleName()+", "+this.gl.toString():"<null>"; String sgl2 = (null!=gl)?gl.getClass().getSimpleName()+", "+gl.toString():"<null>"; Exception e = new Exception("Info: setGL (OpenGL "+getGLVersion()+"): "+Thread.currentThread().getName()+", "+sgl1+" -> "+sgl2); e.printStackTrace(); } this.gl = gl; return gl; } /** * Call this method to notify the OpenGL context * that the drawable has changed (size or position). * * <p> * This is currently being used and overridden by Mac OSX, * which issues the {@link jogamp.opengl.macosx.cgl.CGL#updateContext(long) NSOpenGLContext update()} call. * </p> * * @throws GLException */ protected void drawableUpdatedNotify() throws GLException { } public abstract Object getPlatformGLExtensions(); // Note: the surface is locked within [makeCurrent .. swap .. release] @Override public void release() throws GLException { release(false); } private void release(boolean inDestruction) throws GLException { if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[release.0]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+", inDestruction: "+inDestruction+", "+lock); } if ( !lock.isOwner(Thread.currentThread()) ) { final String msg = getThreadName() +": Context not current on current thread, obj " + toHexString(hashCode())+", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+", inDestruction: "+inDestruction+", "+lock; if( DEBUG_TRACE_SWITCH ) { System.err.println(msg); if( null != lastCtxReleaseStack ) { System.err.print("Last release call: "); lastCtxReleaseStack.printStackTrace(); } else { System.err.println("Last release call: NONE"); } } throw new GLException(msg); } Throwable drawableContextMadeCurrentException = null; final boolean actualRelease = ( inDestruction || lock.getHoldCount() == 1 ) && 0 != contextHandle; try { if( actualRelease ) { if( !inDestruction ) { try { contextMadeCurrent(false); } catch (Throwable t) { drawableContextMadeCurrentException = t; } } releaseImpl(); } } finally { // exception prone .. if( actualRelease ) { setCurrent(null); } drawable.unlockSurface(); lock.unlock(); if( DEBUG_TRACE_SWITCH ) { final String msg = getThreadName() +": GLContext.ContextSwitch[release.X]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - "+(actualRelease?"switch":"keep ")+" - "+lock; lastCtxReleaseStack = new Throwable(msg); if( TRACE_SWITCH ) { System.err.println(msg); // Thread.dumpStack(); } } } if(null != drawableContextMadeCurrentException) { throw new GLException("GLContext.release(false) during GLDrawableImpl.contextMadeCurrent(this, false)", drawableContextMadeCurrentException); } } private Throwable lastCtxReleaseStack = null; protected abstract void releaseImpl() throws GLException; @Override public final void destroy() { if ( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName() + ": GLContextImpl.destroy.0: obj " + toHexString(hashCode()) + ", ctx " + toHexString(contextHandle) + ", surf "+toHexString(drawable.getHandle())+", isShared "+GLContextShareSet.isShared(this)+" - "+lock); } if (contextHandle != 0) { final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock: "+drawable); } Throwable drawableContextRealizedException = null; try { // Must hold the lock around the destroy operation to make sure we // don't destroy the context while another thread renders to it. lock.lock(); // holdCount++ -> 1 - n (1: not locked, 2-n: destroy while rendering) if ( lock.getHoldCount() > 2 ) { final String msg = getThreadName() + ": GLContextImpl.destroy: obj " + toHexString(hashCode()) + ", ctx " + toHexString(contextHandle); if ( DEBUG_TRACE_SWITCH ) { System.err.println(msg+" - Lock was hold more than once - makeCurrent/release imbalance: "+lock); Thread.dumpStack(); } } try { // release current context if(lock.getHoldCount() == 1) { // needs current context to disable debug handler makeCurrent(); } try { contextRealized(false); drawable.associateContext(this, false); } catch (Throwable t) { drawableContextRealizedException = t; } if(0 != defaultVAO) { int[] tmp = new int[] { defaultVAO }; gl.getGL2GL3().glBindVertexArray(0); gl.getGL2GL3().glDeleteVertexArrays(1, tmp, 0); defaultVAO = 0; } glDebugHandler.enable(false); if(lock.getHoldCount() > 1) { // pending release() after makeCurrent() release(true); } destroyImpl(); contextHandle = 0; glDebugHandler = null; // this maybe impl. in a platform specific way to release remaining shared ctx. if(GLContextShareSet.contextDestroyed(this) && !GLContextShareSet.hasCreatedSharedLeft(this)) { GLContextShareSet.unregisterSharing(this); } } finally { lock.unlock(); if ( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName() + ": GLContextImpl.destroy.X: obj " + toHexString(hashCode()) + ", ctx " + toHexString(contextHandle) + ", isShared "+GLContextShareSet.isShared(this)+" - "+lock); } } } finally { drawable.unlockSurface(); } if(null != drawableContextRealizedException) { throw new GLException("GLContext.destroy() during GLDrawableImpl.contextRealized(this, false)", drawableContextRealizedException); } } resetStates(); } protected abstract void destroyImpl() throws GLException; @Override public final void copy(GLContext source, int mask) throws GLException { if (source.getHandle() == 0) { throw new GLException("Source OpenGL context has not been created"); } if (getHandle() == 0) { throw new GLException("Destination OpenGL context has not been created"); } final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { // this would be odd .. throw new GLException("Surface not ready to lock"); } try { copyImpl(source, mask); } finally { drawable.unlockSurface(); } } protected abstract void copyImpl(GLContext source, int mask) throws GLException; //---------------------------------------------------------------------- // /** * {@inheritDoc} * <p> * MakeCurrent functionality, which also issues the creation of the actual OpenGL context. * </p> * The complete callgraph for general OpenGL context creation is:<br> * <ul> * <li> {@link #makeCurrent} <i>GLContextImpl</i></li> * <li> {@link #makeCurrentImpl} <i>Platform Implementation</i></li> * <li> {@link #create} <i>Platform Implementation</i></li> * <li> If <code>ARB_create_context</code> is supported: * <ul> * <li> {@link #createContextARB} <i>GLContextImpl</i></li> * <li> {@link #createContextARBImpl} <i>Platform Implementation</i></li> * </ul></li> * </ul><br> * * Once at startup, ie triggered by the singleton constructor of a {@link GLDrawableFactoryImpl} specialization, * calling {@link #createContextARB} will query all available OpenGL versions:<br> * <ul> * <li> <code>FOR ALL GL* DO</code>: * <ul> * <li> {@link #createContextARBMapVersionsAvailable} * <ul> * <li> {@link #createContextARBVersions}</li> * </ul></li> * <li> {@link #mapVersionAvailable}</li> * </ul></li> * </ul><br> * * @see #makeCurrentImpl * @see #create * @see #createContextARB * @see #createContextARBImpl * @see #mapVersionAvailable * @see #destroyContextARBImpl */ @Override public int makeCurrent() throws GLException { if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.0]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - "+lock); } // Note: the surface is locked within [makeCurrent .. swap .. release] final int lockRes = drawable.lockSurface(); if (NativeSurface.LOCK_SURFACE_NOT_READY >= lockRes) { if( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X1]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - Surface Not Ready - CONTEXT_NOT_CURRENT - "+lock); } return CONTEXT_NOT_CURRENT; } boolean unlockContextAndSurface = true; // Must be cleared if successful, otherwise finally block will release context and surface! int res = CONTEXT_NOT_CURRENT; try { if (0 == drawable.getHandle()) { throw new GLException("drawable has invalid handle: "+drawable); } if (NativeSurface.LOCK_SURFACE_CHANGED == lockRes) { drawable.updateHandle(); } if ( drawable.isRealized() ) { lock.lock(); try { // One context can only be current by one thread, // and one thread can only have one context current! final GLContext current = getCurrent(); if (current != null) { if (current == this) { // implicit recursive locking! // Assume we don't need to make this context current again // For Mac OS X, however, we need to update the context to track resizes drawableUpdatedNotify(); unlockContextAndSurface = false; // success if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X2]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - keep - CONTEXT_CURRENT - "+lock); } return CONTEXT_CURRENT; } else { current.release(); } } res = makeCurrentWithinLock(lockRes); unlockContextAndSurface = CONTEXT_NOT_CURRENT == res; // success ? /** * FIXME: refactor dependence on Java 2D / JOGL bridge if ( tracker != null && res == CONTEXT_CURRENT_NEW ) { // Increase reference count of GLObjectTracker tracker.ref(); } */ } catch (RuntimeException e) { unlockContextAndSurface = true; throw e; } finally { if (unlockContextAndSurface) { if( DEBUG_TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.1]: Context lock.unlock() due to error, res "+makeCurrentResultToString(res)+", "+lock); } lock.unlock(); } } } /* if ( drawable.isRealized() ) */ } catch (RuntimeException e) { unlockContextAndSurface = true; throw e; } finally { if (unlockContextAndSurface) { drawable.unlockSurface(); } } if (res != CONTEXT_NOT_CURRENT) { setCurrent(this); if(res == CONTEXT_CURRENT_NEW) { // check if the drawable's and the GL's GLProfile are equal // throws an GLException if not getGLDrawable().getGLProfile().verifyEquality(gl.getGLProfile()); glDebugHandler.init( isGL2GL3() && isGLDebugEnabled() ); if(DEBUG_GL) { gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Debug", null, gl, null) ); if(glDebugHandler.isEnabled()) { glDebugHandler.addListener(new GLDebugMessageHandler.StdErrGLDebugListener(true)); } } if(TRACE_GL) { gl = gl.getContext().setGL( GLPipelineFactory.create("javax.media.opengl.Trace", null, gl, new Object[] { System.err } ) ); } contextRealized(true); } contextMadeCurrent(true); /* FIXME: refactor dependence on Java 2D / JOGL bridge // Try cleaning up any stale server-side OpenGL objects // FIXME: not sure what to do here if this throws if (deletedObjectTracker != null) { deletedObjectTracker.clean(getGL()); } */ } if( TRACE_SWITCH ) { System.err.println(getThreadName() +": GLContext.ContextSwitch[makeCurrent.X3]: obj " + toHexString(hashCode()) + ", ctx "+toHexString(contextHandle)+", surf "+toHexString(drawable.getHandle())+" - switch - "+makeCurrentResultToString(res)+" - "+lock); } return res; } private final int makeCurrentWithinLock(int surfaceLockRes) throws GLException { if (!isCreated()) { if(DEBUG_GL) { // only impacts w/ createContextARB(..) additionalCtxCreationFlags |= GLContext.CTX_OPTION_DEBUG ; } final GLContextImpl shareWith = (GLContextImpl) GLContextShareSet.getShareContext(this); if (null != shareWith) { shareWith.getDrawableImpl().lockSurface(); } final boolean created; try { created = createImpl(shareWith); // may throws exception if fails! if( created && isGL3core() ) { // Due to GL 3.1 core spec: E.1. DEPRECATED AND REMOVED FEATURES (p 296), // GL 3.2 core spec: E.2. DEPRECATED AND REMOVED FEATURES (p 331) // there is no more default VAO buffer 0 bound, hence generating and binding one // to avoid INVALID_OPERATION at VertexAttribPointer. // More clear is GL 4.3 core spec: 10.4 (p 307). final int[] tmp = new int[1]; gl.getGL2GL3().glGenVertexArrays(1, tmp, 0); defaultVAO = tmp[0]; gl.getGL2GL3().glBindVertexArray(defaultVAO); } } finally { if (null != shareWith) { shareWith.getDrawableImpl().unlockSurface(); } } if ( DEBUG_TRACE_SWITCH ) { if(created) { System.err.println(getThreadName() + ": Create GL context OK: obj " + toHexString(hashCode()) + ", ctx " + toHexString(contextHandle) + ", surf "+toHexString(drawable.getHandle())+" for " + getClass().getName()+" - "+getGLVersion()); // Thread.dumpStack(); } else { System.err.println(getThreadName() + ": Create GL context FAILED obj " + toHexString(hashCode()) + ", surf "+toHexString(drawable.getHandle())+" for " + getClass().getName()); } } if(!created) { return CONTEXT_NOT_CURRENT; } // finalize mapping the available GLVersions, in case it's not done yet { final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice device = config.getScreen().getDevice(); // Non ARB desktop profiles may not have been registered if( !GLContext.getAvailableGLVersionsSet(device) ) { // not yet set if( 0 == ( ctxOptions & GLContext.CTX_PROFILE_ES) ) { // not ES profile final int reqMajor; final int reqProfile; if( ctxVersion.compareTo(Version30) <= 0 ) { reqMajor = 2; } else { reqMajor = ctxVersion.getMajor(); } if( 0 != ( ctxOptions & GLContext.CTX_PROFILE_CORE) ) { reqProfile = GLContext.CTX_PROFILE_CORE; } else { reqProfile = GLContext.CTX_PROFILE_COMPAT; } GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); GLContext.setAvailableGLVersionsSet(device); if (DEBUG) { System.err.println(getThreadName() + ": createContextOLD-MapVersionsAvailable HAVE: " + device+" -> "+reqMajor+"."+reqProfile+ " -> "+getGLVersion()); } } } } GLContextShareSet.contextCreated(this); return CONTEXT_CURRENT_NEW; } makeCurrentImpl(); return CONTEXT_CURRENT; } protected abstract void makeCurrentImpl() throws GLException; /** * @see GLDrawableImpl#contextRealized(GLContext, boolean) */ protected void contextRealized(boolean realized) { drawable.contextRealized(this, realized); } /** * @see GLDrawableImpl#contextMadeCurrent(GLContext, boolean) */ protected void contextMadeCurrent(boolean current) { drawable.contextMadeCurrent(this, current); } /** * Platform dependent entry point for context creation.<br> * * This method is called from {@link #makeCurrentWithinLock()} .. {@link #makeCurrent()} .<br> * * The implementation shall verify this context with a * <code>MakeContextCurrent</code> call.<br> * * The implementation <b>must</b> leave the context current.<br> * * @param share the shared context or null * @return the valid and current context if successful, or null * @throws GLException */ protected abstract boolean createImpl(GLContextImpl sharedWith) throws GLException ; /** * Platform dependent but harmonized implementation of the <code>ARB_create_context</code> * mechanism to create a context.<br> * * This method is called from {@link #createContextARB}, {@link #createImpl(GLContextImpl)} .. {@link #makeCurrent()} .<br> * * The implementation shall verify this context with a * <code>MakeContextCurrent</code> call.<br> * * The implementation <b>must</b> leave the context current.<br> * * @param share the shared context or null * @param direct flag if direct is requested * @param ctxOptionFlags <code>ARB_create_context</code> related, see references below * @param major major number * @param minor minor number * @return the valid and current context if successful, or null * * @see #makeCurrent * @see #CTX_PROFILE_COMPAT * @see #CTX_OPTION_FORWARD * @see #CTX_OPTION_DEBUG * @see #makeCurrentImpl * @see #create * @see #createContextARB * @see #createContextARBImpl * @see #destroyContextARBImpl */ protected abstract long createContextARBImpl(long share, boolean direct, int ctxOptionFlags, int major, int minor); /** * Destroy the context created by {@link #createContextARBImpl}. * * @see #makeCurrent * @see #makeCurrentImpl * @see #create * @see #createContextARB * @see #createContextARBImpl * @see #destroyContextARBImpl */ protected abstract void destroyContextARBImpl(long context); /** * Platform independent part of using the <code>ARB_create_context</code> * mechanism to create a context.<br> * * The implementation of {@link #create} shall use this protocol in case the platform supports <code>ARB_create_context</code>.<br> * * This method may call {@link #createContextARBImpl} and {@link #destroyContextARBImpl}. <br> * * This method will also query all available native OpenGL context when first called,<br> * usually the first call should happen with the shared GLContext of the DrawableFactory.<br> * * The implementation makes the context current, if successful<br> * * @see #makeCurrentImpl * @see #create * @see #createContextARB * @see #createContextARBImpl * @see #destroyContextARBImpl */ protected final long createContextARB(final long share, final boolean direct) { final AbstractGraphicsConfiguration config = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice device = config.getScreen().getDevice(); if (DEBUG) { System.err.println(getThreadName() + ": createContextARB: mappedVersionsAvailableSet("+device.getConnection()+"): "+ GLContext.getAvailableGLVersionsSet(device)); } if ( !GLContext.getAvailableGLVersionsSet(device) ) { if(!mapGLVersions(device)) { // none of the ARB context creation calls was successful, bail out return 0; } } final GLCapabilitiesImmutable glCaps = (GLCapabilitiesImmutable) config.getChosenCapabilities(); final int[] reqMajorCTP = new int[] { 0, 0 }; getRequestMajorAndCompat(glCaps.getGLProfile(), reqMajorCTP); int _major[] = { 0 }; int _minor[] = { 0 }; int _ctp[] = { 0 }; long _ctx = 0; if( GLContext.getAvailableGLVersion(device, reqMajorCTP[0], reqMajorCTP[1], _major, _minor, _ctp)) { _ctp[0] |= additionalCtxCreationFlags; _ctx = createContextARBImpl(share, direct, _ctp[0], _major[0], _minor[0]); if(0!=_ctx) { setGLFunctionAvailability(true, _major[0], _minor[0], _ctp[0], false); } } return _ctx; } private final boolean mapGLVersions(AbstractGraphicsDevice device) { synchronized (GLContext.deviceVersionAvailable) { final long t0 = ( DEBUG ) ? System.nanoTime() : 0; boolean success = false; // Following GLProfile.GL_PROFILE_LIST_ALL order of profile detection { GL4bc, GL3bc, GL2, GL4, GL3, GL2GL3, GLES2, GL2ES2, GLES1, GL2ES1 } boolean hasGL4bc = false; boolean hasGL3bc = false; boolean hasGL2 = false; boolean hasGL4 = false; boolean hasGL3 = false; // Even w/ PROFILE_ALIASING, try to use true core GL profiles // ensuring proper user behavior across platforms due to different feature sets! // if(!hasGL4) { hasGL4 = createContextARBMapVersionsAvailable(4, CTX_PROFILE_CORE); // GL4 success |= hasGL4; if(hasGL4) { // Map all lower compatible profiles: GL3 GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); if(PROFILE_ALIASING) { hasGL3 = true; } resetStates(); // clean context states, since creation was temporary } } if(!hasGL3) { hasGL3 = createContextARBMapVersionsAvailable(3, CTX_PROFILE_CORE); // GL3 success |= hasGL3; if(hasGL3) { resetStates(); // clean this context states, since creation was temporary } } if(!hasGL4bc) { hasGL4bc = createContextARBMapVersionsAvailable(4, CTX_PROFILE_COMPAT); // GL4bc success |= hasGL4bc; if(hasGL4bc) { // Map all lower compatible profiles: GL3bc, GL2, GL4, GL3 GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_COMPAT, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); GLContext.mapAvailableGLVersion(device, 2, CTX_PROFILE_COMPAT, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); if(!hasGL4) { GLContext.mapAvailableGLVersion(device, 4, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); } if(!hasGL3) { GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); } if(PROFILE_ALIASING) { hasGL3bc = true; hasGL2 = true; hasGL4 = true; hasGL3 = true; } resetStates(); // clean this context states, since creation was temporary } } if(!hasGL3bc) { hasGL3bc = createContextARBMapVersionsAvailable(3, CTX_PROFILE_COMPAT); // GL3bc success |= hasGL3bc; if(hasGL3bc) { // Map all lower compatible profiles: GL2 and GL3 GLContext.mapAvailableGLVersion(device, 2, CTX_PROFILE_COMPAT, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); if(!hasGL3) { GLContext.mapAvailableGLVersion(device, 3, CTX_PROFILE_CORE, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); } if(PROFILE_ALIASING) { hasGL2 = true; hasGL3 = true; } resetStates(); // clean this context states, since creation was temporary } } if(!hasGL2) { hasGL2 = createContextARBMapVersionsAvailable(2, CTX_PROFILE_COMPAT); // GL2 success |= hasGL2; if(hasGL2) { resetStates(); // clean this context states, since creation was temporary } } if(success) { // only claim GL versions set [and hence detected] if ARB context creation was successful GLContext.setAvailableGLVersionsSet(device); if(DEBUG) { final long t1 = System.nanoTime(); System.err.println("GLContextImpl.mapGLVersions: "+device+", profileAliasing: "+PROFILE_ALIASING+", total "+(t1-t0)/1e6 +"ms"); System.err.println(GLContext.dumpAvailableGLVersions(null).toString()); } } else if (DEBUG) { System.err.println(getThreadName() + ": createContextARB-MapVersions NONE for :"+device); } return success; } } /** * Note: Since context creation is temporary, caller need to issue {@link #resetStates()}, if creation was successful, i.e. returns true. * This method does not reset the states, allowing the caller to utilize the state variables. **/ private final boolean createContextARBMapVersionsAvailable(int reqMajor, int reqProfile) { long _context; int ctp = CTX_IS_ARB_CREATED; if(CTX_PROFILE_COMPAT == reqProfile) { ctp |= CTX_PROFILE_COMPAT ; } else { ctp |= CTX_PROFILE_CORE ; } // To ensure GL profile compatibility within the JOGL application // we always try to map against the highest GL version, // so the user can always cast to the highest available one. int majorMax, minorMax; int majorMin, minorMin; int major[] = new int[1]; int minor[] = new int[1]; if( 4 == reqMajor ) { majorMax=4; minorMax=GLContext.getMaxMinor(majorMax); majorMin=4; minorMin=0; } else if( 3 == reqMajor ) { majorMax=3; minorMax=GLContext.getMaxMinor(majorMax); majorMin=3; minorMin=1; } else /* if( glp.isGL2() ) */ { // our minimum desktop OpenGL runtime requirements are 1.1, // nevertheless we restrict ARB context creation to 2.0 to spare us futile attempts majorMax=3; minorMax=0; majorMin=2; minorMin=0; } _context = createContextARBVersions(0, true, ctp, /* max */ majorMax, minorMax, /* min */ majorMin, minorMin, /* res */ major, minor); if( 0 == _context && CTX_PROFILE_CORE == reqProfile && !PROFILE_ALIASING ) { // try w/ FORWARD instead of CORE ctp &= ~CTX_PROFILE_CORE ; ctp |= CTX_OPTION_FORWARD ; _context = createContextARBVersions(0, true, ctp, /* max */ majorMax, minorMax, /* min */ majorMin, minorMin, /* res */ major, minor); if( 0 == _context ) { // Try a compatible one .. even though not requested .. last resort ctp &= ~CTX_PROFILE_CORE ; ctp &= ~CTX_OPTION_FORWARD ; ctp |= CTX_PROFILE_COMPAT ; _context = createContextARBVersions(0, true, ctp, /* max */ majorMax, minorMax, /* min */ majorMin, minorMin, /* res */ major, minor); } } final boolean res; if( 0 != _context ) { AbstractGraphicsDevice device = drawable.getNativeSurface().getGraphicsConfiguration().getScreen().getDevice(); // ctxMajorVersion, ctxMinorVersion, ctxOptions is being set by // createContextARBVersions(..) -> setGLFunctionAvailbility(..) -> setContextVersion(..) GLContext.mapAvailableGLVersion(device, reqMajor, reqProfile, ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions); destroyContextARBImpl(_context); if (DEBUG) { System.err.println(getThreadName() + ": createContextARB-MapVersionsAvailable HAVE: " +reqMajor+"."+reqProfile+ " -> "+getGLVersion()); } res = true; } else { if (DEBUG) { System.err.println(getThreadName() + ": createContextARB-MapVersionsAvailable NOPE: "+reqMajor+"."+reqProfile); } res = false; } return res; } private final long createContextARBVersions(long share, boolean direct, int ctxOptionFlags, int majorMax, int minorMax, int majorMin, int minorMin, int major[], int minor[]) { major[0]=majorMax; minor[0]=minorMax; long _context=0; while ( GLContext.isValidGLVersion(major[0], minor[0]) && ( major[0]>majorMin || major[0]==majorMin && minor[0] >=minorMin ) ) { if (DEBUG) { System.err.println(getThreadName() + ": createContextARBVersions: share "+share+", direct "+direct+", version "+major[0]+"."+minor[0]); } _context = createContextARBImpl(share, direct, ctxOptionFlags, major[0], minor[0]); if(0 != _context) { if( setGLFunctionAvailability(true, major[0], minor[0], ctxOptionFlags, true) ) { break; } else { destroyContextARBImpl(_context); _context = 0; } } if(!GLContext.decrementGLVersion(major, minor)) { break; } } return _context; } //---------------------------------------------------------------------- // Managing the actual OpenGL version, usually figured at creation time. // As a last resort, the GL_VERSION string may be used .. // /** * If major > 0 || minor > 0 : Use passed values, determined at creation time * Otherwise .. don't touch .. */ private final void setContextVersion(int major, int minor, int ctp, boolean setVersionString) { if ( 0 == ctp ) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } if (!GLContext.isValidGLVersion(major, minor)) { throw new GLException("Invalid GL Version "+major+"."+minor+", ctp "+toHexString(ctp)); } ctxVersion = new VersionNumber(major, minor, 0); ctxOptions = ctp; if(setVersionString) { ctxVersionString = getGLVersion(major, minor, ctxOptions, gl.glGetString(GL.GL_VERSION)); ctxGLSLVersion = null; if(major >= 2) { // >= ES2 || GL2.0 final String glslVersion = gl.glGetString(GL2ES2.GL_SHADING_LANGUAGE_VERSION); if( null != glslVersion ) { ctxGLSLVersion = new VersionNumber(glslVersion, "."); if( ctxGLSLVersion.getMajor() < 1 ) { ctxGLSLVersion = null; // failed .. } } } if( null == ctxGLSLVersion ){ final int[] sver = new int[2]; getStaticGLSLVersionNumber(major, minor, ctxOptions, sver); ctxGLSLVersion = new VersionNumber(sver[0], sver[1], 0); } } } //---------------------------------------------------------------------- // Helpers for various context implementations // private Object createInstance(GLProfile glp, String suffix, Class<?>[] cstrArgTypes, Object[] cstrArgs) { return ReflectionUtil.createInstance(glp.getGLImplBaseClassName()+suffix, cstrArgTypes, cstrArgs, getClass().getClassLoader()); } private boolean verifyInstance(GLProfile glp, String suffix, Object instance) { return ReflectionUtil.instanceOf(instance, glp.getGLImplBaseClassName()+suffix); } /** Create the GL for this context. */ protected GL createGL(GLProfile glp) { final GL gl = (GL) createInstance(glp, "Impl", new Class[] { GLProfile.class, GLContextImpl.class }, new Object[] { glp, this } ); /* FIXME: refactor dependence on Java 2D / JOGL bridge if (tracker != null) { gl.setObjectTracker(tracker); } */ return gl; } public final ProcAddressTable getGLProcAddressTable() { return glProcAddressTable; } /** * Shall return the platform extension ProcAddressTable, * ie for GLXExt, EGLExt, .. */ public abstract ProcAddressTable getPlatformExtProcAddressTable(); /** * Pbuffer support; given that this is a GLContext associated with a * pbuffer, binds this pbuffer to its texture target. * @throws GLException if not implemented (default) * @deprecated use FBO/GLOffscreenAutoDrawable instead of pbuffer */ public void bindPbufferToTexture() { throw new GLException("not implemented"); } /** * Pbuffer support; given that this is a GLContext associated with a * pbuffer, releases this pbuffer from its texture target. * @throws GLException if not implemented (default) * @deprecated use FBO/GLOffscreenAutoDrawable instead of pbuffer */ public void releasePbufferFromTexture() { throw new GLException("not implemented"); } public abstract ByteBuffer glAllocateMemoryNV(int arg0, float arg1, float arg2, float arg3); /** Maps the given "platform-independent" function name to a real function name. Currently this is only used to map "glAllocateMemoryNV" and associated routines to wglAllocateMemoryNV / glXAllocateMemoryNV. */ protected final String mapToRealGLFunctionName(String glFunctionName) { Map<String, String> map = getFunctionNameMap(); String lookup = ( null != map ) ? map.get(glFunctionName) : null; if (lookup != null) { return lookup; } return glFunctionName; } protected abstract Map<String, String> getFunctionNameMap() ; /** Maps the given "platform-independent" extension name to a real function name. Currently this is only used to map "GL_ARB_pbuffer" to "WGL_ARB_pbuffer/GLX_SGIX_pbuffer" and "GL_ARB_pixel_format" to "WGL_ARB_pixel_format/n.a." */ protected final String mapToRealGLExtensionName(String glExtensionName) { Map<String, String> map = getExtensionNameMap(); String lookup = ( null != map ) ? map.get(glExtensionName) : null; if (lookup != null) { return lookup; } return glExtensionName; } protected abstract Map<String, String> getExtensionNameMap() ; /** Helper routine which resets a ProcAddressTable generated by the GLEmitter by looking up anew all of its function pointers. */ protected final void resetProcAddressTable(ProcAddressTable table) { table.reset(getDrawableImpl().getGLDynamicLookupHelper() ); } private final boolean initGLRendererAndGLVersionStrings() { final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper(); final long _glGetString = glDynLookupHelper.dynamicLookupFunction("glGetString"); if(0 == _glGetString) { System.err.println("Error: Entry point to 'glGetString' is NULL."); if(DEBUG) { Thread.dumpStack(); } return false; } else { final String _glRenderer = glGetStringInt(GL.GL_RENDERER, _glGetString); if(null == _glRenderer) { if(DEBUG) { System.err.println("Warning: GL_RENDERER is NULL."); Thread.dumpStack(); } return false; } glRenderer = _glRenderer; glRendererLowerCase = glRenderer.toLowerCase(); final String _glVersion = glGetStringInt(GL.GL_VERSION, _glGetString); if(null == _glVersion) { // FIXME if(DEBUG) { System.err.println("Warning: GL_VERSION is NULL."); Thread.dumpStack(); } return false; } glVersion = _glVersion; return true; } } /** * We cannot promote a non ARB context to >= 3.1, reduce it to 3.0 then. */ private static void limitNonARBContextVersion(int[] major, int[] minor, int ctp) { if ( 0 == (ctp & CTX_IS_ARB_CREATED) && ( major[0] > 3 || major[0] == 3 && minor[0] >= 1 ) ) { major[0] = 3; minor[0] = 0; } } /** * Returns null if version string is invalid, otherwise a valid instance. * <p> * Note: Non ARB ctx is limited to GL 3.0. * </p> */ private static final VersionNumber getGLVersionNumber(int ctp, String glVersionStr) { if( null != glVersionStr ) { final GLVersionNumber version = new GLVersionNumber(glVersionStr); if ( version.isValid() ) { int[] major = new int[] { version.getMajor() }; int[] minor = new int[] { version.getMinor() }; limitNonARBContextVersion(major, minor, ctp); if ( GLContext.isValidGLVersion(major[0], minor[0]) ) { return new VersionNumber(major[0], minor[0], 0); } } } return null; } /** * Returns false if <code>glGetIntegerv</code> is inaccessible, otherwise queries major.minor * version for given arrays. * <p> * If the GL query fails, major will be zero. * </p> * <p> * Note: Non ARB ctx is limited to GL 3.0. * </p> */ private final boolean getGLIntVersion(int[] glIntMajor, int[] glIntMinor, int ctp) { glIntMajor[0] = 0; // clear final GLDynamicLookupHelper glDynLookupHelper = getDrawableImpl().getGLDynamicLookupHelper(); final long _glGetIntegerv = glDynLookupHelper.dynamicLookupFunction("glGetIntegerv"); if( 0 == _glGetIntegerv ) { System.err.println("Error: Entry point to 'glGetIntegerv' is NULL."); if(DEBUG) { Thread.dumpStack(); } return false; } else { glGetIntegervInt(GL2GL3.GL_MAJOR_VERSION, glIntMajor, 0, _glGetIntegerv); glGetIntegervInt(GL2GL3.GL_MINOR_VERSION, glIntMinor, 0, _glGetIntegerv); limitNonARBContextVersion(glIntMajor, glIntMinor, ctp); return true; } } /** * Sets the OpenGL implementation class and * the cache of which GL functions are available for calling through this * context. See {@link #isFunctionAvailable(String)} for more information on * the definition of "available". * <br> * All ProcaddressTables are being determined and cached, the GL version is being set * and the extension cache is determined as well. * * @param force force the setting, even if is already being set. * This might be useful if you change the OpenGL implementation. * @param major OpenGL major version * @param minor OpenGL minor version * @param ctxProfileBits OpenGL context profile and option bits, see {@link javax.media.opengl.GLContext#CTX_OPTION_ANY} * @param strictMatch if <code>true</code> the ctx must * <ul> * <li>be greater or equal than the requested <code>major.minor</code> version, and</li> * <li>match the ctxProfileBits</li> * </ul>, otherwise method aborts and returns <code>false</code>. * @return returns <code>true</code> if successful, otherwise <code>false</code>. See <code>strictMatch</code>. * If <code>false</code> is returned, no data has been cached or mapped, i.e. ProcAddressTable, Extensions, Version, etc. * @see #setContextVersion * @see javax.media.opengl.GLContext#CTX_OPTION_ANY * @see javax.media.opengl.GLContext#CTX_PROFILE_COMPAT * @see javax.media.opengl.GLContext#CTX_IMPL_ES2_COMPAT */ protected final boolean setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits, boolean strictMatch) { if(null!=this.gl && null!=glProcAddressTable && !force) { return true; // already done and not forced } if ( 0 < major && !GLContext.isValidGLVersion(major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } updateGLXProcAddressTable(); final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { final String errMsg = "Intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } else if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } // // Validate GL version either by GL-Integer or GL-String // if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Pre version verification - expected "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch); } boolean versionValidated = false; boolean versionGL3IntFailed = false; { // Validate the requested version w/ the GL-version from an integer query. final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } // Only validate if a valid int version was fetched, otherwise cont. w/ version-string method -> 3.0 > Version || Version > MAX! if ( GLContext.isValidGLVersion(glIntMajor[0], glIntMinor[0]) ) { if( glIntMajor[0]<major || ( glIntMajor[0]==major && glIntMinor[0]<minor ) || 0 == major ) { - if( strictMatch && 0 < major ) { + if( strictMatch && 2 < major ) { // relaxed match for versions major < 3 requests, last resort! if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (Int): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } return false; } major = glIntMajor[0]; minor = glIntMinor[0]; } versionValidated = true; } else { versionGL3IntFailed = true; } } if( !versionValidated ) { // Validate the requested version w/ the GL-version from the version string. final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } // Only validate if a valid string version was fetched -> MIN > Version || Version > MAX! if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { - if( strictMatch && 0 < major ) { + if( strictMatch && 2 < major ) { // relaxed match for versions major < 3 requests, last resort! if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (String): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } major = strGLVersionNumber.getMajor(); minor = strGLVersionNumber.getMinor(); } if( strictMatch && versionGL3IntFailed && major >= 3 ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } versionValidated = true; } } if( strictMatch && !versionValidated && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } if( 2 > major ) { // there is no ES2-compat for a profile w/ major < 2 ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } setRendererQuirks(major, minor, ctxProfileBits); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } // // UpdateGLProcAddressTable functionality // ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLProcAddress.get( contextFQN ); if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) { throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName()); } } if(null != table) { glProcAddressTable = table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode())); } } else { glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable", new Class[] { FunctionAddressResolver.class } , new Object[] { new GLProcAddressResolver() } ); resetProcAddressTable(getGLProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLProcAddress.put(contextFQN, getGLProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode())); } } } // // Update ExtensionAvailabilityCache // ExtensionAvailabilityCache eCache; synchronized(mappedContextTypeObjectLock) { eCache = mappedExtensionAvailabilityCache.get( contextFQN ); } if(null != eCache) { extensionAvailability = eCache; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount()); } } else { extensionAvailability = new ExtensionAvailabilityCache(); setContextVersion(major, minor, ctxProfileBits, false); // pre-set of GL version, required for extension cache usage extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount()); } } } if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; } // // Set GL Version (complete w/ version string) // setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); final int glErrX = gl.glGetError(); // clear GL error, maybe caused by above operations if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; } private final void setRendererQuirks(int major, int minor, int ctp) { int[] quirks = new int[GLRendererQuirks.COUNT]; int i = 0; final boolean hwAccel = 0 == ( ctp & GLContext.CTX_IMPL_ACCEL_SOFT ); final boolean compatCtx = 0 != ( ctp & GLContext.CTX_PROFILE_COMPAT ); // OS related quirks if( Platform.getOSType() == Platform.OSType.MACOS ) { final int quirk1 = GLRendererQuirks.NoOffscreenBitmap; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk1)+": cause: OS "+Platform.getOSType()); } quirks[i++] = quirk1; } else if( Platform.getOSType() == Platform.OSType.WINDOWS ) { final int quirk = GLRendererQuirks.NoDoubleBufferedBitmap; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType()); } quirks[i++] = quirk; } // Renderer related quirks, may also involve OS if( Platform.OSType.ANDROID == Platform.getOSType() && glRendererLowerCase.contains("powervr") ) { final int quirk = GLRendererQuirks.NoSetSwapInterval; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: OS "+Platform.getOSType() + " / Renderer " + glRenderer); } quirks[i++] = quirk; } if( glRendererLowerCase.contains("mesa") || glRendererLowerCase.contains("gallium") ) { { final int quirk = GLRendererQuirks.NoSetSwapIntervalPostRetarget; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer " + glRenderer); } quirks[i++] = quirk; } if( hwAccel /* glRendererLowerCase.contains("intel(r)") || glRendererLowerCase.contains("amd") */ ) { final int quirk = GLRendererQuirks.NoDoubleBufferedPBuffer; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer " + glRenderer); } quirks[i++] = quirk; } if( glRendererLowerCase.contains("intel(r)") && compatCtx && ( major>3 || major==3 && minor>=1 ) ) { final int quirk = GLRendererQuirks.GLNonCompliant; if(DEBUG) { System.err.println("Quirk: "+GLRendererQuirks.toString(quirk)+": cause: Renderer " + glRenderer); } quirks[i++] = quirk; } } glRendererQuirks = new GLRendererQuirks(quirks, 0, i); } private static final boolean hasFBOImpl(int major, int ctp, ExtensionAvailabilityCache extCache) { return ( 0 != (ctp & CTX_PROFILE_ES) && major >= 2 ) || // ES >= 2.0 major >= 3 || // any >= 3.0 GL ctx ( null != extCache && extCache.isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) || // ES 2.0 compatible extCache.isExtensionAvailable(GLExtensions.ARB_framebuffer_object) || // ARB_framebuffer_object extCache.isExtensionAvailable(GLExtensions.EXT_framebuffer_object) || // EXT_framebuffer_object extCache.isExtensionAvailable(GLExtensions.OES_framebuffer_object) ) ; // OES_framebuffer_object excluded } private final void removeCachedVersion(int major, int minor, int ctxProfileBits) { if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": RM Context FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } synchronized(mappedContextTypeObjectLock) { final ProcAddressTable table = mappedGLProcAddress.remove( contextFQN ); if(DEBUG) { final int hc = null != table ? table.hashCode() : 0; System.err.println(getThreadName() + ": RM GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(hc)); } } synchronized(mappedContextTypeObjectLock) { final ExtensionAvailabilityCache eCache = mappedExtensionAvailabilityCache.remove( contextFQN ); if(DEBUG) { final int hc = null != eCache ? eCache.hashCode() : 0; System.err.println(getThreadName() + ": RM GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(hc)); } } } private final boolean isCurrentContextHardwareRasterizer() { boolean isHardwareRasterizer = true; if(!drawable.getChosenGLCapabilities().getHardwareAccelerated()) { isHardwareRasterizer = false; } else { isHardwareRasterizer = ! ( glRendererLowerCase.contains("software") /* Mesa3D */ || glRendererLowerCase.contains("mesa x11") /* Mesa3D*/ || glRendererLowerCase.contains("softpipe") /* Gallium */ || glRendererLowerCase.contains("llvmpipe") /* Gallium */ ); } return isHardwareRasterizer; } /** * Updates the platform's 'GLX' function cache */ protected abstract void updateGLXProcAddressTable(); protected abstract StringBuilder getPlatformExtensionsStringImpl(); @Override public final boolean isFunctionAvailable(String glFunctionName) { // Check GL 1st (cached) if(null!=glProcAddressTable) { // null if this context wasn't not created try { if(0!=glProcAddressTable.getAddressFor(glFunctionName)) { return true; } } catch (Exception e) {} } // Check platform extensions 2nd (cached) - context had to be enabled once final ProcAddressTable pTable = getPlatformExtProcAddressTable(); if(null!=pTable) { try { if(0!=pTable.getAddressFor(glFunctionName)) { return true; } } catch (Exception e) {} } // dynamic function lookup at last incl name aliasing (not cached) DynamicLookupHelper dynLookup = getDrawableImpl().getGLDynamicLookupHelper(); String tmpBase = GLNameResolver.normalizeVEN(GLNameResolver.normalizeARB(glFunctionName, true), true); long addr = 0; int variants = GLNameResolver.getFuncNamePermutationNumber(tmpBase); for(int i = 0; 0==addr && i < variants; i++) { String tmp = GLNameResolver.getFuncNamePermutation(tmpBase, i); try { addr = dynLookup.dynamicLookupFunction(tmp); } catch (Exception e) { } } if(0!=addr) { return true; } return false; } @Override public boolean isExtensionAvailable(String glExtensionName) { if(null!=extensionAvailability) { return extensionAvailability.isExtensionAvailable(mapToRealGLExtensionName(glExtensionName)); } return false; } @Override public final int getPlatformExtensionCount() { return null != extensionAvailability ? extensionAvailability.getPlatformExtensionCount() : 0; } @Override public final String getPlatformExtensionsString() { if(null!=extensionAvailability) { return extensionAvailability.getPlatformExtensionsString(); } return null; } @Override public final int getGLExtensionCount() { return null != extensionAvailability ? extensionAvailability.getGLExtensionCount() : 0; } @Override public final String getGLExtensionsString() { if(null!=extensionAvailability) { return extensionAvailability.getGLExtensionsString(); } return null; } public final boolean isExtensionCacheInitialized() { if(null!=extensionAvailability) { return extensionAvailability.isInitialized(); } return false; } protected static String getContextFQN(AbstractGraphicsDevice device, int major, int minor, int ctxProfileBits) { // remove non-key values ctxProfileBits &= ~( GLContext.CTX_IMPL_ES2_COMPAT | GLContext.CTX_IMPL_FBO ) ; return device.getUniqueID() + "-" + toHexString(composeBits(major, minor, ctxProfileBits)); } protected final String getContextFQN() { return contextFQN; } /** Indicates which floating-point pbuffer implementation is in use. Returns one of GLPbuffer.APPLE_FLOAT, GLPbuffer.ATI_FLOAT, or GLPbuffer.NV_FLOAT. */ public int getFloatingPointMode() throws GLException { throw new GLException("Not supported on non-pbuffer contexts"); } @Override public boolean isGLOrientationFlippedVertical() { return true; } @Override public int getDefaultPixelDataType() { if(!pixelDataTypeEvaluated) { synchronized(this) { if(!pixelDataTypeEvaluated) { evalPixelDataType(); pixelDataTypeEvaluated = true; } } } return pixelDataType; } private volatile boolean pixelDataTypeEvaluated = false; int /* pixelDataInternalFormat, */ pixelDataFormat, pixelDataType; private final void evalPixelDataType() { /* if(isGL2GL3() && 3 == components) { pixelDataInternalFormat=GL.GL_RGB; pixelDataFormat=GL.GL_RGB; pixelDataType = GL.GL_UNSIGNED_BYTE; } else */ if(isGLES2Compatible() || isExtensionAvailable(GLExtensions.OES_read_format)) { final int[] glImplColorReadVals = new int[] { 0, 0 }; gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_FORMAT, glImplColorReadVals, 0); gl.glGetIntegerv(GL.GL_IMPLEMENTATION_COLOR_READ_TYPE, glImplColorReadVals, 1); // pixelDataInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB; pixelDataFormat = glImplColorReadVals[0]; pixelDataType = glImplColorReadVals[1]; } else { // RGBA read is safe for all GL profiles // pixelDataInternalFormat = (4 == components) ? GL.GL_RGBA : GL.GL_RGB; pixelDataFormat=GL.GL_RGBA; pixelDataType = GL.GL_UNSIGNED_BYTE; } } //---------------------------------------------------------------------- // Helpers for buffer object optimizations public final void setBufferSizeTracker(GLBufferSizeTracker bufferSizeTracker) { this.bufferSizeTracker = bufferSizeTracker; } public final GLBufferSizeTracker getBufferSizeTracker() { return bufferSizeTracker; } public final GLBufferStateTracker getBufferStateTracker() { return bufferStateTracker; } public final GLStateTracker getGLStateTracker() { return glStateTracker; } //--------------------------------------------------------------------------- // Helpers for context optimization where the last context is left // current on the OpenGL worker thread // /** * Returns true if the given thread is owner, otherwise false. * <p> * Method exists merely for code validation of {@link #isCurrent()}. * </p> */ public final boolean isOwner(Thread thread) { return lock.isOwner(thread); } /** * Returns true if there are other threads waiting for this GLContext to {@link #makeCurrent()}, otherwise false. * <p> * Since method does not perform any synchronization, accurate result are returned if lock is hold - only. * </p> */ public final boolean hasWaiters() { return lock.getQueueLength()>0; } /** * Returns the number of hold locks. See {@link RecursiveLock#getHoldCount()} for semantics. * <p> * Since method does not perform any synchronization, accurate result are returned if lock is hold - only. * </p> */ public final int getLockCount() { return lock.getHoldCount(); } //--------------------------------------------------------------------------- // Special FBO hook // /** * Tracks {@link GL#GL_FRAMEBUFFER}, {@link GL2GL3#GL_DRAW_FRAMEBUFFER} and {@link GL2GL3#GL_READ_FRAMEBUFFER} * to be returned via {@link #getBoundFramebuffer(int)}. * * <p>Invoked by {@link GL#glBindFramebuffer(int, int)}. </p> * * <p>Assumes valid <code>framebufferName</code> range of [0..{@link Integer#MAX_VALUE}]</p> * * <p>Does not throw an exception if <code>target</code> is unknown or <code>framebufferName</code> invalid.</p> */ public final void setBoundFramebuffer(int target, int framebufferName) { if(0 > framebufferName) { return; // ignore invalid name } switch(target) { case GL.GL_FRAMEBUFFER: boundFBOTarget[0] = framebufferName; // draw boundFBOTarget[1] = framebufferName; // read break; case GL2GL3.GL_DRAW_FRAMEBUFFER: boundFBOTarget[0] = framebufferName; // draw break; case GL2GL3.GL_READ_FRAMEBUFFER: boundFBOTarget[1] = framebufferName; // read break; default: // ignore untracked target } } @Override public final int getBoundFramebuffer(int target) { switch(target) { case GL.GL_FRAMEBUFFER: case GL2GL3.GL_DRAW_FRAMEBUFFER: return boundFBOTarget[0]; // draw case GL2GL3.GL_READ_FRAMEBUFFER: return boundFBOTarget[1]; // read default: throw new InternalError("Invalid FBO target name: "+toHexString(target)); } } @Override public final int getDefaultDrawFramebuffer() { return drawable.getDefaultDrawFramebuffer(); } @Override public final int getDefaultReadFramebuffer() { return drawable.getDefaultReadFramebuffer(); } @Override public final int getDefaultReadBuffer() { return drawable.getDefaultReadBuffer(gl); } //--------------------------------------------------------------------------- // GL_ARB_debug_output, GL_AMD_debug_output helpers // @Override public final String getGLDebugMessageExtension() { return glDebugHandler.getExtension(); } @Override public final boolean isGLDebugMessageEnabled() { return glDebugHandler.isEnabled(); } @Override public final int getContextCreationFlags() { return additionalCtxCreationFlags; } @Override public final void setContextCreationFlags(int flags) { if(!isCreated()) { additionalCtxCreationFlags = flags & GLContext.CTX_OPTION_DEBUG; } } @Override public final boolean isGLDebugSynchronous() { return glDebugHandler.isSynchronous(); } @Override public final void setGLDebugSynchronous(boolean synchronous) { glDebugHandler.setSynchronous(synchronous); } @Override public final void enableGLDebugMessage(boolean enable) throws GLException { if(!isCreated()) { if(enable) { additionalCtxCreationFlags |= GLContext.CTX_OPTION_DEBUG; } else { additionalCtxCreationFlags &= ~GLContext.CTX_OPTION_DEBUG; } } else if(0 != (additionalCtxCreationFlags & GLContext.CTX_OPTION_DEBUG) && null != getGLDebugMessageExtension()) { glDebugHandler.enable(enable); } } @Override public final void addGLDebugListener(GLDebugListener listener) { glDebugHandler.addListener(listener); } @Override public final void removeGLDebugListener(GLDebugListener listener) { glDebugHandler.removeListener(listener); } @Override public final void glDebugMessageControl(int source, int type, int severity, int count, IntBuffer ids, boolean enabled) { if(glDebugHandler.isExtensionARB()) { gl.getGL2GL3().glDebugMessageControlARB(source, type, severity, count, ids, enabled); } else if(glDebugHandler.isExtensionAMD()) { gl.getGL2GL3().glDebugMessageEnableAMD(GLDebugMessage.translateARB2AMDCategory(source, type), severity, count, ids, enabled); } } @Override public final void glDebugMessageControl(int source, int type, int severity, int count, int[] ids, int ids_offset, boolean enabled) { if(glDebugHandler.isExtensionARB()) { gl.getGL2GL3().glDebugMessageControlARB(source, type, severity, count, ids, ids_offset, enabled); } else if(glDebugHandler.isExtensionAMD()) { gl.getGL2GL3().glDebugMessageEnableAMD(GLDebugMessage.translateARB2AMDCategory(source, type), severity, count, ids, ids_offset, enabled); } } @Override public final void glDebugMessageInsert(int source, int type, int id, int severity, String buf) { final int len = (null != buf) ? buf.length() : 0; if(glDebugHandler.isExtensionARB()) { gl.getGL2GL3().glDebugMessageInsertARB(source, type, id, severity, len, buf); } else if(glDebugHandler.isExtensionAMD()) { gl.getGL2GL3().glDebugMessageInsertAMD(GLDebugMessage.translateARB2AMDCategory(source, type), severity, id, len, buf); } } /** Internal bootstraping glGetString(GL_RENDERER) */ protected static native String glGetStringInt(int name, long procAddress); /** Internal bootstraping glGetIntegerv(..) for version */ protected static native void glGetIntegervInt(int pname, int[] params, int params_offset, long procAddress); }
false
true
protected final boolean setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits, boolean strictMatch) { if(null!=this.gl && null!=glProcAddressTable && !force) { return true; // already done and not forced } if ( 0 < major && !GLContext.isValidGLVersion(major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } updateGLXProcAddressTable(); final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { final String errMsg = "Intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } else if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } // // Validate GL version either by GL-Integer or GL-String // if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Pre version verification - expected "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch); } boolean versionValidated = false; boolean versionGL3IntFailed = false; { // Validate the requested version w/ the GL-version from an integer query. final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } // Only validate if a valid int version was fetched, otherwise cont. w/ version-string method -> 3.0 > Version || Version > MAX! if ( GLContext.isValidGLVersion(glIntMajor[0], glIntMinor[0]) ) { if( glIntMajor[0]<major || ( glIntMajor[0]==major && glIntMinor[0]<minor ) || 0 == major ) { if( strictMatch && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (Int): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } return false; } major = glIntMajor[0]; minor = glIntMinor[0]; } versionValidated = true; } else { versionGL3IntFailed = true; } } if( !versionValidated ) { // Validate the requested version w/ the GL-version from the version string. final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } // Only validate if a valid string version was fetched -> MIN > Version || Version > MAX! if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { if( strictMatch && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (String): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } major = strGLVersionNumber.getMajor(); minor = strGLVersionNumber.getMinor(); } if( strictMatch && versionGL3IntFailed && major >= 3 ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } versionValidated = true; } } if( strictMatch && !versionValidated && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } if( 2 > major ) { // there is no ES2-compat for a profile w/ major < 2 ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } setRendererQuirks(major, minor, ctxProfileBits); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } // // UpdateGLProcAddressTable functionality // ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLProcAddress.get( contextFQN ); if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) { throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName()); } } if(null != table) { glProcAddressTable = table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode())); } } else { glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable", new Class[] { FunctionAddressResolver.class } , new Object[] { new GLProcAddressResolver() } ); resetProcAddressTable(getGLProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLProcAddress.put(contextFQN, getGLProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode())); } } } // // Update ExtensionAvailabilityCache // ExtensionAvailabilityCache eCache; synchronized(mappedContextTypeObjectLock) { eCache = mappedExtensionAvailabilityCache.get( contextFQN ); } if(null != eCache) { extensionAvailability = eCache; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount()); } } else { extensionAvailability = new ExtensionAvailabilityCache(); setContextVersion(major, minor, ctxProfileBits, false); // pre-set of GL version, required for extension cache usage extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount()); } } } if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; } // // Set GL Version (complete w/ version string) // setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); final int glErrX = gl.glGetError(); // clear GL error, maybe caused by above operations if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; }
protected final boolean setGLFunctionAvailability(boolean force, int major, int minor, int ctxProfileBits, boolean strictMatch) { if(null!=this.gl && null!=glProcAddressTable && !force) { return true; // already done and not forced } if ( 0 < major && !GLContext.isValidGLVersion(major, minor) ) { throw new GLException("Invalid GL Version Request "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)); } if(null==this.gl || !verifyInstance(gl.getGLProfile(), "Impl", this.gl)) { setGL( createGL( getGLDrawable().getGLProfile() ) ); } updateGLXProcAddressTable(); final AbstractGraphicsConfiguration aconfig = drawable.getNativeSurface().getGraphicsConfiguration(); final AbstractGraphicsDevice adevice = aconfig.getScreen().getDevice(); { final boolean initGLRendererAndGLVersionStringsOK = initGLRendererAndGLVersionStrings(); if( !initGLRendererAndGLVersionStringsOK ) { final String errMsg = "Intialization of GL renderer strings failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } else if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Given "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } } // // Validate GL version either by GL-Integer or GL-String // if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: Pre version verification - expected "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch); } boolean versionValidated = false; boolean versionGL3IntFailed = false; { // Validate the requested version w/ the GL-version from an integer query. final int[] glIntMajor = new int[] { 0 }, glIntMinor = new int[] { 0 }; final boolean getGLIntVersionOK = getGLIntVersion(glIntMajor, glIntMinor, ctxProfileBits); if( !getGLIntVersionOK ) { final String errMsg = "Fetching GL Integer Version failed. "+adevice+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, null); if( strictMatch ) { // query mode .. simply fail if(DEBUG) { System.err.println("Warning: setGLFunctionAvailability: "+errMsg); } return false; } else { // unusable GL context - non query mode - hard fail! throw new GLException(errMsg); } } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (Int): "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } // Only validate if a valid int version was fetched, otherwise cont. w/ version-string method -> 3.0 > Version || Version > MAX! if ( GLContext.isValidGLVersion(glIntMajor[0], glIntMinor[0]) ) { if( glIntMajor[0]<major || ( glIntMajor[0]==major && glIntMinor[0]<minor ) || 0 == major ) { if( strictMatch && 2 < major ) { // relaxed match for versions major < 3 requests, last resort! if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (Int): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+glIntMajor[0]+"."+glIntMinor[0]); } return false; } major = glIntMajor[0]; minor = glIntMinor[0]; } versionValidated = true; } else { versionGL3IntFailed = true; } } if( !versionValidated ) { // Validate the requested version w/ the GL-version from the version string. final VersionNumber setGLVersionNumber = new VersionNumber(major, minor, 0); final VersionNumber strGLVersionNumber = getGLVersionNumber(ctxProfileBits, glVersion); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: version verification (String): "+glVersion+", "+strGLVersionNumber); } // Only validate if a valid string version was fetched -> MIN > Version || Version > MAX! if( null != strGLVersionNumber ) { if( strGLVersionNumber.compareTo(setGLVersionNumber) < 0 || 0 == major ) { if( strictMatch && 2 < major ) { // relaxed match for versions major < 3 requests, last resort! if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL version mismatch (String): "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } major = strGLVersionNumber.getMajor(); minor = strGLVersionNumber.getMinor(); } if( strictMatch && versionGL3IntFailed && major >= 3 ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL3 version Int failed, String: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion+", "+strGLVersionNumber); } return false; } versionValidated = true; } } if( strictMatch && !versionValidated && 0 < major ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, No GL version validation possible: "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+" -> "+glVersion); } return false; } if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail: post version verification "+GLContext.getGLVersion(major, minor, ctxProfileBits, null)+", strictMatch "+strictMatch+", versionValidated "+versionValidated+", versionGL3IntFailed "+versionGL3IntFailed); } if( 2 > major ) { // there is no ES2-compat for a profile w/ major < 2 ctxProfileBits &= ~GLContext.CTX_IMPL_ES2_COMPAT; } setRendererQuirks(major, minor, ctxProfileBits); if( strictMatch && glRendererQuirks.exist(GLRendererQuirks.GLNonCompliant) ) { if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: FAIL, GL is not compliant: "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)+", "+glRenderer); } return false; } if(!isCurrentContextHardwareRasterizer()) { ctxProfileBits |= GLContext.CTX_IMPL_ACCEL_SOFT; } contextFQN = getContextFQN(adevice, major, minor, ctxProfileBits); if (DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.0 validated FQN: "+contextFQN+" - "+GLContext.getGLVersion(major, minor, ctxProfileBits, glVersion)); } // // UpdateGLProcAddressTable functionality // ProcAddressTable table = null; synchronized(mappedContextTypeObjectLock) { table = mappedGLProcAddress.get( contextFQN ); if(null != table && !verifyInstance(gl.getGLProfile(), "ProcAddressTable", table)) { throw new InternalError("GLContext GL ProcAddressTable mapped key("+contextFQN+" - " + GLContext.getGLVersion(major, minor, ctxProfileBits, null)+ ") -> "+ table.getClass().getName()+" not matching "+gl.getGLProfile().getGLImplBaseClassName()); } } if(null != table) { glProcAddressTable = table; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable reusing key("+contextFQN+") -> "+toHexString(table.hashCode())); } } else { glProcAddressTable = (ProcAddressTable) createInstance(gl.getGLProfile(), "ProcAddressTable", new Class[] { FunctionAddressResolver.class } , new Object[] { new GLProcAddressResolver() } ); resetProcAddressTable(getGLProcAddressTable()); synchronized(mappedContextTypeObjectLock) { mappedGLProcAddress.put(contextFQN, getGLProcAddressTable()); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ProcAddressTable mapping key("+contextFQN+") -> "+toHexString(getGLProcAddressTable().hashCode())); } } } // // Update ExtensionAvailabilityCache // ExtensionAvailabilityCache eCache; synchronized(mappedContextTypeObjectLock) { eCache = mappedExtensionAvailabilityCache.get( contextFQN ); } if(null != eCache) { extensionAvailability = eCache; if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache reusing key("+contextFQN+") -> "+toHexString(eCache.hashCode()) + " - entries: "+eCache.getTotalExtensionCount()); } } else { extensionAvailability = new ExtensionAvailabilityCache(); setContextVersion(major, minor, ctxProfileBits, false); // pre-set of GL version, required for extension cache usage extensionAvailability.reset(this); synchronized(mappedContextTypeObjectLock) { mappedExtensionAvailabilityCache.put(contextFQN, extensionAvailability); if(DEBUG) { System.err.println(getThreadName() + ": GLContext GL ExtensionAvailabilityCache mapping key("+contextFQN+") -> "+toHexString(extensionAvailability.hashCode()) + " - entries: "+extensionAvailability.getTotalExtensionCount()); } } } if( ( 0 != ( CTX_PROFILE_ES & ctxProfileBits ) && major >= 2 ) || isExtensionAvailable(GLExtensions.ARB_ES2_compatibility) ) { ctxProfileBits |= CTX_IMPL_ES2_COMPAT; ctxProfileBits |= CTX_IMPL_FBO; } else if( hasFBOImpl(major, ctxProfileBits, extensionAvailability) ) { ctxProfileBits |= CTX_IMPL_FBO; } if(FORCE_NO_FBO_SUPPORT) { ctxProfileBits &= ~CTX_IMPL_FBO ; } // // Set GL Version (complete w/ version string) // setContextVersion(major, minor, ctxProfileBits, true); setDefaultSwapInterval(); final int glErrX = gl.glGetError(); // clear GL error, maybe caused by above operations if(DEBUG) { System.err.println(getThreadName() + ": GLContext.setGLFuncAvail.X: OK "+contextFQN+" - "+GLContext.getGLVersion(ctxVersion.getMajor(), ctxVersion.getMinor(), ctxOptions, null)+" - glErr "+toHexString(glErrX)); } return true; }
diff --git a/notification-consumer-services/src/main/java/uk/ac/bbsrc/tgac/miso/notification/consumer/service/mechanism/PacBioNotificationMessageConsumerMechanism.java b/notification-consumer-services/src/main/java/uk/ac/bbsrc/tgac/miso/notification/consumer/service/mechanism/PacBioNotificationMessageConsumerMechanism.java index a66005d69..e8a14e790 100644 --- a/notification-consumer-services/src/main/java/uk/ac/bbsrc/tgac/miso/notification/consumer/service/mechanism/PacBioNotificationMessageConsumerMechanism.java +++ b/notification-consumer-services/src/main/java/uk/ac/bbsrc/tgac/miso/notification/consumer/service/mechanism/PacBioNotificationMessageConsumerMechanism.java @@ -1,365 +1,364 @@ /* * Copyright (c) 2012. The Genome Analysis Centre, Norwich, UK * MISO project contacts: Robert Davey, Mario Caccamo @ TGAC * ********************************************************************* * * This file is part of MISO. * * MISO is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * MISO is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with MISO. If not, see <http://www.gnu.org/licenses/>. * * ********************************************************************* */ package uk.ac.bbsrc.tgac.miso.notification.consumer.service.mechanism; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.integration.Message; import org.springframework.util.Assert; import uk.ac.bbsrc.tgac.miso.core.data.*; import uk.ac.bbsrc.tgac.miso.core.data.impl.RunImpl; import uk.ac.bbsrc.tgac.miso.core.data.impl.SequencerPartitionContainerImpl; import uk.ac.bbsrc.tgac.miso.core.data.impl.pacbio.PacBioRun; import uk.ac.bbsrc.tgac.miso.core.data.impl.pacbio.PacBioStatus; import uk.ac.bbsrc.tgac.miso.core.data.type.HealthType; import uk.ac.bbsrc.tgac.miso.core.data.type.PlatformType; import uk.ac.bbsrc.tgac.miso.core.exception.InterrogationException; import uk.ac.bbsrc.tgac.miso.core.manager.RequestManager; import uk.ac.bbsrc.tgac.miso.core.service.integration.mechanism.NotificationMessageConsumerMechanism; import uk.ac.bbsrc.tgac.miso.integration.util.IntegrationUtils; import uk.ac.bbsrc.tgac.miso.tools.run.RunFolderConstants; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * uk.ac.bbsrc.tgac.miso.core.service.integration.mechanism.impl * <p/> * Info * * @author Rob Davey * @date 03/02/12 * @since 0.1.5 */ public class PacBioNotificationMessageConsumerMechanism implements NotificationMessageConsumerMechanism<Message<Map<String, List<String>>>, Set<Run>> { protected static final Logger log = LoggerFactory.getLogger(PacBioNotificationMessageConsumerMechanism.class); public boolean attemptRunPopulation = true; public void setAttemptRunPopulation(boolean attemptRunPopulation) { this.attemptRunPopulation = attemptRunPopulation; } private final String runDirRegex = RunFolderConstants.PACBIO_FOLDER_NAME_GROUP_CAPTURE_REGEX; private final Pattern p = Pattern.compile(runDirRegex); @Override public Set<Run> consume(Message<Map<String, List<String>>> message) throws InterrogationException { RequestManager requestManager = message.getHeaders().get("handler", RequestManager.class); Assert.notNull(requestManager, "Cannot consume MISO notification messages without a RequestManager."); Map<String, List<String>> statuses = message.getPayload(); Set<Run> output = new HashSet<Run>(); for (String key : statuses.keySet()) { HealthType ht = HealthType.valueOf(key); JSONArray runs = (JSONArray) JSONArray.fromObject(statuses.get(key)).get(0); Map<String, Run> map = processRunJSON(ht, runs, requestManager); for (Run r : map.values()) { output.add(r); } } return output; } private Map<String, Run> processRunJSON(HealthType ht, JSONArray runs, RequestManager requestManager) { Map<String, Run> updatedRuns = new HashMap<String, Run>(); List<Run> runsToSave = new ArrayList<Run>(); DateFormat gsLogDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); DateFormat startDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); for (JSONObject run : (Iterable<JSONObject>)runs) { String runName = run.getString("runName"); log.info("Processing " + runName); String status = ""; if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); for (JSONObject cell : (Iterable<JSONObject>)cells) { if (cell.has("cellStatus")) { try { String s = new String(IntegrationUtils.decompress(URLDecoder.decode(cell.getString("cellStatus"), "UTF-8").getBytes())); status += s + "\n\n"; } catch (UnsupportedEncodingException e) { log.error("Cannot decode status xml: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.error("Cannot decompress and decode incoming status: " + e.getMessage()); e.printStackTrace(); } } } } if (!"".equals(status)) { try { //String runLog = run.getString("status"); if (!status.startsWith("ERROR")) { Status is = new PacBioStatus(status); is.setHealth(ht); is.setRunName(runName); Run r = null; Matcher m = p.matcher(runName); if (m.matches()) { try { r = requestManager.getRunByAlias(runName); } catch(IOException ioe) { log.warn("Cannot find run by this alias. This usually means the run hasn't been previously imported. If attemptRunPopulation is false, processing will not take place for this run!"); } } if (attemptRunPopulation) { if (r == null) { log.info("\\_ Saving new run and status: " + is.getRunName()); r = new PacBioRun(status); r.setAlias(run.getString("runName")); r.setDescription(m.group(2)); r.setPairedEnd(false); if (run.has("fullPath")) { r.setFilePath(run.getString("fullPath")); } SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } is.setInstrumentName(sr.getName()); r.setStatus(is); r.setSequencerReference(sr); - runsToSave.add(r); } else { log.error("\\_ Cannot save " + is.getRunName() + ": no sequencer reference available."); } } else { log.info("\\_ Updating existing run and status: " + is.getRunName()); r.setPlatformType(PlatformType.PACBIO); r.setDescription(m.group(2)); r.setPairedEnd(false); if (r.getSequencerReference() == null) { SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { r.getStatus().setInstrumentName(sr.getName()); r.setSequencerReference(sr); } } if (r.getSequencerReference() != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } //update path if changed if (run.has("fullPath") && !"".equals(run.getString("fullPath")) && r.getFilePath() != null && !"".equals(r.getFilePath())) { if (!run.getString("fullPath").equals(r.getFilePath())) { log.info("Updating run file path:" + r.getFilePath() + " -> " + run.getString("fullPath")); r.setFilePath(run.getString("fullPath")); } } // update status if run isn't completed or failed if (!r.getStatus().getHealth().equals(HealthType.Completed) && !r.getStatus().getHealth().equals(HealthType.Failed)) { log.info("Saving previously saved status: " + is.getRunName() + " (" + r.getStatus().getHealth().getKey() + " -> " + is.getHealth().getKey() + ")"); //if (!r.getStatus().getHealth().equals(is.getHealth())) { r.setStatus(is); //} //requestManager.saveStatus(is); } } } if (r.getSequencerReference() != null) { List<SequencerPartitionContainer<SequencerPoolPartition>> fs = ((PacBioRun)r).getSequencerPartitionContainers(); if (fs.isEmpty()) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { Collection<SequencerPartitionContainer<SequencerPoolPartition>> pfs = requestManager.listSequencerPartitionContainersByBarcode(run.getString("plateId")); if (!pfs.isEmpty()) { if (pfs.size() == 1) { SequencerPartitionContainer<SequencerPoolPartition> lf = new ArrayList<SequencerPartitionContainer<SequencerPoolPartition>>(pfs).get(0); if (lf.getSecurityProfile() != null && r.getSecurityProfile() == null) { r.setSecurityProfile(lf.getSecurityProfile()); } if (lf.getPlatformType() == null && r.getPlatformType() != null) { lf.setPlatformType(r.getPlatformType()); } else { lf.setPlatformType(PlatformType.PACBIO); } ((RunImpl)r).addSequencerPartitionContainer(lf); } else { //more than one flowcell hit to this barcode log.warn(r.getAlias() + ":: More than one container has this barcode. Cannot automatically link to a pre-existing barcode."); } } else { if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); SequencerPartitionContainer f = new SequencerPartitionContainerImpl(); f.setPartitionLimit(cells.size()); f.initEmptyPartitions(); if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); } if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } f.setRun(r); log.info("\\_ Created new container with "+f.getPartitions().size()+" partitions"); long flowId = requestManager.saveSequencerPartitionContainer(f); f.setId(flowId); ((RunImpl)r).addSequencerPartitionContainer(f); //TODO match up samples to libraries and pools? /* for (JSONObject obj : (Iterable<JSONObject>)cells) { int cellindex = obj.getInt("index"); String sample = obj.getString("sample"); SequencerPoolPartition p = f.getPartitionAt(cellindex); if (p.getPool() == null) { Pool pool = new PoolImpl(); } } */ } } } } else { SequencerPartitionContainer f = fs.iterator().next(); f.setSecurityProfile(r.getSecurityProfile()); if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } if (f.getIdentificationBarcode() == null || "".equals(f.getIdentificationBarcode())) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); requestManager.saveSequencerPartitionContainer(f); } } } updatedRuns.put(r.getAlias(), r); runsToSave.add(r); } } else { log.warn("\\_ Run not saved. Saving status: " + is.getRunName()); requestManager.saveStatus(is); } } } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } } else { log.error("No notification status available for " + runName); } } try { if (runsToSave.size() > 0) { int[] saved = requestManager.saveRuns(runsToSave); log.info("Batch saved " + saved.length + " / "+ runs.size() + " runs"); } } catch (IOException e) { log.error("Couldn't save run batch: " + e.getMessage()); e.printStackTrace(); } return updatedRuns; } }
true
true
private Map<String, Run> processRunJSON(HealthType ht, JSONArray runs, RequestManager requestManager) { Map<String, Run> updatedRuns = new HashMap<String, Run>(); List<Run> runsToSave = new ArrayList<Run>(); DateFormat gsLogDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); DateFormat startDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); for (JSONObject run : (Iterable<JSONObject>)runs) { String runName = run.getString("runName"); log.info("Processing " + runName); String status = ""; if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); for (JSONObject cell : (Iterable<JSONObject>)cells) { if (cell.has("cellStatus")) { try { String s = new String(IntegrationUtils.decompress(URLDecoder.decode(cell.getString("cellStatus"), "UTF-8").getBytes())); status += s + "\n\n"; } catch (UnsupportedEncodingException e) { log.error("Cannot decode status xml: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.error("Cannot decompress and decode incoming status: " + e.getMessage()); e.printStackTrace(); } } } } if (!"".equals(status)) { try { //String runLog = run.getString("status"); if (!status.startsWith("ERROR")) { Status is = new PacBioStatus(status); is.setHealth(ht); is.setRunName(runName); Run r = null; Matcher m = p.matcher(runName); if (m.matches()) { try { r = requestManager.getRunByAlias(runName); } catch(IOException ioe) { log.warn("Cannot find run by this alias. This usually means the run hasn't been previously imported. If attemptRunPopulation is false, processing will not take place for this run!"); } } if (attemptRunPopulation) { if (r == null) { log.info("\\_ Saving new run and status: " + is.getRunName()); r = new PacBioRun(status); r.setAlias(run.getString("runName")); r.setDescription(m.group(2)); r.setPairedEnd(false); if (run.has("fullPath")) { r.setFilePath(run.getString("fullPath")); } SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } is.setInstrumentName(sr.getName()); r.setStatus(is); r.setSequencerReference(sr); runsToSave.add(r); } else { log.error("\\_ Cannot save " + is.getRunName() + ": no sequencer reference available."); } } else { log.info("\\_ Updating existing run and status: " + is.getRunName()); r.setPlatformType(PlatformType.PACBIO); r.setDescription(m.group(2)); r.setPairedEnd(false); if (r.getSequencerReference() == null) { SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { r.getStatus().setInstrumentName(sr.getName()); r.setSequencerReference(sr); } } if (r.getSequencerReference() != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } //update path if changed if (run.has("fullPath") && !"".equals(run.getString("fullPath")) && r.getFilePath() != null && !"".equals(r.getFilePath())) { if (!run.getString("fullPath").equals(r.getFilePath())) { log.info("Updating run file path:" + r.getFilePath() + " -> " + run.getString("fullPath")); r.setFilePath(run.getString("fullPath")); } } // update status if run isn't completed or failed if (!r.getStatus().getHealth().equals(HealthType.Completed) && !r.getStatus().getHealth().equals(HealthType.Failed)) { log.info("Saving previously saved status: " + is.getRunName() + " (" + r.getStatus().getHealth().getKey() + " -> " + is.getHealth().getKey() + ")"); //if (!r.getStatus().getHealth().equals(is.getHealth())) { r.setStatus(is); //} //requestManager.saveStatus(is); } } } if (r.getSequencerReference() != null) { List<SequencerPartitionContainer<SequencerPoolPartition>> fs = ((PacBioRun)r).getSequencerPartitionContainers(); if (fs.isEmpty()) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { Collection<SequencerPartitionContainer<SequencerPoolPartition>> pfs = requestManager.listSequencerPartitionContainersByBarcode(run.getString("plateId")); if (!pfs.isEmpty()) { if (pfs.size() == 1) { SequencerPartitionContainer<SequencerPoolPartition> lf = new ArrayList<SequencerPartitionContainer<SequencerPoolPartition>>(pfs).get(0); if (lf.getSecurityProfile() != null && r.getSecurityProfile() == null) { r.setSecurityProfile(lf.getSecurityProfile()); } if (lf.getPlatformType() == null && r.getPlatformType() != null) { lf.setPlatformType(r.getPlatformType()); } else { lf.setPlatformType(PlatformType.PACBIO); } ((RunImpl)r).addSequencerPartitionContainer(lf); } else { //more than one flowcell hit to this barcode log.warn(r.getAlias() + ":: More than one container has this barcode. Cannot automatically link to a pre-existing barcode."); } } else { if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); SequencerPartitionContainer f = new SequencerPartitionContainerImpl(); f.setPartitionLimit(cells.size()); f.initEmptyPartitions(); if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); } if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } f.setRun(r); log.info("\\_ Created new container with "+f.getPartitions().size()+" partitions"); long flowId = requestManager.saveSequencerPartitionContainer(f); f.setId(flowId); ((RunImpl)r).addSequencerPartitionContainer(f); //TODO match up samples to libraries and pools? /* for (JSONObject obj : (Iterable<JSONObject>)cells) { int cellindex = obj.getInt("index"); String sample = obj.getString("sample"); SequencerPoolPartition p = f.getPartitionAt(cellindex); if (p.getPool() == null) { Pool pool = new PoolImpl(); } } */ } } } } else { SequencerPartitionContainer f = fs.iterator().next(); f.setSecurityProfile(r.getSecurityProfile()); if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } if (f.getIdentificationBarcode() == null || "".equals(f.getIdentificationBarcode())) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); requestManager.saveSequencerPartitionContainer(f); } } } updatedRuns.put(r.getAlias(), r); runsToSave.add(r); } } else { log.warn("\\_ Run not saved. Saving status: " + is.getRunName()); requestManager.saveStatus(is); } } } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } } else { log.error("No notification status available for " + runName); } } try { if (runsToSave.size() > 0) { int[] saved = requestManager.saveRuns(runsToSave); log.info("Batch saved " + saved.length + " / "+ runs.size() + " runs"); } } catch (IOException e) { log.error("Couldn't save run batch: " + e.getMessage()); e.printStackTrace(); } return updatedRuns; }
private Map<String, Run> processRunJSON(HealthType ht, JSONArray runs, RequestManager requestManager) { Map<String, Run> updatedRuns = new HashMap<String, Run>(); List<Run> runsToSave = new ArrayList<Run>(); DateFormat gsLogDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy"); DateFormat startDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); for (JSONObject run : (Iterable<JSONObject>)runs) { String runName = run.getString("runName"); log.info("Processing " + runName); String status = ""; if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); for (JSONObject cell : (Iterable<JSONObject>)cells) { if (cell.has("cellStatus")) { try { String s = new String(IntegrationUtils.decompress(URLDecoder.decode(cell.getString("cellStatus"), "UTF-8").getBytes())); status += s + "\n\n"; } catch (UnsupportedEncodingException e) { log.error("Cannot decode status xml: " + e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.error("Cannot decompress and decode incoming status: " + e.getMessage()); e.printStackTrace(); } } } } if (!"".equals(status)) { try { //String runLog = run.getString("status"); if (!status.startsWith("ERROR")) { Status is = new PacBioStatus(status); is.setHealth(ht); is.setRunName(runName); Run r = null; Matcher m = p.matcher(runName); if (m.matches()) { try { r = requestManager.getRunByAlias(runName); } catch(IOException ioe) { log.warn("Cannot find run by this alias. This usually means the run hasn't been previously imported. If attemptRunPopulation is false, processing will not take place for this run!"); } } if (attemptRunPopulation) { if (r == null) { log.info("\\_ Saving new run and status: " + is.getRunName()); r = new PacBioRun(status); r.setAlias(run.getString("runName")); r.setDescription(m.group(2)); r.setPairedEnd(false); if (run.has("fullPath")) { r.setFilePath(run.getString("fullPath")); } SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } is.setInstrumentName(sr.getName()); r.setStatus(is); r.setSequencerReference(sr); } else { log.error("\\_ Cannot save " + is.getRunName() + ": no sequencer reference available."); } } else { log.info("\\_ Updating existing run and status: " + is.getRunName()); r.setPlatformType(PlatformType.PACBIO); r.setDescription(m.group(2)); r.setPairedEnd(false); if (r.getSequencerReference() == null) { SequencerReference sr = null; if (run.has("sequencerName")) { sr = requestManager.getSequencerReferenceByName(run.getString("sequencerName")); } if (sr != null) { r.getStatus().setInstrumentName(sr.getName()); r.setSequencerReference(sr); } } if (r.getSequencerReference() != null) { if (run.has("startDate") && !"".equals(run.getString("startDate"))) { try { r.getStatus().setStartDate(startDateFormat.parse(run.getString("startDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } if (run.has("completionDate") && !"".equals(run.getString("completionDate"))) { try { r.getStatus().setCompletionDate(startDateFormat.parse(run.getString("completionDate"))); } catch (ParseException e) { log.error(e.getMessage()); e.printStackTrace(); } } //update path if changed if (run.has("fullPath") && !"".equals(run.getString("fullPath")) && r.getFilePath() != null && !"".equals(r.getFilePath())) { if (!run.getString("fullPath").equals(r.getFilePath())) { log.info("Updating run file path:" + r.getFilePath() + " -> " + run.getString("fullPath")); r.setFilePath(run.getString("fullPath")); } } // update status if run isn't completed or failed if (!r.getStatus().getHealth().equals(HealthType.Completed) && !r.getStatus().getHealth().equals(HealthType.Failed)) { log.info("Saving previously saved status: " + is.getRunName() + " (" + r.getStatus().getHealth().getKey() + " -> " + is.getHealth().getKey() + ")"); //if (!r.getStatus().getHealth().equals(is.getHealth())) { r.setStatus(is); //} //requestManager.saveStatus(is); } } } if (r.getSequencerReference() != null) { List<SequencerPartitionContainer<SequencerPoolPartition>> fs = ((PacBioRun)r).getSequencerPartitionContainers(); if (fs.isEmpty()) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { Collection<SequencerPartitionContainer<SequencerPoolPartition>> pfs = requestManager.listSequencerPartitionContainersByBarcode(run.getString("plateId")); if (!pfs.isEmpty()) { if (pfs.size() == 1) { SequencerPartitionContainer<SequencerPoolPartition> lf = new ArrayList<SequencerPartitionContainer<SequencerPoolPartition>>(pfs).get(0); if (lf.getSecurityProfile() != null && r.getSecurityProfile() == null) { r.setSecurityProfile(lf.getSecurityProfile()); } if (lf.getPlatformType() == null && r.getPlatformType() != null) { lf.setPlatformType(r.getPlatformType()); } else { lf.setPlatformType(PlatformType.PACBIO); } ((RunImpl)r).addSequencerPartitionContainer(lf); } else { //more than one flowcell hit to this barcode log.warn(r.getAlias() + ":: More than one container has this barcode. Cannot automatically link to a pre-existing barcode."); } } else { if (run.has("cells")) { JSONArray cells = run.getJSONArray("cells"); SequencerPartitionContainer f = new SequencerPartitionContainerImpl(); f.setPartitionLimit(cells.size()); f.initEmptyPartitions(); if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); } if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } f.setRun(r); log.info("\\_ Created new container with "+f.getPartitions().size()+" partitions"); long flowId = requestManager.saveSequencerPartitionContainer(f); f.setId(flowId); ((RunImpl)r).addSequencerPartitionContainer(f); //TODO match up samples to libraries and pools? /* for (JSONObject obj : (Iterable<JSONObject>)cells) { int cellindex = obj.getInt("index"); String sample = obj.getString("sample"); SequencerPoolPartition p = f.getPartitionAt(cellindex); if (p.getPool() == null) { Pool pool = new PoolImpl(); } } */ } } } } else { SequencerPartitionContainer f = fs.iterator().next(); f.setSecurityProfile(r.getSecurityProfile()); if (f.getPlatformType() == null && r.getPlatformType() != null) { f.setPlatformType(r.getPlatformType()); } else { f.setPlatformType(PlatformType.PACBIO); } if (f.getIdentificationBarcode() == null || "".equals(f.getIdentificationBarcode())) { if (run.has("plateId") && !"".equals(run.getString("plateId"))) { f.setIdentificationBarcode(run.getString("plateId")); requestManager.saveSequencerPartitionContainer(f); } } } updatedRuns.put(r.getAlias(), r); runsToSave.add(r); } } else { log.warn("\\_ Run not saved. Saving status: " + is.getRunName()); requestManager.saveStatus(is); } } } catch (IOException e) { log.error(e.getMessage()); e.printStackTrace(); } } else { log.error("No notification status available for " + runName); } } try { if (runsToSave.size() > 0) { int[] saved = requestManager.saveRuns(runsToSave); log.info("Batch saved " + saved.length + " / "+ runs.size() + " runs"); } } catch (IOException e) { log.error("Couldn't save run batch: " + e.getMessage()); e.printStackTrace(); } return updatedRuns; }
diff --git a/core/src/main/java/org/dbpedia/extraction/sources/WikipediaDumpParser.java b/core/src/main/java/org/dbpedia/extraction/sources/WikipediaDumpParser.java index 03cbb0f4..cd3b1303 100644 --- a/core/src/main/java/org/dbpedia/extraction/sources/WikipediaDumpParser.java +++ b/core/src/main/java/org/dbpedia/extraction/sources/WikipediaDumpParser.java @@ -1,372 +1,372 @@ package org.dbpedia.extraction.sources; import org.dbpedia.extraction.util.Language; import org.dbpedia.extraction.wikiparser.*; import org.dbpedia.util.Exceptions; import org.dbpedia.util.text.xml.XMLStreamUtils; import scala.Enumeration; import scala.Function1; import scala.util.control.ControlThrowable; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.IOException; import java.io.InputStream; import java.util.logging.Level; import java.util.logging.Logger; import static javax.xml.stream.XMLStreamConstants.START_ELEMENT; public class WikipediaDumpParser { /** the logger */ private static final Logger logger = Logger.getLogger(WikipediaDumpParser.class.getName()); /** */ private static final String ROOT_ELEM = "mediawiki"; /** */ private static final String SITEINFO_ELEM = "siteinfo"; /** */ private static final String BASE_ELEM = "base"; /** */ private static final String PAGE_ELEM = "page"; /** */ private static final String TITLE_ELEM = "title"; /** */ private static final String REDIRECT_ELEM = "redirect"; /** */ private static final String ID_ELEM = "id"; /** */ private static final String NS_ELEM = "ns"; /** */ private static final String REVISION_ELEM = "revision"; /** */ private static final String TEXT_ELEM = "text"; /** the raw input stream */ private final InputStream _stream; /** the reader, null before and after run() */ private XMLStreamReader _reader; /** * Note: current namespace URI is "http://www.mediawiki.org/xml/export-0.6/", * but older dumps use 0.3, so we just ignore the namespace URI. * TODO: make this configurable, or use two different subclasses of this class. */ private final String _namespace; /** * Language used to parse page titles. If null, get language from siteinfo. * If given, ignore siteinfo element. */ private Language _language; /** */ private final Function1<WikiTitle, Boolean> _filter; /** page processor, called for each page */ private final Function1<WikiPage, ?> _processor; /** * @param stream The input stream. Will be closed after reading. * @param namespace expected namespace. If null, namespace is not checked, only local element names. * @param language language used to parse page titles. If null, get language from siteinfo. * If given, ignore siteinfo element. * @param filter page filter. Only matching pages will be processed. * @param processor page processor */ public WikipediaDumpParser(InputStream stream, String namespace, Language language, Function1<WikiTitle, Boolean> filter, Function1<WikiPage, ?> processor) { if (stream == null) throw new NullPointerException("file"); if (processor == null) throw new NullPointerException("processor"); _stream = stream; _namespace = namespace; _language = language; _filter = filter; _processor = processor; } public void run() throws IOException, XMLStreamException, InterruptedException { XMLInputFactory factory = XMLInputFactory.newInstance(); _reader = factory.createXMLStreamReader(_stream, "UTF-8"); try { readDump(); } finally { _reader.close(); _reader = null; } } private void readDump() throws XMLStreamException, InterruptedException { nextTag(); // consume <mediawiki> tag requireStartElement(ROOT_ELEM); nextTag(); if (_language == null) { _language = readSiteInfo(); } else { if (isStartElement(SITEINFO_ELEM)) skipElement(SITEINFO_ELEM, true); } // now after </siteinfo> readPages(); requireEndElement(ROOT_ELEM); } private Language readSiteInfo() throws XMLStreamException { requireStartElement(SITEINFO_ELEM); nextTag(); //Consume <sitename> tag skipElement("sitename", true); requireStartElement(BASE_ELEM); //Read contents of <base>: http://xx.wikipedia.org/wiki/... String uri = _reader.getElementText(); String wikiCode = uri.substring(uri.indexOf("://") + 3, uri.indexOf('.')); Language language = Language.apply(wikiCode); nextTag(); //Consume <generator> tag skipElement("generator", true); //Consume <case> tag skipElement("case", true); //Consume <namespaces> tag // TODO: read namespaces, use them to parse page titles skipElement("namespaces", true); requireEndElement(SITEINFO_ELEM); // now at </siteinfo> nextTag(); return language; } private void readPages() throws XMLStreamException, InterruptedException { while (isStartElement(PAGE_ELEM)) { readPage(); // now at </page> nextTag(); } } private void readPage() throws XMLStreamException { requireStartElement(PAGE_ELEM); nextTag(); //Read title requireStartElement(TITLE_ELEM); String titleStr = _reader.getElementText(); WikiTitle title = parseTitle(titleStr); _reader.nextTag(); // now after </title> //Skip filtered pages if(title == null || ! _filter.apply(title)) { while(! isEndElement(PAGE_ELEM)) _reader.next(); return; } long nsId = requireLong(NS_ELEM, true); // now after </ns> if (title.namespace().id() != nsId) { // Emulate Scala call Namespace(nsId) Not as bad as it looks. // But let's hope the Scala compiler doesn't change its naming pattern... Enumeration.Value expected = org.dbpedia.extraction.wikiparser.package$Namespace$.MODULE$.apply((int)nsId); - logger.log(Level.WARNING, "Error parsing title: found namespace "+title.namespace().id()+", expected "+expected+" in title "+titleStr); + logger.log(Level.WARNING, "Error parsing title: found namespace "+title.namespace()+", expected "+expected+" in title "+titleStr); } //Read page id long pageId = requireLong(ID_ELEM, false); // now at </id> //Read page WikiPage page = null; WikiTitle redirect = null; while (nextTag() == START_ELEMENT) { if (isStartElement(REDIRECT_ELEM)) { // if (_reader.getAttributeCount() != 1) // logger.log(Level.WARNING, "Error parsing rediret ["+title+"] - "+_reader.getAttributeCount()+" attrs"); redirect = parseTitle(_reader.getAttributeValue(null, TITLE_ELEM)); nextTag(); // now at </redirect> } else if (isStartElement(REVISION_ELEM)) { page = readRevision(title, redirect, pageId); // now at </revision> } else { // skip all other elements, don't care about the name, don't skip end tag skipElement(null, false); } } if (page != null) { try { _processor.apply(page); } catch (Exception e) { // emulate Scala exception handling. Ugly... if (e instanceof ControlThrowable) throw Exceptions.unchecked(e); if (e instanceof InterruptedException) throw Exceptions.unchecked(e); else logger.log(Level.WARNING, "Error processing page " + title, e); } } requireEndElement(PAGE_ELEM); } private WikiPage readRevision(WikiTitle title, WikiTitle redirect, long pageId) throws XMLStreamException { String text = null; long revisionId = -1; while (nextTag() == START_ELEMENT) { if (isStartElement(TEXT_ELEM)) { text = _reader.getElementText(); // now at </text> } else if (isStartElement(ID_ELEM)) { revisionId = requireLong(ID_ELEM, false); // now at </id> } else { // skip all other elements, don't care about the name, don't skip end tag skipElement(null, false); } } requireEndElement(REVISION_ELEM); // now at </revision> return new WikiPage(title, redirect, pageId, revisionId, text); } /* Methods for low-level work. Ideally, only these methods would access _reader while the * higher-level methods would only use these. */ /** * @param name expected name of element. if null, don't check name. * @param nextTag should we advance to the next tag after the closing tag of this element? * @return null if title cannot be parsed for some reason * @throws XMLStreamException */ private WikiTitle parseTitle( String titleString ) { try { return WikiTitle.parse(titleString, _language); } catch (Exception e) { logger.log(Level.WARNING, "Error parsing page title ["+titleString+"]", e); return null; } } /** * @param name expected name of element. if null, don't check name. * @param nextTag should we advance to the next tag after the closing tag of this element? * @return long value * @throws XMLStreamException * @throws IllegalArgumentException if element content cannot be parsed as long */ private long requireLong( String name, boolean nextTag ) throws XMLStreamException { XMLStreamUtils.requireStartElement(_reader, _namespace, name); try { long result = Long.parseLong(_reader.getElementText()); if (nextTag) _reader.nextTag(); return result; } catch (NumberFormatException e) { throw new IllegalArgumentException("cannot parse content of element ["+name+"] as long", e); } } private void skipElement(String name, boolean nextTag) throws XMLStreamException { XMLStreamUtils.requireStartElement(_reader, _namespace, name); XMLStreamUtils.skipElement(_reader); if (nextTag) _reader.nextTag(); } private boolean isStartElement(String name) throws XMLStreamException { return XMLStreamUtils.isStartElement(_reader, _namespace, name); } private boolean isEndElement(String name) throws XMLStreamException { return XMLStreamUtils.isEndElement(_reader, _namespace, name); } private void requireStartElement(String name) throws XMLStreamException { XMLStreamUtils.requireStartElement(_reader, _namespace, name); } private void requireEndElement(String name) throws XMLStreamException { XMLStreamUtils.requireEndElement(_reader, _namespace, name); } private int nextTag() throws XMLStreamException { return _reader.nextTag(); } }
true
true
private void readPage() throws XMLStreamException { requireStartElement(PAGE_ELEM); nextTag(); //Read title requireStartElement(TITLE_ELEM); String titleStr = _reader.getElementText(); WikiTitle title = parseTitle(titleStr); _reader.nextTag(); // now after </title> //Skip filtered pages if(title == null || ! _filter.apply(title)) { while(! isEndElement(PAGE_ELEM)) _reader.next(); return; } long nsId = requireLong(NS_ELEM, true); // now after </ns> if (title.namespace().id() != nsId) { // Emulate Scala call Namespace(nsId) Not as bad as it looks. // But let's hope the Scala compiler doesn't change its naming pattern... Enumeration.Value expected = org.dbpedia.extraction.wikiparser.package$Namespace$.MODULE$.apply((int)nsId); logger.log(Level.WARNING, "Error parsing title: found namespace "+title.namespace().id()+", expected "+expected+" in title "+titleStr); } //Read page id long pageId = requireLong(ID_ELEM, false); // now at </id> //Read page WikiPage page = null; WikiTitle redirect = null; while (nextTag() == START_ELEMENT) { if (isStartElement(REDIRECT_ELEM)) { // if (_reader.getAttributeCount() != 1) // logger.log(Level.WARNING, "Error parsing rediret ["+title+"] - "+_reader.getAttributeCount()+" attrs"); redirect = parseTitle(_reader.getAttributeValue(null, TITLE_ELEM)); nextTag(); // now at </redirect> } else if (isStartElement(REVISION_ELEM)) { page = readRevision(title, redirect, pageId); // now at </revision> } else { // skip all other elements, don't care about the name, don't skip end tag skipElement(null, false); } } if (page != null) { try { _processor.apply(page); } catch (Exception e) { // emulate Scala exception handling. Ugly... if (e instanceof ControlThrowable) throw Exceptions.unchecked(e); if (e instanceof InterruptedException) throw Exceptions.unchecked(e); else logger.log(Level.WARNING, "Error processing page " + title, e); } } requireEndElement(PAGE_ELEM); }
private void readPage() throws XMLStreamException { requireStartElement(PAGE_ELEM); nextTag(); //Read title requireStartElement(TITLE_ELEM); String titleStr = _reader.getElementText(); WikiTitle title = parseTitle(titleStr); _reader.nextTag(); // now after </title> //Skip filtered pages if(title == null || ! _filter.apply(title)) { while(! isEndElement(PAGE_ELEM)) _reader.next(); return; } long nsId = requireLong(NS_ELEM, true); // now after </ns> if (title.namespace().id() != nsId) { // Emulate Scala call Namespace(nsId) Not as bad as it looks. // But let's hope the Scala compiler doesn't change its naming pattern... Enumeration.Value expected = org.dbpedia.extraction.wikiparser.package$Namespace$.MODULE$.apply((int)nsId); logger.log(Level.WARNING, "Error parsing title: found namespace "+title.namespace()+", expected "+expected+" in title "+titleStr); } //Read page id long pageId = requireLong(ID_ELEM, false); // now at </id> //Read page WikiPage page = null; WikiTitle redirect = null; while (nextTag() == START_ELEMENT) { if (isStartElement(REDIRECT_ELEM)) { // if (_reader.getAttributeCount() != 1) // logger.log(Level.WARNING, "Error parsing rediret ["+title+"] - "+_reader.getAttributeCount()+" attrs"); redirect = parseTitle(_reader.getAttributeValue(null, TITLE_ELEM)); nextTag(); // now at </redirect> } else if (isStartElement(REVISION_ELEM)) { page = readRevision(title, redirect, pageId); // now at </revision> } else { // skip all other elements, don't care about the name, don't skip end tag skipElement(null, false); } } if (page != null) { try { _processor.apply(page); } catch (Exception e) { // emulate Scala exception handling. Ugly... if (e instanceof ControlThrowable) throw Exceptions.unchecked(e); if (e instanceof InterruptedException) throw Exceptions.unchecked(e); else logger.log(Level.WARNING, "Error processing page " + title, e); } } requireEndElement(PAGE_ELEM); }
diff --git a/src/main/java/uk/co/revthefox/foxbot/commands/CommandUptime.java b/src/main/java/uk/co/revthefox/foxbot/commands/CommandUptime.java index 158ef70..46b9958 100644 --- a/src/main/java/uk/co/revthefox/foxbot/commands/CommandUptime.java +++ b/src/main/java/uk/co/revthefox/foxbot/commands/CommandUptime.java @@ -1,50 +1,49 @@ package uk.co.revthefox.foxbot.commands; import org.pircbotx.Channel; import org.pircbotx.Colors; import org.pircbotx.User; import uk.co.revthefox.foxbot.FoxBot; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.util.Scanner; import java.util.concurrent.TimeUnit; public class CommandUptime extends Command { private FoxBot foxbot; public CommandUptime(FoxBot foxbot) { super("uptime", "command.uptime"); this.foxbot = foxbot; } @Override public void execute(User sender, Channel channel, String[] args) - { - if (args.length == 0) - { + { + if(System.getProperty("os.name").toLowerCase().contains("win")){ + foxbot.getBot().sendNotice(sender, "This command is only supported on linux based systems."); + return; + } try { String uptime = new Scanner(new FileInputStream("/proc/uptime")).next().replaceAll("\\.[0-9]+", ""); int unixTime = Integer.valueOf(uptime); int day = (int) TimeUnit.SECONDS.toDays(unixTime); long hours = TimeUnit.SECONDS.toHours(unixTime) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(unixTime) - (TimeUnit.SECONDS.toHours(unixTime) * 60); long seconds = TimeUnit.SECONDS.toSeconds(unixTime) - (TimeUnit.SECONDS.toMinutes(unixTime) * 60); channel.sendMessage(String.format("%sSystem uptime: %s%s days %s hours %s minutes %s seconds", Colors.GREEN, Colors.NORMAL, day, hours, minute, seconds)); return; } catch (FileNotFoundException ex) { foxbot.getBot().sendNotice(sender, "File \"/proc/uptime\" not found. Are you sure you're using Linux?"); return; } - } - foxbot.getBot().sendNotice(sender, String.format("Wrong number of args! use %suptime", - foxbot.getConfig().getCommandPrefix())); } }
false
true
public void execute(User sender, Channel channel, String[] args) { if (args.length == 0) { try { String uptime = new Scanner(new FileInputStream("/proc/uptime")).next().replaceAll("\\.[0-9]+", ""); int unixTime = Integer.valueOf(uptime); int day = (int) TimeUnit.SECONDS.toDays(unixTime); long hours = TimeUnit.SECONDS.toHours(unixTime) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(unixTime) - (TimeUnit.SECONDS.toHours(unixTime) * 60); long seconds = TimeUnit.SECONDS.toSeconds(unixTime) - (TimeUnit.SECONDS.toMinutes(unixTime) * 60); channel.sendMessage(String.format("%sSystem uptime: %s%s days %s hours %s minutes %s seconds", Colors.GREEN, Colors.NORMAL, day, hours, minute, seconds)); return; } catch (FileNotFoundException ex) { foxbot.getBot().sendNotice(sender, "File \"/proc/uptime\" not found. Are you sure you're using Linux?"); return; } } foxbot.getBot().sendNotice(sender, String.format("Wrong number of args! use %suptime", foxbot.getConfig().getCommandPrefix())); }
public void execute(User sender, Channel channel, String[] args) { if(System.getProperty("os.name").toLowerCase().contains("win")){ foxbot.getBot().sendNotice(sender, "This command is only supported on linux based systems."); return; } try { String uptime = new Scanner(new FileInputStream("/proc/uptime")).next().replaceAll("\\.[0-9]+", ""); int unixTime = Integer.valueOf(uptime); int day = (int) TimeUnit.SECONDS.toDays(unixTime); long hours = TimeUnit.SECONDS.toHours(unixTime) - (day * 24); long minute = TimeUnit.SECONDS.toMinutes(unixTime) - (TimeUnit.SECONDS.toHours(unixTime) * 60); long seconds = TimeUnit.SECONDS.toSeconds(unixTime) - (TimeUnit.SECONDS.toMinutes(unixTime) * 60); channel.sendMessage(String.format("%sSystem uptime: %s%s days %s hours %s minutes %s seconds", Colors.GREEN, Colors.NORMAL, day, hours, minute, seconds)); return; } catch (FileNotFoundException ex) { foxbot.getBot().sendNotice(sender, "File \"/proc/uptime\" not found. Are you sure you're using Linux?"); return; } }
diff --git a/ch.deif.meander/src/ch/deif/meander/map/ComputeLabelingTask.java b/ch.deif.meander/src/ch/deif/meander/map/ComputeLabelingTask.java index 62505606..1eae6051 100644 --- a/ch.deif.meander/src/ch/deif/meander/map/ComputeLabelingTask.java +++ b/ch.deif.meander/src/ch/deif/meander/map/ComputeLabelingTask.java @@ -1,114 +1,115 @@ package ch.deif.meander.map; import java.util.ArrayList; import java.util.Collection; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Device; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.FontData; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.widgets.Display; import ch.akuhn.util.Get; import ch.akuhn.util.ProgressMonitor; import ch.akuhn.values.Arguments; import ch.akuhn.values.TaskValue; import ch.akuhn.values.Value; import ch.deif.meander.DefaultLabelScheme; import ch.deif.meander.Labeling; import ch.deif.meander.Location; import ch.deif.meander.MapInstance; import ch.deif.meander.swt.Label; import ch.deif.meander.swt.LabelOverlay; import ch.deif.meander.util.MapScheme; public class ComputeLabelingTask extends TaskValue<Labeling> { public ComputeLabelingTask(Value<MapInstance> mapInstance, Value<MapScheme<String>> labelScheme) { super("Label layout", mapInstance, labelScheme); } @Override protected Labeling computeValue(ProgressMonitor monitor, Arguments arguments) { MapInstance mapInstance = arguments.nextOrFail(); MapScheme<String> labelScheme = arguments.nextOrFail(); if (labelScheme == null) labelScheme = new DefaultLabelScheme(); return computeValue(monitor, mapInstance, labelScheme); } private Labeling computeValue(ProgressMonitor monitor, MapInstance mapInstance, MapScheme<String> labelScheme) { Device device = Display.getDefault(); Image image = new Image(device, 8, 8); // to get a GC GC gc = new GC(image); Iterable<Label> labels = makeLabels(monitor, gc, mapInstance, labelScheme); labels = new LayoutAlgorithm().layout(labels); gc.dispose(); image.dispose(); return new Labeling(labels); } private Iterable<Label> makeLabels(ProgressMonitor monitor, GC gc, MapInstance map, MapScheme<String> labelScheme) { Collection<Label> labels = new ArrayList<Label>(); Font basefont = new Font(gc.getDevice(), LabelOverlay.ARIAL_NARROW, 12, SWT.NORMAL); for (Location each: map.locations()) { + String text = labelScheme.forLocation(each.getPoint()); + if (text == null) continue; FontData[] fontData = basefont.getFontData(); int height = (int) (Math.sqrt(each.getElevation()) * 2); for (FontData fd: fontData) fd.setHeight(height); Font font = new Font(gc.getDevice(), fontData); gc.setFont(font); - String text = labelScheme.forLocation(each.getPoint()); Point extent = gc.stringExtent(text); labels.add(new Label(each.px, each.py, extent, height, text)); font.dispose(); } basefont.dispose(); return labels; } private class LayoutAlgorithm { Collection<Label> layout; public Iterable<Label> layout(Iterable<Label> labels) { layout = new ArrayList<Label>(); for (Label each: Get.sorted(labels)) mayebAddToLayout(each); return layout; } private void mayebAddToLayout(Label label) { for (double[] each: ORIENTATION) { label.changeOrientation(each[0], each[1]); if (intersectsLabels(label)) continue; layout.add(label); return; } } private boolean intersectsLabels(Label label) { for (Label each: layout) if (label.intersects(each)) return true; return false; } } private static final double[][] ORIENTATION = new double[][] { {-.5d,-1d}, // north {-.5d,-.5d}, // center {-.5d,0d}, // south {-.25d,-1d}, {-.25d,-.5d}, {-.25d,0d}, {-.75d,-1d}, {-.75d,-.5d}, {-.75d,0d}, {0d,-.5d}, {-1d,-.5d}}; }
false
true
private Iterable<Label> makeLabels(ProgressMonitor monitor, GC gc, MapInstance map, MapScheme<String> labelScheme) { Collection<Label> labels = new ArrayList<Label>(); Font basefont = new Font(gc.getDevice(), LabelOverlay.ARIAL_NARROW, 12, SWT.NORMAL); for (Location each: map.locations()) { FontData[] fontData = basefont.getFontData(); int height = (int) (Math.sqrt(each.getElevation()) * 2); for (FontData fd: fontData) fd.setHeight(height); Font font = new Font(gc.getDevice(), fontData); gc.setFont(font); String text = labelScheme.forLocation(each.getPoint()); Point extent = gc.stringExtent(text); labels.add(new Label(each.px, each.py, extent, height, text)); font.dispose(); } basefont.dispose(); return labels; }
private Iterable<Label> makeLabels(ProgressMonitor monitor, GC gc, MapInstance map, MapScheme<String> labelScheme) { Collection<Label> labels = new ArrayList<Label>(); Font basefont = new Font(gc.getDevice(), LabelOverlay.ARIAL_NARROW, 12, SWT.NORMAL); for (Location each: map.locations()) { String text = labelScheme.forLocation(each.getPoint()); if (text == null) continue; FontData[] fontData = basefont.getFontData(); int height = (int) (Math.sqrt(each.getElevation()) * 2); for (FontData fd: fontData) fd.setHeight(height); Font font = new Font(gc.getDevice(), fontData); gc.setFont(font); Point extent = gc.stringExtent(text); labels.add(new Label(each.px, each.py, extent, height, text)); font.dispose(); } basefont.dispose(); return labels; }
diff --git a/src/main/java/herbstJennrichLehmannRitter/ui/GUI/GameMenuGUI.java b/src/main/java/herbstJennrichLehmannRitter/ui/GUI/GameMenuGUI.java index 779a9d8..7853bb4 100644 --- a/src/main/java/herbstJennrichLehmannRitter/ui/GUI/GameMenuGUI.java +++ b/src/main/java/herbstJennrichLehmannRitter/ui/GUI/GameMenuGUI.java @@ -1,183 +1,183 @@ package herbstJennrichLehmannRitter.ui.GUI; import herbstJennrichLehmannRitter.engine.Globals; import herbstJennrichLehmannRitter.ki.KI; import herbstJennrichLehmannRitter.server.GameServer; import herbstJennrichLehmannRitter.ui.impl.LocalEnemyKIUserInterface; import java.rmi.RemoteException; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; /** Description of GameMenuGUI Class * Implementation of Menu Selection */ public class GameMenuGUI extends AbstractMagicGUIElement { private Text nameTextField; private Button startHostButton; private Button startClientButton; private Button startLocalButton; private Button backButton; private MainMenuGUI mainMenuGUI; protected GameServer gameServer; private ClientMenuGUI clientMenuGUI; public GameMenuGUI(Display parent, MainMenuGUI mainMenuGUI) { super(parent); this.mainMenuGUI = mainMenuGUI; this.clientMenuGUI = new ClientMenuGUI(getDisplay(), this.mainMenuGUI); initGUI(); } @Override protected void onInitGUI() { initNameTextLabel(); initNameTextField(); initSelectionTextLabel(); initStartHostButton(); initStartClientButton(); initStartLocalButton(); initBackButton(); } @Override protected void onInitShell() { getShell().setText("Spielauswahl"); getShell().setLayout(new GridLayout(1, false)); } private void initNameTextLabel() { createLabel("Bitte geben Sie ihren Namen an:"); } private void initNameTextField() { GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 3; this.nameTextField = new Text(getShell(), SWT.FILL); this.nameTextField.setText(this.mainMenuGUI.getPlayerName()); this.nameTextField.setLayoutData(gridData); this.nameTextField.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { Text changedText = (Text)e.widget; GameMenuGUI.this.mainMenuGUI.setPlayerName(changedText.getText()); } }); } private void initSelectionTextLabel() { createLabel("Wählen Sie ihre Spieloption aus:"); } private void initStartHostButton() { this.startHostButton = createButton("Starte als Host"); this.startHostButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GameMenuGUI.this.gameServer = Globals.getLocalGameServer(); GameMenuGUI.this.mainMenuGUI.setGameServer(GameMenuGUI.this.gameServer); HostMenuGUI hostMenuGUI = new HostMenuGUI(getDisplay(), GameMenuGUI.this.mainMenuGUI); PlayGameGUI playGameGUI = new PlayGameGUI(getDisplay(), GameMenuGUI.this.mainMenuGUI.getClientUserInterface(), GameMenuGUI.this.gameServer); playGameGUI.setPlayerName(GameMenuGUI.this.mainMenuGUI.getPlayerName()); playGameGUI.setEnemyName("Gegner"); hostMenuGUI.setPlayGameGUI(playGameGUI); GameMenuGUI.this.mainMenuGUI.getClientUserInterface().setPlayGameGUI(playGameGUI); hostMenuGUI.open(); } }); } private void initStartClientButton() { this.startClientButton = createButton("Starte als Client"); this.startClientButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { GameMenuGUI.this.clientMenuGUI.open(); } }); } private void initStartLocalButton() { this.startLocalButton= createButton("Lokales Spiel starten"); this.startLocalButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { GameMenuGUI.this.gameServer = Globals.getLocalGameServer(); GameMenuGUI.this.mainMenuGUI.setGameServer(GameMenuGUI.this.gameServer); PlayGameGUI playGameGUI = new PlayGameGUI(getDisplay(), GameMenuGUI.this.mainMenuGUI.getClientUserInterface(), GameMenuGUI.this.mainMenuGUI.getGameServer()); GameMenuGUI.this.gameServer.register(GameMenuGUI.this.mainMenuGUI. - getClientUserInterface()); + getClientUserInterface()); LocalEnemyKIUserInterface localUserInterface = new LocalEnemyKIUserInterface(); localUserInterface.setMainMenuGUI(GameMenuGUI.this.mainMenuGUI); localUserInterface.setPlayGameGUI(playGameGUI); KI.startBridgedKIOnServer(GameMenuGUI.this.gameServer, GameMenuGUI.this.mainMenuGUI. - getEnemyName(),localUserInterface); + getEnemyName(),localUserInterface); playGameGUI.setPlayerName(GameMenuGUI.this.mainMenuGUI.getPlayerName()); playGameGUI.setEnemyName(GameMenuGUI.this.mainMenuGUI.getEnemyName()); playGameGUI.open(); } catch (RemoteException e2) { e2.printStackTrace(); } } }); } private void initBackButton() { this.backButton = createButton("Zurück"); this.backButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { getShell().close(); } }); } private Button createButton(String text) { Button button = new Button(getShell(), SWT.NONE); button.setText(text); button.setLayoutData(new GridData(GridData.FILL, GridData.CENTER, true, false)); return button; } private void createLabel(String text) { GridData gridData = new GridData(GridData.FILL_HORIZONTAL); gridData.grabExcessHorizontalSpace = true; gridData.horizontalSpan = 3; Label label = new Label(getShell(), SWT.FILL); label.setText(text); label.setBackground(getShell().getBackground()); label.setLayoutData(gridData); } }
false
true
private void initStartLocalButton() { this.startLocalButton= createButton("Lokales Spiel starten"); this.startLocalButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { GameMenuGUI.this.gameServer = Globals.getLocalGameServer(); GameMenuGUI.this.mainMenuGUI.setGameServer(GameMenuGUI.this.gameServer); PlayGameGUI playGameGUI = new PlayGameGUI(getDisplay(), GameMenuGUI.this.mainMenuGUI.getClientUserInterface(), GameMenuGUI.this.mainMenuGUI.getGameServer()); GameMenuGUI.this.gameServer.register(GameMenuGUI.this.mainMenuGUI. getClientUserInterface()); LocalEnemyKIUserInterface localUserInterface = new LocalEnemyKIUserInterface(); localUserInterface.setMainMenuGUI(GameMenuGUI.this.mainMenuGUI); localUserInterface.setPlayGameGUI(playGameGUI); KI.startBridgedKIOnServer(GameMenuGUI.this.gameServer, GameMenuGUI.this.mainMenuGUI. getEnemyName(),localUserInterface); playGameGUI.setPlayerName(GameMenuGUI.this.mainMenuGUI.getPlayerName()); playGameGUI.setEnemyName(GameMenuGUI.this.mainMenuGUI.getEnemyName()); playGameGUI.open(); } catch (RemoteException e2) { e2.printStackTrace(); } } }); }
private void initStartLocalButton() { this.startLocalButton= createButton("Lokales Spiel starten"); this.startLocalButton.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { try { GameMenuGUI.this.gameServer = Globals.getLocalGameServer(); GameMenuGUI.this.mainMenuGUI.setGameServer(GameMenuGUI.this.gameServer); PlayGameGUI playGameGUI = new PlayGameGUI(getDisplay(), GameMenuGUI.this.mainMenuGUI.getClientUserInterface(), GameMenuGUI.this.mainMenuGUI.getGameServer()); GameMenuGUI.this.gameServer.register(GameMenuGUI.this.mainMenuGUI. getClientUserInterface()); LocalEnemyKIUserInterface localUserInterface = new LocalEnemyKIUserInterface(); localUserInterface.setMainMenuGUI(GameMenuGUI.this.mainMenuGUI); localUserInterface.setPlayGameGUI(playGameGUI); KI.startBridgedKIOnServer(GameMenuGUI.this.gameServer, GameMenuGUI.this.mainMenuGUI. getEnemyName(),localUserInterface); playGameGUI.setPlayerName(GameMenuGUI.this.mainMenuGUI.getPlayerName()); playGameGUI.setEnemyName(GameMenuGUI.this.mainMenuGUI.getEnemyName()); playGameGUI.open(); } catch (RemoteException e2) { e2.printStackTrace(); } } }); }
diff --git a/evolvers/src/java/uk/ac/cam/caret/rsf/evolverimpl/StandardDynamicListInputEvolver.java b/evolvers/src/java/uk/ac/cam/caret/rsf/evolverimpl/StandardDynamicListInputEvolver.java index 4bf6701..f18eb1f 100644 --- a/evolvers/src/java/uk/ac/cam/caret/rsf/evolverimpl/StandardDynamicListInputEvolver.java +++ b/evolvers/src/java/uk/ac/cam/caret/rsf/evolverimpl/StandardDynamicListInputEvolver.java @@ -1,83 +1,83 @@ /* * Created on 6 Mar 2007 */ package uk.ac.cam.caret.rsf.evolverimpl; import uk.org.ponder.beanutil.BeanGetter; import uk.org.ponder.rsf.components.UIBasicListMember; import uk.org.ponder.rsf.components.UIBoundString; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIInitBlock; import uk.org.ponder.rsf.components.UIInputMany; import uk.org.ponder.rsf.components.UIJointContainer; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.evolvers.BoundedDynamicListInputEvolver; import uk.org.ponder.rsf.uitype.UITypes; public class StandardDynamicListInputEvolver implements BoundedDynamicListInputEvolver { public static final String COMPONENT_ID = "dynamic-list-input:"; public static final String CORE_ID = "dynamic-list-input-core:"; private BeanGetter rbg; private UIBoundString removelabel; private UIBoundString addlabel; private int maxlength = 1000; private int minlength = 0; public void setRequestBeanGetter(BeanGetter rbg) { this.rbg = rbg; } public UIJointContainer evolve(UIInputMany toevolve) { toevolve.parent.remove(toevolve); UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID); toevolve.ID = "list-control"; togo.addComponent(toevolve); String[] value = toevolve.getValue(); // Note that a bound value is NEVER null, an unset value is detected via // this standard call if (UITypes.isPlaceholder(value)) { value = (String[]) rbg.getBean(toevolve.valuebinding.value); // May as well save on later fixups toevolve.setValue(value); } UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID); int limit = Math.max(minlength, value.length); for (int i = 0; i < limit; ++i) { UIBranchContainer row = UIBranchContainer.make(core, "dynamic-list-input-row:", Integer.toString(i)); String thisvalue = i < value.length? value[i] : ""; UIOutput.make(row, "input", thisvalue); UIBasicListMember.makeBasic(row, "input", toevolve.getFullID(), i); UIOutput.make(row, "remove", removelabel.getValue(), removelabel.valuebinding == null ? null : removelabel.valuebinding.value); } UIOutput.make(core, "add-row", addlabel.getValue(), addlabel.valuebinding == null ? null : addlabel.valuebinding.value); UIInitBlock.make(togo, "init-script", "DynamicListInput.init_DynamicListInput", - new Object[] {core, limit, minlength, maxlength}); + new Object[] {core, new Integer(limit), new Integer(minlength), new Integer(maxlength)}); return togo; } public void setLabels(UIBoundString removelabel, UIBoundString addlabel) { this.removelabel = removelabel; this.addlabel = addlabel; } public void setMaximumLength(int maxlength) { this.maxlength = maxlength; } public void setMinimumLength(int minlength) { this.minlength = minlength; } }
true
true
public UIJointContainer evolve(UIInputMany toevolve) { toevolve.parent.remove(toevolve); UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID); toevolve.ID = "list-control"; togo.addComponent(toevolve); String[] value = toevolve.getValue(); // Note that a bound value is NEVER null, an unset value is detected via // this standard call if (UITypes.isPlaceholder(value)) { value = (String[]) rbg.getBean(toevolve.valuebinding.value); // May as well save on later fixups toevolve.setValue(value); } UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID); int limit = Math.max(minlength, value.length); for (int i = 0; i < limit; ++i) { UIBranchContainer row = UIBranchContainer.make(core, "dynamic-list-input-row:", Integer.toString(i)); String thisvalue = i < value.length? value[i] : ""; UIOutput.make(row, "input", thisvalue); UIBasicListMember.makeBasic(row, "input", toevolve.getFullID(), i); UIOutput.make(row, "remove", removelabel.getValue(), removelabel.valuebinding == null ? null : removelabel.valuebinding.value); } UIOutput.make(core, "add-row", addlabel.getValue(), addlabel.valuebinding == null ? null : addlabel.valuebinding.value); UIInitBlock.make(togo, "init-script", "DynamicListInput.init_DynamicListInput", new Object[] {core, limit, minlength, maxlength}); return togo; }
public UIJointContainer evolve(UIInputMany toevolve) { toevolve.parent.remove(toevolve); UIJointContainer togo = new UIJointContainer(toevolve.parent, toevolve.ID, COMPONENT_ID); toevolve.ID = "list-control"; togo.addComponent(toevolve); String[] value = toevolve.getValue(); // Note that a bound value is NEVER null, an unset value is detected via // this standard call if (UITypes.isPlaceholder(value)) { value = (String[]) rbg.getBean(toevolve.valuebinding.value); // May as well save on later fixups toevolve.setValue(value); } UIBranchContainer core = UIBranchContainer.make(togo, CORE_ID); int limit = Math.max(minlength, value.length); for (int i = 0; i < limit; ++i) { UIBranchContainer row = UIBranchContainer.make(core, "dynamic-list-input-row:", Integer.toString(i)); String thisvalue = i < value.length? value[i] : ""; UIOutput.make(row, "input", thisvalue); UIBasicListMember.makeBasic(row, "input", toevolve.getFullID(), i); UIOutput.make(row, "remove", removelabel.getValue(), removelabel.valuebinding == null ? null : removelabel.valuebinding.value); } UIOutput.make(core, "add-row", addlabel.getValue(), addlabel.valuebinding == null ? null : addlabel.valuebinding.value); UIInitBlock.make(togo, "init-script", "DynamicListInput.init_DynamicListInput", new Object[] {core, new Integer(limit), new Integer(minlength), new Integer(maxlength)}); return togo; }
diff --git a/app/controllers/api/AbstractMemberJsonSerializer.java b/app/controllers/api/AbstractMemberJsonSerializer.java index 3de79ee..2f67cf9 100644 --- a/app/controllers/api/AbstractMemberJsonSerializer.java +++ b/app/controllers/api/AbstractMemberJsonSerializer.java @@ -1,56 +1,53 @@ package controllers.api; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import helpers.JSON; import models.Member; import org.apache.commons.collections.CollectionUtils; import java.lang.reflect.Type; public abstract class AbstractMemberJsonSerializer { private boolean details; protected AbstractMemberJsonSerializer(boolean details) { this.details = details; } public JsonElement serializeMember(Member member, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject result = new JsonObject(); result.addProperty("id", member.id); result.addProperty("firstname", member.firstname); result.addProperty("lastname", member.lastname); result.addProperty("login", member.login); result.addProperty("company", member.company); result.addProperty("shortdesc", member.shortDescription); result.addProperty("longdesc", member.longDescription); result.addProperty("urlimage", member.getUrlImage()); result.addProperty("nbConsults", member.nbConsults); if (CollectionUtils.isNotEmpty(member.links)) { result.add("links", JSON.toJsonArrayOfIds(member.links)); } if (CollectionUtils.isNotEmpty(member.linkers)) { result.add("linkers", JSON.toJsonArrayOfIds(member.linkers)); } - if (CollectionUtils.isNotEmpty(member.interests)) { - result.add("linkers", JSON.toJsonArrayOfIds(member.interests)); - } if (CollectionUtils.isNotEmpty(member.sharedLinks)) { result.add("sharedLinks", jsonSerializationContext.serialize(member.sharedLinks)); } if (CollectionUtils.isNotEmpty(member.interests)) { if (details) { result.add("interests", jsonSerializationContext.serialize(member.interests)); } else { result.add("interests", JSON.toJsonArrayOfIds(member.interests)); } } return result; } }
true
true
public JsonElement serializeMember(Member member, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject result = new JsonObject(); result.addProperty("id", member.id); result.addProperty("firstname", member.firstname); result.addProperty("lastname", member.lastname); result.addProperty("login", member.login); result.addProperty("company", member.company); result.addProperty("shortdesc", member.shortDescription); result.addProperty("longdesc", member.longDescription); result.addProperty("urlimage", member.getUrlImage()); result.addProperty("nbConsults", member.nbConsults); if (CollectionUtils.isNotEmpty(member.links)) { result.add("links", JSON.toJsonArrayOfIds(member.links)); } if (CollectionUtils.isNotEmpty(member.linkers)) { result.add("linkers", JSON.toJsonArrayOfIds(member.linkers)); } if (CollectionUtils.isNotEmpty(member.interests)) { result.add("linkers", JSON.toJsonArrayOfIds(member.interests)); } if (CollectionUtils.isNotEmpty(member.sharedLinks)) { result.add("sharedLinks", jsonSerializationContext.serialize(member.sharedLinks)); } if (CollectionUtils.isNotEmpty(member.interests)) { if (details) { result.add("interests", jsonSerializationContext.serialize(member.interests)); } else { result.add("interests", JSON.toJsonArrayOfIds(member.interests)); } } return result; }
public JsonElement serializeMember(Member member, Type type, JsonSerializationContext jsonSerializationContext) { JsonObject result = new JsonObject(); result.addProperty("id", member.id); result.addProperty("firstname", member.firstname); result.addProperty("lastname", member.lastname); result.addProperty("login", member.login); result.addProperty("company", member.company); result.addProperty("shortdesc", member.shortDescription); result.addProperty("longdesc", member.longDescription); result.addProperty("urlimage", member.getUrlImage()); result.addProperty("nbConsults", member.nbConsults); if (CollectionUtils.isNotEmpty(member.links)) { result.add("links", JSON.toJsonArrayOfIds(member.links)); } if (CollectionUtils.isNotEmpty(member.linkers)) { result.add("linkers", JSON.toJsonArrayOfIds(member.linkers)); } if (CollectionUtils.isNotEmpty(member.sharedLinks)) { result.add("sharedLinks", jsonSerializationContext.serialize(member.sharedLinks)); } if (CollectionUtils.isNotEmpty(member.interests)) { if (details) { result.add("interests", jsonSerializationContext.serialize(member.interests)); } else { result.add("interests", JSON.toJsonArrayOfIds(member.interests)); } } return result; }
diff --git a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/Publisher.java b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/Publisher.java index 76df6080f..2ad155eff 100644 --- a/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/Publisher.java +++ b/bundles/org.eclipse.equinox.p2.publisher/src/org/eclipse/equinox/p2/publisher/Publisher.java @@ -1,263 +1,261 @@ /******************************************************************************* * Copyright (c) 2008, 2010 Code 9 and others. All rights reserved. This * program and the accompanying materials are made available under the terms of * the Eclipse Public License v1.0 which accompanies this distribution, and is * available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Code 9 - initial API and implementation * IBM - ongoing development ******************************************************************************/ package org.eclipse.equinox.p2.publisher; import java.net.URI; import java.util.Collection; import org.eclipse.core.runtime.*; import org.eclipse.equinox.internal.p2.core.helpers.Tracing; import org.eclipse.equinox.internal.p2.publisher.Activator; import org.eclipse.equinox.p2.core.IProvisioningAgent; import org.eclipse.equinox.p2.core.ProvisionException; import org.eclipse.equinox.p2.metadata.IInstallableUnit; import org.eclipse.equinox.p2.repository.*; import org.eclipse.equinox.p2.repository.artifact.IArtifactRepository; import org.eclipse.equinox.p2.repository.artifact.IArtifactRepositoryManager; import org.eclipse.equinox.p2.repository.metadata.IMetadataRepository; import org.eclipse.equinox.p2.repository.metadata.IMetadataRepositoryManager; public class Publisher { static final public String PUBLISH_PACK_FILES_AS_SIBLINGS = "publishPackFilesAsSiblings"; //$NON-NLS-1$ private static final long SERVICE_TIMEOUT = 5000; private IPublisherInfo info; private IPublisherResult results; /** * Returns a metadata repository that corresponds to the given settings. If a repository at the * given location already exists, it is updated with the settings and returned. If no repository * is found then a new Simple repository is created, configured and returned * @param agent the provisioning agent to use when creating the repository * @param location the URL location of the repository * @param name the name of the repository * @param append whether or not the repository should appended or cleared * @param compress whether or not to compress the repository index * @return the discovered or created repository * @throws ProvisionException */ public static IMetadataRepository createMetadataRepository(IProvisioningAgent agent, URI location, String name, boolean append, boolean compress) throws ProvisionException { try { IMetadataRepository result = loadMetadataRepository(agent, location, true, true); if (result != null && result.isModifiable()) { result.setProperty(IRepository.PROP_COMPRESSED, compress ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$ if (!append) result.removeAll(); return result; } } catch (ProvisionException e) { //fall through and create a new repository } // the given repo location is not an existing repo so we have to create something IMetadataRepositoryManager manager = getService(agent, IMetadataRepositoryManager.SERVICE_NAME); String repositoryName = name == null ? location + " - metadata" : name; //$NON-NLS-1$ IMetadataRepository result = manager.createRepository(location, repositoryName, IMetadataRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); if (result != null) { manager.removeRepository(result.getLocation()); result.setProperty(IRepository.PROP_COMPRESSED, compress ? "true" : "false"); //$NON-NLS-1$ //$NON-NLS-2$ return result; } // I don't think we can really get here, but just in case, we better throw a provisioning exception String msg = org.eclipse.equinox.internal.p2.metadata.repository.Messages.repoMan_internalError; throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.INTERNAL_ERROR, msg, null)); } /** * Load a metadata repository from the given location. * @param location the URI location of the repository * @param modifiable whether to ask the manager for a modifiable repository * @param removeFromManager remove the loaded repository from the manager if it wasn't already loaded * @return the loaded repository * @throws ProvisionException */ public static IMetadataRepository loadMetadataRepository(IProvisioningAgent agent, URI location, boolean modifiable, boolean removeFromManager) throws ProvisionException { IMetadataRepositoryManager manager = getService(agent, IMetadataRepositoryManager.SERVICE_NAME); boolean existing = manager.contains(location); IMetadataRepository result = manager.loadRepository(location, modifiable ? IRepositoryManager.REPOSITORY_HINT_MODIFIABLE : 0, null); if (!existing && removeFromManager) manager.removeRepository(location); return result; } /** * Returns an artifact repository that corresponds to the given settings. If a repository at the * given location already exists, it is updated with the settings and returned. If no repository * is found then a new Simple repository is created, configured and returned * @param agent the provisioning agent to use when creating the repository * @param location the URL location of the repository * @param name the name of the repository * @param compress whether or not to compress the repository index * @param reusePackedFiles whether or not to include discovered Pack200 files in the repository * @return the discovered or created repository * @throws ProvisionException */ public static IArtifactRepository createArtifactRepository(IProvisioningAgent agent, URI location, String name, boolean compress, boolean reusePackedFiles) throws ProvisionException { try { IArtifactRepository result = loadArtifactRepository(agent, location, true, true); if (result != null && result.isModifiable()) { result.setProperty(IRepository.PROP_COMPRESSED, compress ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$ if (reusePackedFiles) result.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$ return result; } } catch (ProvisionException e) { //fall through and create a new repository } IArtifactRepositoryManager manager = getService(agent, IArtifactRepositoryManager.SERVICE_NAME); String repositoryName = name != null ? name : location + " - artifacts"; //$NON-NLS-1$ IArtifactRepository result = manager.createRepository(location, repositoryName, IArtifactRepositoryManager.TYPE_SIMPLE_REPOSITORY, null); if (result != null) { manager.removeRepository(result.getLocation()); if (reusePackedFiles) result.setProperty(PUBLISH_PACK_FILES_AS_SIBLINGS, "true"); //$NON-NLS-1$ result.setProperty(IRepository.PROP_COMPRESSED, compress ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$ return result; } // I don't think we can really get here, but just in case, we better throw a provisioning exception String msg = org.eclipse.equinox.internal.p2.artifact.repository.Messages.repoMan_internalError; throw new ProvisionException(new Status(IStatus.ERROR, Activator.ID, ProvisionException.INTERNAL_ERROR, msg, null)); } /** * Load an artifact repository from the given location. * @param location the URI location of the repository * @param modifiable whether to ask the manager for a modifiable repository * @param removeFromManager remove the loaded repository from the manager if it wasn't already loaded * @return the loaded repository * @throws ProvisionException */ public static IArtifactRepository loadArtifactRepository(IProvisioningAgent agent, URI location, boolean modifiable, boolean removeFromManager) throws ProvisionException { IArtifactRepositoryManager manager = getService(agent, IArtifactRepositoryManager.SERVICE_NAME); boolean existing = manager.contains(location); IArtifactRepository result = manager.loadRepository(location, modifiable ? IRepositoryManager.REPOSITORY_HINT_MODIFIABLE : 0, null); if (!existing && removeFromManager) manager.removeRepository(location); return result; } public Publisher(IPublisherInfo info) { this.info = info; results = new PublisherResult(); } /** * Obtains a service from the agent, waiting for a reasonable timeout period * if the service is not yet available. This method never returns <code>null</code>; * an exception is thrown if the service could not be obtained. * * @param <T> The type of the service to return * @param agent The agent to obtain the service from * @param serviceName The name of the service to obtain * @return The service instance */ @SuppressWarnings("unchecked") protected static <T> T getService(IProvisioningAgent agent, String serviceName) { T service = (T) agent.getService(serviceName); if (service != null) return service; long start = System.currentTimeMillis(); do { try { Thread.sleep(100); } catch (InterruptedException e) { //ignore and keep waiting } service = (T) agent.getService(serviceName); if (service != null) return service; } while ((System.currentTimeMillis() - start) < SERVICE_TIMEOUT); //could not obtain the service throw new IllegalStateException("Unable to obtain required service: " + serviceName); //$NON-NLS-1$ } public Publisher(IPublisherInfo info, IPublisherResult results) { this.info = info; this.results = results; } class ArtifactProcess implements IRunnableWithProgress { private final IPublisherAction[] actions; private final IPublisherInfo info; private IStatus result = null; public ArtifactProcess(IPublisherAction[] actions, IPublisherInfo info) { this.info = info; this.actions = actions; } public void run(IProgressMonitor monitor) { MultiStatus finalStatus = new MultiStatus("this", 0, "publishing result", null); //$NON-NLS-1$//$NON-NLS-2$ for (int i = 0; i < actions.length; i++) { if (monitor.isCanceled()) { result = Status.CANCEL_STATUS; return; } IStatus status = actions[i].perform(info, results, monitor); finalStatus.merge(status); monitor.worked(1); } result = finalStatus; } public IStatus getStatus() { return result; } } public IStatus publish(IPublisherAction[] actions, IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); SubMonitor sub = SubMonitor.convert(monitor, actions.length); if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Invoking publisher"); //$NON-NLS-1$ try { ArtifactProcess artifactProcess = new ArtifactProcess(actions, info); IStatus finalStatus = null; if (info.getArtifactRepository() != null) { finalStatus = info.getArtifactRepository().executeBatch(artifactProcess, sub); if (!finalStatus.matches(IStatus.ERROR | IStatus.CANCEL)) // If the batch process didn't report any errors, then // Use the status from our actions finalStatus = artifactProcess.getStatus(); } else { artifactProcess.run(sub); finalStatus = artifactProcess.getStatus(); } if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Publishing complete. Result=" + finalStatus); //$NON-NLS-1$ - // if there were no errors, publish all the ius. - if (finalStatus.isOK() || finalStatus.matches(IStatus.INFO | IStatus.WARNING)) - savePublishedIUs(); + savePublishedIUs(); if (!finalStatus.isOK()) return finalStatus; return Status.OK_STATUS; } finally { sub.done(); } } protected void savePublishedIUs() { IMetadataRepository metadataRepository = info.getMetadataRepository(); if (metadataRepository != null) { Collection<IInstallableUnit> ius = results.getIUs(null, null); metadataRepository.addInstallableUnits(ius); } } }
true
true
public IStatus publish(IPublisherAction[] actions, IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); SubMonitor sub = SubMonitor.convert(monitor, actions.length); if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Invoking publisher"); //$NON-NLS-1$ try { ArtifactProcess artifactProcess = new ArtifactProcess(actions, info); IStatus finalStatus = null; if (info.getArtifactRepository() != null) { finalStatus = info.getArtifactRepository().executeBatch(artifactProcess, sub); if (!finalStatus.matches(IStatus.ERROR | IStatus.CANCEL)) // If the batch process didn't report any errors, then // Use the status from our actions finalStatus = artifactProcess.getStatus(); } else { artifactProcess.run(sub); finalStatus = artifactProcess.getStatus(); } if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Publishing complete. Result=" + finalStatus); //$NON-NLS-1$ // if there were no errors, publish all the ius. if (finalStatus.isOK() || finalStatus.matches(IStatus.INFO | IStatus.WARNING)) savePublishedIUs(); if (!finalStatus.isOK()) return finalStatus; return Status.OK_STATUS; } finally { sub.done(); } }
public IStatus publish(IPublisherAction[] actions, IProgressMonitor monitor) { if (monitor == null) monitor = new NullProgressMonitor(); SubMonitor sub = SubMonitor.convert(monitor, actions.length); if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Invoking publisher"); //$NON-NLS-1$ try { ArtifactProcess artifactProcess = new ArtifactProcess(actions, info); IStatus finalStatus = null; if (info.getArtifactRepository() != null) { finalStatus = info.getArtifactRepository().executeBatch(artifactProcess, sub); if (!finalStatus.matches(IStatus.ERROR | IStatus.CANCEL)) // If the batch process didn't report any errors, then // Use the status from our actions finalStatus = artifactProcess.getStatus(); } else { artifactProcess.run(sub); finalStatus = artifactProcess.getStatus(); } if (Tracing.DEBUG_PUBLISHING) Tracing.debug("Publishing complete. Result=" + finalStatus); //$NON-NLS-1$ savePublishedIUs(); if (!finalStatus.isOK()) return finalStatus; return Status.OK_STATUS; } finally { sub.done(); } }
diff --git a/simbeeotic-vis/src/main/java/harvard/robobees/simbeeotic/component/VisComponent3D.java b/simbeeotic-vis/src/main/java/harvard/robobees/simbeeotic/component/VisComponent3D.java index 66c205c..288a68c 100644 --- a/simbeeotic-vis/src/main/java/harvard/robobees/simbeeotic/component/VisComponent3D.java +++ b/simbeeotic-vis/src/main/java/harvard/robobees/simbeeotic/component/VisComponent3D.java @@ -1,66 +1,66 @@ package harvard.robobees.simbeeotic.component; import com.google.inject.Inject; import com.google.inject.name.Named; import javax.swing.*; import java.awt.*; import java.awt.event.WindowEvent; /** * A top level component that provides a 3D world view and controls. * * @author bkate */ public class VisComponent3D extends JFrame implements VariationComponent { private Java3DWorld world; @Inject private VariationContext context; @Inject(optional=true) @Named("use-background") private boolean useBackground = true; @Override public void initialize() { Dimension size = new Dimension(900, 600); world = new Java3DWorld(useBackground); ControlPanel control = new ControlPanel(world, context.getClockControl(), context.getSimEngine()); JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, world, control); context.getRecorder().addListener(world); pane.setPreferredSize(size); pane.setResizeWeight(1.0); - setTitle("3D Visulaization"); + setTitle("3D Visualization"); setSize(size); setContentPane(pane); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setVisible(true); pane.setDividerLocation(0.7); } @Override public void shutdown() { Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING)); } @Override public void dispose() { world.dispose(); super.dispose(); } }
true
true
public void initialize() { Dimension size = new Dimension(900, 600); world = new Java3DWorld(useBackground); ControlPanel control = new ControlPanel(world, context.getClockControl(), context.getSimEngine()); JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, world, control); context.getRecorder().addListener(world); pane.setPreferredSize(size); pane.setResizeWeight(1.0); setTitle("3D Visulaization"); setSize(size); setContentPane(pane); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setVisible(true); pane.setDividerLocation(0.7); }
public void initialize() { Dimension size = new Dimension(900, 600); world = new Java3DWorld(useBackground); ControlPanel control = new ControlPanel(world, context.getClockControl(), context.getSimEngine()); JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, world, control); context.getRecorder().addListener(world); pane.setPreferredSize(size); pane.setResizeWeight(1.0); setTitle("3D Visualization"); setSize(size); setContentPane(pane); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setVisible(true); pane.setDividerLocation(0.7); }
diff --git a/src/SettingsDialog.java b/src/SettingsDialog.java index 086f87b..011020b 100644 --- a/src/SettingsDialog.java +++ b/src/SettingsDialog.java @@ -1,211 +1,211 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package twelve.team; //import com.sun.xml.internal.ws.Closeable; /** * * @author Curtis */ public class SettingsDialog extends javax.swing.JDialog { /** * */ private static final long serialVersionUID = 2808376280918300839L; /** * Creates new form SettingsDialog */ public SettingsDialog(java.awt.Frame parent, boolean modal, GameController controller, boolean cancelEnabled) { super(parent, modal); this.controller = controller; this.cancelEnabled = cancelEnabled; initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { gameTypeGroup = new javax.swing.ButtonGroup(); btnOK = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); labelWidth = new javax.swing.JLabel(); labelHeight = new javax.swing.JLabel(); comboWidth = new javax.swing.JComboBox<String>(widthChoices); comboHeight = new javax.swing.JComboBox<String>(heightChoices); labelGameType = new javax.swing.JLabel(); radioSingle = new javax.swing.JRadioButton("SINGLE"); radioMultClient = new javax.swing.JRadioButton("MULT_CLIENT"); radioMultServer = new javax.swing.JRadioButton("MULT_SERVER"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); btnOK.setText("OK"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnCancel.setEnabled(cancelEnabled); Settings settings = controller.getSettings(); labelWidth.setText("Board Width: "); labelHeight.setText("Board Height: "); comboWidth.setSelectedItem(""+settings.boardWidth); comboHeight.setSelectedItem(""+settings.boardHeight); labelGameType.setText("Game Type: "); gameTypeGroup.add(radioSingle); switch(settings.gameType){ case SINGLE: radioSingle.setSelected(true); break; case MULT_CLIENT: radioMultClient.setSelected(true); break; case MULT_SERVER: radioMultServer.setSelected(true); break; default: radioSingle.setSelected(true); } radioSingle.setText("Single Player"); radioSingle.setActionCommand("SINGLE"); gameTypeGroup.add(radioMultClient); radioMultClient.setText("Multiplayer - Client"); radioMultClient.setActionCommand("MULT_CLIENT"); gameTypeGroup.add(radioMultServer); radioMultServer.setText("Multiplayer - Server"); radioMultServer.setActionCommand("MULT_SERVER"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnCancel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) - .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelHeight) .addComponent(labelWidth)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(labelGameType) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(radioMultClient) .addComponent(radioSingle) .addComponent(radioMultServer)))) .addGap(0, 50, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelWidth) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelHeight) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelGameType) .addComponent(radioSingle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultClient) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnOK) .addComponent(btnCancel)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnOKActionPerformed(java.awt.event.ActionEvent evt) { int width = Integer.parseInt((String)comboWidth.getSelectedItem()); int height = Integer.parseInt((String)comboHeight.getSelectedItem()); Settings.GameType type; switch(gameTypeGroup.getSelection().getActionCommand()){ case "SINGLE": type = Settings.GameType.SINGLE; break; case "MULT_CLIENT": type = Settings.GameType.MULT_CLIENT; break; case "MULT_SERVER": type = Settings.GameType.MULT_SERVER; break; default: type = Settings.GameType.SINGLE; } Settings settings = new Settings(type, width, height); controller.updateSettings(settings); dispose(); } private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) { dispose(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnOK; private javax.swing.JComboBox<String> comboHeight; private javax.swing.JComboBox<String> comboWidth; private javax.swing.ButtonGroup gameTypeGroup; private javax.swing.JLabel labelGameType; private javax.swing.JLabel labelHeight; private javax.swing.JLabel labelWidth; private javax.swing.JRadioButton radioMultClient; private javax.swing.JRadioButton radioMultServer; private javax.swing.JRadioButton radioSingle; // End of variables declaration//GEN-END:variables private GameController controller; private boolean cancelEnabled; private String[] widthChoices = {"1", "3", "5", "7", "9", "11", "13"}; private String[] heightChoices = {"1", "3", "5", "7", "9", "11", "13"}; }
true
true
private void initComponents() { gameTypeGroup = new javax.swing.ButtonGroup(); btnOK = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); labelWidth = new javax.swing.JLabel(); labelHeight = new javax.swing.JLabel(); comboWidth = new javax.swing.JComboBox<String>(widthChoices); comboHeight = new javax.swing.JComboBox<String>(heightChoices); labelGameType = new javax.swing.JLabel(); radioSingle = new javax.swing.JRadioButton("SINGLE"); radioMultClient = new javax.swing.JRadioButton("MULT_CLIENT"); radioMultServer = new javax.swing.JRadioButton("MULT_SERVER"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); btnOK.setText("OK"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnCancel.setEnabled(cancelEnabled); Settings settings = controller.getSettings(); labelWidth.setText("Board Width: "); labelHeight.setText("Board Height: "); comboWidth.setSelectedItem(""+settings.boardWidth); comboHeight.setSelectedItem(""+settings.boardHeight); labelGameType.setText("Game Type: "); gameTypeGroup.add(radioSingle); switch(settings.gameType){ case SINGLE: radioSingle.setSelected(true); break; case MULT_CLIENT: radioMultClient.setSelected(true); break; case MULT_SERVER: radioMultServer.setSelected(true); break; default: radioSingle.setSelected(true); } radioSingle.setText("Single Player"); radioSingle.setActionCommand("SINGLE"); gameTypeGroup.add(radioMultClient); radioMultClient.setText("Multiplayer - Client"); radioMultClient.setActionCommand("MULT_CLIENT"); gameTypeGroup.add(radioMultServer); radioMultServer.setText("Multiplayer - Server"); radioMultServer.setActionCommand("MULT_SERVER"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnCancel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelHeight) .addComponent(labelWidth)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(labelGameType) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(radioMultClient) .addComponent(radioSingle) .addComponent(radioMultServer)))) .addGap(0, 50, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelWidth) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelHeight) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelGameType) .addComponent(radioSingle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultClient) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnOK) .addComponent(btnCancel)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
private void initComponents() { gameTypeGroup = new javax.swing.ButtonGroup(); btnOK = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); labelWidth = new javax.swing.JLabel(); labelHeight = new javax.swing.JLabel(); comboWidth = new javax.swing.JComboBox<String>(widthChoices); comboHeight = new javax.swing.JComboBox<String>(heightChoices); labelGameType = new javax.swing.JLabel(); radioSingle = new javax.swing.JRadioButton("SINGLE"); radioMultClient = new javax.swing.JRadioButton("MULT_CLIENT"); radioMultServer = new javax.swing.JRadioButton("MULT_SERVER"); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); btnOK.setText("OK"); btnOK.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnOKActionPerformed(evt); } }); btnCancel.setText("Cancel"); btnCancel.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelActionPerformed(evt); } }); btnCancel.setEnabled(cancelEnabled); Settings settings = controller.getSettings(); labelWidth.setText("Board Width: "); labelHeight.setText("Board Height: "); comboWidth.setSelectedItem(""+settings.boardWidth); comboHeight.setSelectedItem(""+settings.boardHeight); labelGameType.setText("Game Type: "); gameTypeGroup.add(radioSingle); switch(settings.gameType){ case SINGLE: radioSingle.setSelected(true); break; case MULT_CLIENT: radioMultClient.setSelected(true); break; case MULT_SERVER: radioMultServer.setSelected(true); break; default: radioSingle.setSelected(true); } radioSingle.setText("Single Player"); radioSingle.setActionCommand("SINGLE"); gameTypeGroup.add(radioMultClient); radioMultClient.setText("Multiplayer - Client"); radioMultClient.setActionCommand("MULT_CLIENT"); gameTypeGroup.add(radioMultServer); radioMultServer.setText("Multiplayer - Server"); radioMultServer.setActionCommand("MULT_SERVER"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(btnCancel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnOK, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(labelHeight) .addComponent(labelWidth)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addComponent(labelGameType) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(radioMultClient) .addComponent(radioSingle) .addComponent(radioMultServer)))) .addGap(0, 50, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelWidth) .addComponent(comboWidth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelHeight) .addComponent(comboHeight, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(labelGameType) .addComponent(radioSingle)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultClient) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(radioMultServer) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnOK) .addComponent(btnCancel)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents
diff --git a/src/net/zdremann/ClassFormaterCallable.java b/src/net/zdremann/ClassFormaterCallable.java index bc68cbb..3568ae8 100644 --- a/src/net/zdremann/ClassFormaterCallable.java +++ b/src/net/zdremann/ClassFormaterCallable.java @@ -1,428 +1,428 @@ package net.zdremann; import java.io.OutputStream; import java.io.PipedOutputStream; 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.concurrent.Callable; import net.zdremann.compare.MethodComparator; import com.sun.javadoc.ClassDoc; import com.sun.javadoc.ConstructorDoc; import com.sun.javadoc.FieldDoc; import com.sun.javadoc.MethodDoc; import com.sun.javadoc.PackageDoc; import com.sun.javadoc.Parameter; import com.sun.javadoc.Type; import com.sun.javadoc.TypeVariable; public class ClassFormaterCallable implements Callable<Void> { private final ClassDoc clazz; public final PipedOutputStream outputStream; public ClassFormaterCallable(ClassDoc clazz) { this.clazz = clazz; this.outputStream = new PipedOutputStream(); } @Override public Void call() throws Exception { try { writeClassToStream(clazz, outputStream); } finally { outputStream.flush(); outputStream.close(); } return null; } private void writeClassToStream(ClassDoc clazz, OutputStream outputStream) throws Exception { PackageDoc pack = clazz.containingPackage(); outputStream.write(String.format("package %s;%n%n", pack.name()).getBytes()); outputStream.write(String.format("import java.StdTypes;%n").getBytes()); outputStream.write(String.format("@:native(\"%s\")%n",clazz.qualifiedName()).getBytes()); if(clazz.isFinal()) { outputStream.write(String.format("@:final%n").getBytes()); } - if(clazz.isOrdinaryClass()) + if(clazz.isClass()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); String extendsAndImplements = ""; boolean doesExtend = false; if(clazz.superclassType() != null) { String superClassName = Stringifier.typeToString(clazz.superclassType()); if(!superClassName.equals(Stringifier.DYNAMIC_NAME)) { extendsAndImplements += String.format("extends %s ", superClassName); doesExtend = true; } } if(clazz.interfaceTypes().length > 0) { if(doesExtend) extendsAndImplements += ", "; for(Type currentInterface : clazz.interfaceTypes()) { extendsAndImplements += String.format("implements %s,", Stringifier.typeToString(currentInterface)); } extendsAndImplements = extendsAndImplements.substring(0, extendsAndImplements.length()-1); } String className = clazz.name().replace('.', '_'); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); className += String.format("<%s>", parameterTypes); } outputStream.write(String.format("extern class %s %s", className, extendsAndImplements).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); // Fields outputStream.write(buildFields(clazz.fields()).toString().getBytes()); // Constructor outputStream.write(buildConstructors(clazz.constructors()).toString().getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isEnum()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern enum %s", clazz.name().replace('.', '_')).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); String consts = ""; for(FieldDoc enumConst : clazz.enumConstants()) { consts += Stringifier.makeComment(enumConst.getRawCommentText()); consts += "\t" + enumConst.name() + ";\n"; } consts = consts.substring(0, consts.length()-1); outputStream.write(consts.getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isInterface()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern interface %s", clazz.name().replace('.', '_')).getBytes()); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); outputStream.write(String.format("<%s>", parameterTypes).getBytes()); } outputStream.write(String.format("%n{%n").getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else { throw new RuntimeException("Unknown Class Type"); } } private StringBuilder buildFields(FieldDoc[] fields) { StringBuilder s = new StringBuilder(); Collection<String> usedFieldNames = new ArrayList<>(); for(FieldDoc field : fields) { s.append(Stringifier.makeComment(field.getRawCommentText())); if(usedFieldNames.contains(field.name())) { s.append("\t//"); } else s.append("\t"); s.append(String.format("%s%n", fieldString(field))); usedFieldNames.add(field.name()); } return s; } private StringBuilder buildConstructors(ConstructorDoc[] constructors_arry) { StringBuilder s = new StringBuilder(); if(constructors_arry.length == 0) return s; List<ConstructorDoc> constructors = Arrays.asList(constructors_arry); Collections.sort(constructors, new MethodComparator()); List<ConstructorDoc> goodConstructors = new ArrayList<>(); List<ConstructorDoc> badConstructors = new ArrayList<>(); boolean firstPublic = constructors.get(0).isPublic(); for(ConstructorDoc constructor : constructors) { if(constructor.isPublic() == firstPublic) goodConstructors.add(constructor); else badConstructors.add(constructor); } for(ConstructorDoc constructor : badConstructors) { s.append(Stringifier.makeComment(constructor.getRawCommentText())); s.append(String.format("\t//%s%n", constructorString(constructor, MethodStringType.OVERLOADEDv3))); } for(int i=0;i<goodConstructors.size();i++) { ConstructorDoc constructor = goodConstructors.get(i); s.append(Stringifier.makeComment(constructor.getRawCommentText())); if(i < goodConstructors.size()-1) s.append(String.format("\t%s%n", constructorString(constructor, MethodStringType.OVERLOADEDv2))); else s.append(String.format("\t%s%n", constructorString(constructor, MethodStringType.NORMAL))); } return s; } private StringBuilder buildMethods(MethodDoc[] methods) { StringBuilder s = new StringBuilder(); Map<String, List<MethodDoc>> methodsByName = new HashMap<String, List<MethodDoc>>(); for(MethodDoc method : methods) { if(method.isSynthetic()) { continue; } List<MethodDoc> methodsWithSameName; if(methodsByName.containsKey(method.name())) { methodsWithSameName = methodsByName.get(method.name()); } else { methodsWithSameName = new ArrayList<>(); methodsByName.put(method.name(), methodsWithSameName); } methodsWithSameName.add(method); } for(List<MethodDoc> list : methodsByName.values()) { List<MethodDoc> goodMethods = new ArrayList<>(); List<MethodDoc> badMethods = new ArrayList<>(); Collections.sort(list, new MethodComparator()); boolean firstPublic = list.get(0).isPublic(); int typeParamNum = list.get(0).typeParameters().length; for(MethodDoc method : list) { if(firstPublic != method.isPublic()) { badMethods.add(method); } else if(typeParamNum < method.typeParameters().length) { badMethods.add(method); } else { goodMethods.add(method); } } for(MethodDoc method : badMethods) { s.append(Stringifier.makeComment(method.getRawCommentText())); s.append(String.format("\t//%s%n", methodString(method, MethodStringType.OVERLOADEDv3))); } for(int i=0;i<goodMethods.size();i++) { MethodDoc method = goodMethods.get(i); s.append(Stringifier.makeComment(method.getRawCommentText())); if(i < goodMethods.size()-1) s.append(String.format("\t%s%n", methodString(method, MethodStringType.OVERLOADEDv2))); else s.append(String.format("\t%s%n", methodString(method, MethodStringType.NORMAL))); } } return s; } private static enum MethodStringType { NORMAL, OVERLOADEDv2, OVERLOADEDv3 } private String fieldString(FieldDoc field) { String s; Object constValue = field.constantValue(); String modifierString = ""; if(constValue != null) modifierString += "inline "; if(field.isStatic()) modifierString += "static "; if(field.isPublic()) modifierString += "public "; else modifierString += "private "; if(constValue == null && !(constValue instanceof Integer || constValue instanceof String || constValue instanceof Float || constValue instanceof Byte)) s = String.format("%svar %s:%s;", modifierString, Stringifier.reservedNameAvoid(field.name()), Stringifier.typeToString(field.type())); else { String formatString; if(constValue instanceof String) { formatString = "%svar %s:%s = \"%s\";"; } else { formatString = "%svar %s:%s = %d;"; } s = String.format(formatString, modifierString, Stringifier.reservedNameAvoid(field.name()), Stringifier.typeToString(field.type()), constValue); } return s; } private String constructorString(ConstructorDoc constructor, MethodStringType type) { String s = ""; String parameterString = ""; for(Parameter param : constructor.parameters()) { parameterString += String.format("%s:%s,", param.name(), Stringifier.typeToString(param.type())); } if(constructor.parameters().length>0) parameterString = parameterString.substring(0, parameterString.length()-1); switch(type) { case NORMAL: String modifierString = ""; if(constructor.isPublic()) modifierString += "public "; else modifierString += "private "; s = String.format("%sfunction new(%s):Void;", modifierString, parameterString); break; case OVERLOADEDv3: case OVERLOADEDv2: s = String.format("@:overload(function (%s) {})", parameterString); break; } return s; } private String methodString(MethodDoc method, MethodStringType type) { String s = ""; String returnString = Stringifier.typeToString(method.returnType()); String parameterString = ""; for(Parameter param : method.parameters()) { parameterString += String.format("%s:%s,", Stringifier.reservedNameAvoid(param.name()), Stringifier.typeToString(param.type())); } if(method.parameters().length>0) parameterString = parameterString.substring(0, parameterString.length()-1); switch(type) { case NORMAL: String modifierString = ""; if(method.overriddenMethod() != null) modifierString += "override "; if(method.isStatic()) modifierString += "static "; if(method.isPublic()) modifierString += "public "; else modifierString += "private "; String functionName = Stringifier.reservedNameAvoid(method.name()); if(method.typeParameters().length > 0) { functionName += "<"; for(TypeVariable typeVar : method.typeParameters()) { functionName += typeVar.typeName() + ","; } functionName = functionName.substring(0, functionName.length()-1) + ">"; } s = String.format("%sfunction %s(%s):%s;", modifierString, functionName, parameterString, returnString); break; case OVERLOADEDv3: case OVERLOADEDv2: s = String.format("@:overload(function (%s):%s {})", parameterString, returnString); break; } return s; } }
true
true
private void writeClassToStream(ClassDoc clazz, OutputStream outputStream) throws Exception { PackageDoc pack = clazz.containingPackage(); outputStream.write(String.format("package %s;%n%n", pack.name()).getBytes()); outputStream.write(String.format("import java.StdTypes;%n").getBytes()); outputStream.write(String.format("@:native(\"%s\")%n",clazz.qualifiedName()).getBytes()); if(clazz.isFinal()) { outputStream.write(String.format("@:final%n").getBytes()); } if(clazz.isOrdinaryClass()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); String extendsAndImplements = ""; boolean doesExtend = false; if(clazz.superclassType() != null) { String superClassName = Stringifier.typeToString(clazz.superclassType()); if(!superClassName.equals(Stringifier.DYNAMIC_NAME)) { extendsAndImplements += String.format("extends %s ", superClassName); doesExtend = true; } } if(clazz.interfaceTypes().length > 0) { if(doesExtend) extendsAndImplements += ", "; for(Type currentInterface : clazz.interfaceTypes()) { extendsAndImplements += String.format("implements %s,", Stringifier.typeToString(currentInterface)); } extendsAndImplements = extendsAndImplements.substring(0, extendsAndImplements.length()-1); } String className = clazz.name().replace('.', '_'); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); className += String.format("<%s>", parameterTypes); } outputStream.write(String.format("extern class %s %s", className, extendsAndImplements).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); // Fields outputStream.write(buildFields(clazz.fields()).toString().getBytes()); // Constructor outputStream.write(buildConstructors(clazz.constructors()).toString().getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isEnum()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern enum %s", clazz.name().replace('.', '_')).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); String consts = ""; for(FieldDoc enumConst : clazz.enumConstants()) { consts += Stringifier.makeComment(enumConst.getRawCommentText()); consts += "\t" + enumConst.name() + ";\n"; } consts = consts.substring(0, consts.length()-1); outputStream.write(consts.getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isInterface()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern interface %s", clazz.name().replace('.', '_')).getBytes()); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); outputStream.write(String.format("<%s>", parameterTypes).getBytes()); } outputStream.write(String.format("%n{%n").getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else { throw new RuntimeException("Unknown Class Type"); } }
private void writeClassToStream(ClassDoc clazz, OutputStream outputStream) throws Exception { PackageDoc pack = clazz.containingPackage(); outputStream.write(String.format("package %s;%n%n", pack.name()).getBytes()); outputStream.write(String.format("import java.StdTypes;%n").getBytes()); outputStream.write(String.format("@:native(\"%s\")%n",clazz.qualifiedName()).getBytes()); if(clazz.isFinal()) { outputStream.write(String.format("@:final%n").getBytes()); } if(clazz.isClass()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); String extendsAndImplements = ""; boolean doesExtend = false; if(clazz.superclassType() != null) { String superClassName = Stringifier.typeToString(clazz.superclassType()); if(!superClassName.equals(Stringifier.DYNAMIC_NAME)) { extendsAndImplements += String.format("extends %s ", superClassName); doesExtend = true; } } if(clazz.interfaceTypes().length > 0) { if(doesExtend) extendsAndImplements += ", "; for(Type currentInterface : clazz.interfaceTypes()) { extendsAndImplements += String.format("implements %s,", Stringifier.typeToString(currentInterface)); } extendsAndImplements = extendsAndImplements.substring(0, extendsAndImplements.length()-1); } String className = clazz.name().replace('.', '_'); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); className += String.format("<%s>", parameterTypes); } outputStream.write(String.format("extern class %s %s", className, extendsAndImplements).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); // Fields outputStream.write(buildFields(clazz.fields()).toString().getBytes()); // Constructor outputStream.write(buildConstructors(clazz.constructors()).toString().getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isEnum()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern enum %s", clazz.name().replace('.', '_')).getBytes()); outputStream.write(String.format("%n{%n").getBytes()); String consts = ""; for(FieldDoc enumConst : clazz.enumConstants()) { consts += Stringifier.makeComment(enumConst.getRawCommentText()); consts += "\t" + enumConst.name() + ";\n"; } consts = consts.substring(0, consts.length()-1); outputStream.write(consts.getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else if(clazz.isInterface()) { outputStream.write(Stringifier.makeComment(clazz.getRawCommentText()).getBytes()); outputStream.write(String.format("extern interface %s", clazz.name().replace('.', '_')).getBytes()); if(clazz.typeParameters().length > 0) { String parameterTypes = ""; for(TypeVariable type : clazz.typeParameters()) { String extendedString = ""; if(type.bounds().length > 0) { extendedString = ":("; for(Type bound : type.bounds()) extendedString += Stringifier.typeToString(bound) + ","; extendedString = extendedString.substring(0, extendedString.length()-1) + ")"; } parameterTypes += type.qualifiedTypeName()+ extendedString+","; } parameterTypes = parameterTypes.substring(0, parameterTypes.length()-1); outputStream.write(String.format("<%s>", parameterTypes).getBytes()); } outputStream.write(String.format("%n{%n").getBytes()); // Methods outputStream.write(buildMethods(clazz.methods()).toString().getBytes()); outputStream.write(String.format("%n}%n").getBytes()); } else { throw new RuntimeException("Unknown Class Type"); } }
diff --git a/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java b/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java index f8ef61b..c19f0e1 100644 --- a/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java +++ b/VisualWAS/src/main/java/com/github/veithen/visualwas/WebSpherePropertiesPanel.java @@ -1,267 +1,267 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.github.veithen.visualwas; import static java.awt.GridBagConstraints.BOTH; import static java.awt.GridBagConstraints.HORIZONTAL; import static java.awt.GridBagConstraints.NONE; import static java.awt.GridBagConstraints.NORTHWEST; import static java.awt.GridBagConstraints.REMAINDER; import static java.awt.GridBagConstraints.WEST; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.MalformedURLException; import java.security.cert.X509Certificate; import java.util.Map; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import javax.net.ssl.SSLHandshakeException; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import org.openide.awt.Mnemonics; import org.openide.util.NbBundle; import com.github.veithen.visualwas.env.EnvUtil; import com.github.veithen.visualwas.trust.NotTrustedException; import com.sun.tools.visualvm.core.properties.PropertiesPanel; import com.sun.tools.visualvm.core.ui.components.Spacer; /** * * @author veithen */ public class WebSpherePropertiesPanel extends PropertiesPanel { private static final long serialVersionUID = -5821630337324177997L; private final JTextField hostField; private final JTextField portField; private final JCheckBox securityCheckbox; private final JTextField usernameField; private final JPasswordField passwordField; private final JCheckBox saveCheckbox; private final JButton testConnectionButton; private final JTextField testConnectionResultField; public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); + resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); - resetConnectionTestResults(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResultField = new JTextField(); testConnectionResultField.setEditable(false); testConnectionResultField.setBorder(BorderFactory.createEmptyBorder()); add(testConnectionResultField, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); } public String getHost() { return hostField.getText(); } public void setHost(String host) { hostField.setText(host); } public int getPort() { try { return Integer.parseInt(portField.getText()); } catch (NumberFormatException ex) { return -1; } } public boolean isSecurityEnabled() { return securityCheckbox.isSelected(); } public String getUsername() { return isSecurityEnabled() ? usernameField.getText() : null; } public char[] getPassword() { return isSecurityEnabled() ? passwordField.getPassword() : null; } public boolean isSaveCredentials() { return isSecurityEnabled() && saveCheckbox.isSelected(); } private void update() { int port = getPort(); testConnectionButton.setEnabled(getHost().length() > 0 && port > 0 && port < 1<<16); boolean securityEnabled = securityCheckbox.isSelected(); usernameField.setEnabled(securityEnabled); passwordField.setEnabled(securityEnabled); saveCheckbox.setEnabled(securityEnabled); } private void testConnection() { while (true) { // TODO: for this to be displayed, we need to execute the code asynchronously testConnectionResultField.setText(NbBundle.getMessage(WebSpherePropertiesPanel.class, "MSG_Connecting")); testConnectionResultField.setForeground(Color.BLACK); JMXServiceURL serviceURL; try { serviceURL = new JMXServiceURL("soap", getHost(), getPort()); } catch (MalformedURLException ex) { // We should never get here throw new Error(ex); } boolean securityEnabled = isSecurityEnabled(); Map<String,Object> env = EnvUtil.createEnvironment(securityEnabled); if (securityEnabled) { env.put(JMXConnector.CREDENTIALS, new String[] { getUsername(), new String(getPassword()) }); } try { JMXConnectorFactory.connect(serviceURL, env); testConnectionResultField.setText(NbBundle.getMessage(WebSpherePropertiesPanel.class, "MSG_Connection_successful")); testConnectionResultField.setForeground(Color.GREEN); setSettingsValid(true); return; } catch (IOException ex) { if (ex instanceof SSLHandshakeException && ex.getCause() instanceof NotTrustedException) { X509Certificate[] chain = ((NotTrustedException)ex.getCause()).getChain(); SignerExchangeDialog dialog = new SignerExchangeDialog(SwingUtilities.getWindowAncestor(this), chain); if (!dialog.showDialog()) { resetConnectionTestResults(); return; } // else loop } else { ex.printStackTrace(); testConnectionResultField.setText(ex.getClass().getSimpleName() + ": " + ex.getMessage()); testConnectionResultField.setForeground(Color.RED); setSettingsValid(false); return; } } } } private void resetConnectionTestResults() { testConnectionResultField.setText(null); setSettingsValid(false); } }
false
true
public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResultField = new JTextField(); testConnectionResultField.setEditable(false); testConnectionResultField.setBorder(BorderFactory.createEmptyBorder()); add(testConnectionResultField, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }
public WebSpherePropertiesPanel() { setLayout(new GridBagLayout()); { JLabel hostLabel = new JLabel(); Mnemonics.setLocalizedText(hostLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Host")); add(hostLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); hostField = new JTextField(); hostLabel.setLabelFor(hostField); hostField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(hostField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel portLabel = new JLabel(); Mnemonics.setLocalizedText(portLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Port")); add(portLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 0, 2, 0), 0, 0)); portField = new JTextField(6); portLabel.setLabelFor(portField); portField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(portField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { securityCheckbox = new JCheckBox(); Mnemonics.setLocalizedText(securityCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Security_enabled")); securityCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); resetConnectionTestResults(); }; }); add(securityCheckbox, new GridBagConstraints(0, 2, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(8, 0, 2, 0), 0, 0)); } { JLabel usernameLabel = new JLabel(); Mnemonics.setLocalizedText(usernameLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Username")); add(usernameLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); usernameField = new JTextField(12); usernameLabel.setLabelFor(usernameField); usernameField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(usernameField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { JLabel passwordLabel = new JLabel(); Mnemonics.setLocalizedText(passwordLabel, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Password")); add(passwordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); passwordField = new JPasswordField(12); passwordLabel.setLabelFor(passwordField); passwordField.getDocument().addDocumentListener(new SimpleDocumentListener() { @Override protected void updated() { update(); resetConnectionTestResults(); } }); add(passwordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, WEST, NONE, new Insets(2, 5, 2, 0), 0, 0)); } { saveCheckbox = new JCheckBox(); // NOI18N Mnemonics.setLocalizedText(saveCheckbox, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Save_security_credentials")); saveCheckbox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { update(); }; }); add(saveCheckbox, new GridBagConstraints(0, 5, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(2, 15, 2, 0), 0, 0)); } { testConnectionButton = new JButton(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { testConnection(); } }); Mnemonics.setLocalizedText(testConnectionButton, NbBundle.getMessage(WebSpherePropertiesPanel.class, "LBL_Test_connection")); add(testConnectionButton, new GridBagConstraints(0, 6, REMAINDER, 1, 0.0, 0.0, WEST, NONE, new Insets(5, 0, 2, 0), 0, 0)); } { testConnectionResultField = new JTextField(); testConnectionResultField.setEditable(false); testConnectionResultField.setBorder(BorderFactory.createEmptyBorder()); add(testConnectionResultField, new GridBagConstraints(0, 7, REMAINDER, 1, 1.0, 0.0, WEST, HORIZONTAL, new Insets(2, 0, 2, 0), 0, 0)); } add(Spacer.create(), new GridBagConstraints(0, 8, 2, 1, 1.0, 1.0, NORTHWEST, BOTH, new Insets(0, 0, 0, 0), 0, 0)); update(); }
diff --git a/src/com/modcrafting/identify/commands/Buying.java b/src/com/modcrafting/identify/commands/Buying.java index 4fdeb7c..5694d25 100644 --- a/src/com/modcrafting/identify/commands/Buying.java +++ b/src/com/modcrafting/identify/commands/Buying.java @@ -1,203 +1,204 @@ package com.modcrafting.identify.commands; import java.util.Random; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import com.modcrafting.identify.Identify; public class Buying { Identify plugin; public Buying(Identify identify) { this.plugin = identify; } /* * This Method should work. * Use inline with IdentifyCommand * Not going to use Safe NO RESTRICTIONS */ public boolean buyList(Player sender, String args, String lvl){ //Config YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); int iprice = config.getInt("prices.levelprice", 500); //Item ItemStack item = sender.getItemInHand(); String itemName = item.getType().toString(); if (item.getType() == Material.AIR){ sender.sendMessage("Your Not Holding Anything."); return true; } //Enchantment if (args.equalsIgnoreCase("all")){ Enchantment[] enchant = Enchantment.values(); int power = 0; String powerLvl = ""; if (lvl == null){ power = 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); int price = power * iprice * 17; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ for (int i=0; i<enchant.length; i++){ item.addUnsafeEnchantment(enchant[i], power); } + plugin.economy.withdrawPlayer(sender.getName(), amtd); sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + "ALL" + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); return true; } } } Enchantment enchant = Enchant.enchantName(args); if(enchant == null){ int pvar = Integer.parseInt(args); enchant = Enchant.enchant(pvar); } String enchName = enchant.toString(); //Power int power = 0; String powerLvl = ""; if (lvl == null){ power = item.getEnchantmentLevel(enchant) + 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); //Economy int price = power * iprice; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ plugin.economy.withdrawPlayer(sender.getName(), amtd); } } //Complete order sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + enchName + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); item.addUnsafeEnchantment(enchant, power); return true; } public boolean buyRandom(Player sender){ //Config YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); int iprice = config.getInt("prices.randomprice", 1000); String eitemPrice = Integer.toString(iprice); //Random Random generator = new Random(); //Item ItemStack item = sender.getItemInHand(); if (item.getType() == Material.AIR){ sender.sendMessage("Your Not Holding Anything."); return true; } String itemName = item.getType().toString(); int randomizer = generator.nextInt(17) + 1; Enchantment eItem = Enchant.enchant(randomizer); Enchantment eItem1 = null; Enchantment eItem2 = null; Enchantment eItem3 = null; Enchantment eItem4 = null; int power = generator.nextInt(eItem.getMaxLevel()) + 1; int power1 = 0; int power2 = 0; int power3 = 0; int power4 = 0; //Random Levels //Max Amount of random enchants 5 int randomMax = config.getInt("randomMax", 5); int randMax = generator.nextInt(randomMax) + 1; if (randMax > 1){ int randomizer1 = generator.nextInt(17) + 1; eItem1 = Enchant.enchant(randomizer1); power1 = generator.nextInt(eItem1.getMaxLevel()) + 1; if (randMax > 2){ int randomizer2 = generator.nextInt(17) + 1; eItem2 = Enchant.enchant(randomizer2); power2 = generator.nextInt(eItem2.getMaxLevel()) + 1; if (randMax > 3){ int randomizer3 = generator.nextInt(17) + 1; eItem3 = Enchant.enchant(randomizer3); power3 = generator.nextInt(eItem3.getMaxLevel()) + 1; if (randMax > 4){ int randomizer4 = generator.nextInt(17) + 1; eItem4 = Enchant.enchant(randomizer4); power4 = generator.nextInt(eItem4.getMaxLevel()) + 1; } } } } boolean testEitem = Enchant.testEnchantment(item); if(testEitem){ sender.sendMessage("This item is already identified."); return true; }else{ if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ plugin.economy.withdrawPlayer(sender.getName(), amtd); } } sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Your " + ChatColor.BLUE + itemName + ChatColor.DARK_AQUA + " has been identified!"); item.addUnsafeEnchantment(eItem, power); if (eItem1 != null) item.addUnsafeEnchantment(eItem1, power1); if (eItem2 != null) item.addUnsafeEnchantment(eItem2, power2); if (eItem3 != null) item.addUnsafeEnchantment(eItem3, power3); if (eItem4 != null) item.addUnsafeEnchantment(eItem4, power4); return true; } } }
true
true
public boolean buyList(Player sender, String args, String lvl){ //Config YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); int iprice = config.getInt("prices.levelprice", 500); //Item ItemStack item = sender.getItemInHand(); String itemName = item.getType().toString(); if (item.getType() == Material.AIR){ sender.sendMessage("Your Not Holding Anything."); return true; } //Enchantment if (args.equalsIgnoreCase("all")){ Enchantment[] enchant = Enchantment.values(); int power = 0; String powerLvl = ""; if (lvl == null){ power = 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); int price = power * iprice * 17; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ for (int i=0; i<enchant.length; i++){ item.addUnsafeEnchantment(enchant[i], power); } sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + "ALL" + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); return true; } } } Enchantment enchant = Enchant.enchantName(args); if(enchant == null){ int pvar = Integer.parseInt(args); enchant = Enchant.enchant(pvar); } String enchName = enchant.toString(); //Power int power = 0; String powerLvl = ""; if (lvl == null){ power = item.getEnchantmentLevel(enchant) + 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); //Economy int price = power * iprice; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ plugin.economy.withdrawPlayer(sender.getName(), amtd); } } //Complete order sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + enchName + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); item.addUnsafeEnchantment(enchant, power); return true; }
public boolean buyList(Player sender, String args, String lvl){ //Config YamlConfiguration config = (YamlConfiguration) plugin.getConfig(); int iprice = config.getInt("prices.levelprice", 500); //Item ItemStack item = sender.getItemInHand(); String itemName = item.getType().toString(); if (item.getType() == Material.AIR){ sender.sendMessage("Your Not Holding Anything."); return true; } //Enchantment if (args.equalsIgnoreCase("all")){ Enchantment[] enchant = Enchantment.values(); int power = 0; String powerLvl = ""; if (lvl == null){ power = 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); int price = power * iprice * 17; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ for (int i=0; i<enchant.length; i++){ item.addUnsafeEnchantment(enchant[i], power); } plugin.economy.withdrawPlayer(sender.getName(), amtd); sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + "ALL" + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); return true; } } } Enchantment enchant = Enchant.enchantName(args); if(enchant == null){ int pvar = Integer.parseInt(args); enchant = Enchant.enchant(pvar); } String enchName = enchant.toString(); //Power int power = 0; String powerLvl = ""; if (lvl == null){ power = item.getEnchantmentLevel(enchant) + 1; }else{ power = Integer.parseInt(lvl); if (power > 10) power = 10; } int powerMax = 10; //enchant.getMaxLevel(); //After 10 looks retarded. if(power > powerMax){ sender.sendMessage(ChatColor.DARK_AQUA + "The enchantment on this item is Maxed"); return true; } powerLvl = Integer.toString(power); //Economy int price = power * iprice; String eitemPrice = Integer.toString(price); if(plugin.setupEconomy()){ double bal = plugin.economy.getBalance(sender.getName()); double amtd = Double.valueOf(eitemPrice.trim()); if(amtd > bal){ sender.sendMessage(ChatColor.DARK_AQUA + "Your don't have enough money!"); return true; }else{ plugin.economy.withdrawPlayer(sender.getName(), amtd); } } //Complete order sender.sendMessage(ChatColor.DARK_AQUA + "You were charged: " + ChatColor.BLUE + eitemPrice); sender.sendMessage(ChatColor.DARK_AQUA + "Current Item: " + ChatColor.BLUE + itemName); sender.sendMessage(ChatColor.DARK_AQUA + "Enchantment " + ChatColor.BLUE + enchName + ChatColor.DARK_AQUA + " added to level " +ChatColor.BLUE + powerLvl + ChatColor.DARK_AQUA + " !"); item.addUnsafeEnchantment(enchant, power); return true; }
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/Search.java b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/Search.java index 06412a5792..464b00a5aa 100644 --- a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/Search.java +++ b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/ace/Search.java @@ -1,45 +1,45 @@ /* * Search.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text.ace; import com.google.gwt.core.client.JavaScriptObject; public class Search extends JavaScriptObject { public static native Search create(String needle, boolean backwards, boolean wrap, boolean caseSensitive, boolean wholeWord, boolean fromSelection, boolean selectionOnly, boolean regexpMode) /*-{ var Search = $wnd.require('ace/search').Search; return new Search().set({ needle: needle, backwards: backwards, wrap: wrap, caseSensitive: caseSensitive, wholeWord: wholeWord, - start: fromSelection ? null : {row: 0, columns: 0}, + start: fromSelection ? null : {row: 0, column: 0}, scope: selectionOnly ? Search.SELECTION : Search.ALL, regExp: regexpMode }) }-*/; protected Search() {} public final native Range find(EditSession session) /*-{ return this.find(session); }-*/; }
true
true
public static native Search create(String needle, boolean backwards, boolean wrap, boolean caseSensitive, boolean wholeWord, boolean fromSelection, boolean selectionOnly, boolean regexpMode) /*-{ var Search = $wnd.require('ace/search').Search; return new Search().set({ needle: needle, backwards: backwards, wrap: wrap, caseSensitive: caseSensitive, wholeWord: wholeWord, start: fromSelection ? null : {row: 0, columns: 0}, scope: selectionOnly ? Search.SELECTION : Search.ALL, regExp: regexpMode }) }-*/;
public static native Search create(String needle, boolean backwards, boolean wrap, boolean caseSensitive, boolean wholeWord, boolean fromSelection, boolean selectionOnly, boolean regexpMode) /*-{ var Search = $wnd.require('ace/search').Search; return new Search().set({ needle: needle, backwards: backwards, wrap: wrap, caseSensitive: caseSensitive, wholeWord: wholeWord, start: fromSelection ? null : {row: 0, column: 0}, scope: selectionOnly ? Search.SELECTION : Search.ALL, regExp: regexpMode }) }-*/;
diff --git a/org.sonar.ide.eclipse.ui.tests/src/org/sonar/ide/eclipse/ui/tests/ConfigurationTest.java b/org.sonar.ide.eclipse.ui.tests/src/org/sonar/ide/eclipse/ui/tests/ConfigurationTest.java index 10448e0c..c55d5e82 100644 --- a/org.sonar.ide.eclipse.ui.tests/src/org/sonar/ide/eclipse/ui/tests/ConfigurationTest.java +++ b/org.sonar.ide.eclipse.ui.tests/src/org/sonar/ide/eclipse/ui/tests/ConfigurationTest.java @@ -1,134 +1,134 @@ /* * Copyright (C) 2010 Evgeny Mandrikov * * Sonar-IDE is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * Sonar-IDE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Sonar-IDE; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.ide.eclipse.ui.tests; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.fail; import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException; import org.eclipse.swtbot.swt.finder.waits.Conditions; import org.eclipse.swtbot.swt.finder.widgets.SWTBotButton; import org.eclipse.swtbot.swt.finder.widgets.SWTBotShell; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTable; import org.eclipse.swtbot.swt.finder.widgets.SWTBotTableItem; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * TODO test remove * * @author Evgeny Mandrikov */ public class ConfigurationTest extends UITestCase { private static final String DEFAULT_HOST = "http://localhost:9000"; private static SWTBotShell shell; private static SWTBotTable table; @BeforeClass public static void openProperties() throws Exception { shell = showGlobalSonarPropertiesPage(); table = bot.table(); } @AfterClass public static void closeProperties() { shell.bot().button("OK").click(); bot.waitUntil(Conditions.shellCloses(shell)); } private static void closeWizard(SWTBotShell wizard) { wizard.activate(); bot.button("Finish").click(); bot.waitUntil(Conditions.shellCloses(wizard)); } @Test public void test() throws Exception { // test default assertThat(table.rowCount(), equalTo(1)); SWTBotTableItem item = table.getTableItem(0); - assertThat(item.getText(), is(DEFAULT_HOST)); + // assertThat(item.getText(), is(DEFAULT_HOST)); assertThat(table.getTableItem(0).isChecked(), is(true)); // test add bot.button("Add...").click(); bot.waitUntil(Conditions.shellIsActive("New Sonar server connection")); SWTBotShell wizard = bot.shell("New Sonar server connection"); wizard.activate(); testConnection(getSonarServerUrl() + "/", true); // test for SONARIDE-90 testConnection(getSonarServerUrl(), true); testConnection("http://fake", false); closeWizard(wizard); assertThat(table.containsItem("http://fake"), is(true)); // test edit table.getTableItem("http://fake").select(); assertThat(bot.button("Edit...").isEnabled(), is(true)); bot.button("Edit...").click(); bot.waitUntil(Conditions.shellIsActive("Edit Sonar server connection")); wizard = bot.shell("Edit Sonar server connection"); wizard.activate(); assertThat(bot.textWithLabel("Sonar server URL :").getText(), is("http://fake")); assertThat(bot.textWithLabel("Username :").getText(), is("")); assertThat(bot.textWithLabel("Password :").getText(), is("")); bot.textWithLabel("Sonar server URL :").setText("http://fake2"); closeWizard(wizard); assertThat(table.containsItem("http://fake2"), is(true)); // set as default item = table.getTableItem("http://fake2"); item.check(); // test remove item.select(); bot.button("Remove").click(); bot.waitUntil(Conditions.shellIsActive("Remove sonar server connection")); bot.button("OK").click(); assertThat(table.containsItem("http://fake2"), is(false)); assertThat(table.getTableItem(0).isChecked(), is(true)); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(false)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); // test remove last table.getTableItem(0).click(); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(true)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); } private void testConnection(String serverUrl, boolean expectedSuccess) { bot.textWithLabel("Sonar server URL :").setText(serverUrl); SWTBotButton button = bot.button("Test connection"); button.click(); bot.waitUntil(Conditions.widgetIsEnabled(button), 1000 * 30); String message = expectedSuccess ? "Successfully connected!" : "Unable to connect."; try { bot.text(" " + message); } catch (WidgetNotFoundException e) { fail("Expected '" + message + "'"); } } }
true
true
public void test() throws Exception { // test default assertThat(table.rowCount(), equalTo(1)); SWTBotTableItem item = table.getTableItem(0); assertThat(item.getText(), is(DEFAULT_HOST)); assertThat(table.getTableItem(0).isChecked(), is(true)); // test add bot.button("Add...").click(); bot.waitUntil(Conditions.shellIsActive("New Sonar server connection")); SWTBotShell wizard = bot.shell("New Sonar server connection"); wizard.activate(); testConnection(getSonarServerUrl() + "/", true); // test for SONARIDE-90 testConnection(getSonarServerUrl(), true); testConnection("http://fake", false); closeWizard(wizard); assertThat(table.containsItem("http://fake"), is(true)); // test edit table.getTableItem("http://fake").select(); assertThat(bot.button("Edit...").isEnabled(), is(true)); bot.button("Edit...").click(); bot.waitUntil(Conditions.shellIsActive("Edit Sonar server connection")); wizard = bot.shell("Edit Sonar server connection"); wizard.activate(); assertThat(bot.textWithLabel("Sonar server URL :").getText(), is("http://fake")); assertThat(bot.textWithLabel("Username :").getText(), is("")); assertThat(bot.textWithLabel("Password :").getText(), is("")); bot.textWithLabel("Sonar server URL :").setText("http://fake2"); closeWizard(wizard); assertThat(table.containsItem("http://fake2"), is(true)); // set as default item = table.getTableItem("http://fake2"); item.check(); // test remove item.select(); bot.button("Remove").click(); bot.waitUntil(Conditions.shellIsActive("Remove sonar server connection")); bot.button("OK").click(); assertThat(table.containsItem("http://fake2"), is(false)); assertThat(table.getTableItem(0).isChecked(), is(true)); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(false)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); // test remove last table.getTableItem(0).click(); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(true)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); }
public void test() throws Exception { // test default assertThat(table.rowCount(), equalTo(1)); SWTBotTableItem item = table.getTableItem(0); // assertThat(item.getText(), is(DEFAULT_HOST)); assertThat(table.getTableItem(0).isChecked(), is(true)); // test add bot.button("Add...").click(); bot.waitUntil(Conditions.shellIsActive("New Sonar server connection")); SWTBotShell wizard = bot.shell("New Sonar server connection"); wizard.activate(); testConnection(getSonarServerUrl() + "/", true); // test for SONARIDE-90 testConnection(getSonarServerUrl(), true); testConnection("http://fake", false); closeWizard(wizard); assertThat(table.containsItem("http://fake"), is(true)); // test edit table.getTableItem("http://fake").select(); assertThat(bot.button("Edit...").isEnabled(), is(true)); bot.button("Edit...").click(); bot.waitUntil(Conditions.shellIsActive("Edit Sonar server connection")); wizard = bot.shell("Edit Sonar server connection"); wizard.activate(); assertThat(bot.textWithLabel("Sonar server URL :").getText(), is("http://fake")); assertThat(bot.textWithLabel("Username :").getText(), is("")); assertThat(bot.textWithLabel("Password :").getText(), is("")); bot.textWithLabel("Sonar server URL :").setText("http://fake2"); closeWizard(wizard); assertThat(table.containsItem("http://fake2"), is(true)); // set as default item = table.getTableItem("http://fake2"); item.check(); // test remove item.select(); bot.button("Remove").click(); bot.waitUntil(Conditions.shellIsActive("Remove sonar server connection")); bot.button("OK").click(); assertThat(table.containsItem("http://fake2"), is(false)); assertThat(table.getTableItem(0).isChecked(), is(true)); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(false)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); // test remove last table.getTableItem(0).click(); assertThat("Edit button enabled", bot.button("Edit...").isEnabled(), is(true)); assertThat("Remove button enabled", bot.button("Remove").isEnabled(), is(false)); }
diff --git a/adl-frontend/src/main/java/org/ow2/mind/adl/graph/InstanceNameInstantiator.java b/adl-frontend/src/main/java/org/ow2/mind/adl/graph/InstanceNameInstantiator.java index 8d5bf84..cfee99b 100644 --- a/adl-frontend/src/main/java/org/ow2/mind/adl/graph/InstanceNameInstantiator.java +++ b/adl-frontend/src/main/java/org/ow2/mind/adl/graph/InstanceNameInstantiator.java @@ -1,74 +1,77 @@ /** * Copyright (C) 2009 STMicroelectronics * * This file is part of "Mind Compiler" is free software: you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact: [email protected] * * Authors: Matthieu Leclercq * Contributors: */ package org.ow2.mind.adl.graph; import static org.ow2.mind.NameHelper.toValidName; import java.util.Map; import org.objectweb.fractal.adl.ADLException; import org.objectweb.fractal.adl.Definition; import org.ow2.mind.adl.ast.ASTHelper; public class InstanceNameInstantiator extends AbstractInstantiator { // --------------------------------------------------------------------------- // Implementation of the Instantiator interface // --------------------------------------------------------------------------- public ComponentGraph instantiate(final Definition definition, final Map<Object, Object> context) throws ADLException { final ComponentGraph graph = clientInstantiatorItf.instantiate(definition, context); initInstanceName(graph, ""); return graph; } protected void initInstanceName(final ComponentGraph graph, String path) { String instanceName = (String) graph.getDecoration("instance-name"); if (instanceName == null) { final Definition def = graph.getDefinition(); if (ASTHelper.isSingleton(def)) { // component is a singleton instanceName = "__component_" + toValidName(def.getName()) + "_singleton_instance"; } else { - final ComponentGraph[] parents = graph.getParents(); - if (parents.length == 0) { + if (graph.getParents().length == 0) { // top level component instanceName = "__component_" + toValidName(def.getName()); - path = instanceName; } else { instanceName = path + "_" + graph.getNameInParent(graph.getParents()[0]); - path = instanceName; } } graph.setDecoration("instance-name", instanceName); + if (graph.getParents().length == 0) { + // top level component + path = "__component_" + toValidName(def.getName()); + } else { + path = path + "_" + graph.getNameInParent(graph.getParents()[0]); + } for (final ComponentGraph subComponent : graph.getSubComponents()) { initInstanceName(subComponent, path); } } } }
false
true
protected void initInstanceName(final ComponentGraph graph, String path) { String instanceName = (String) graph.getDecoration("instance-name"); if (instanceName == null) { final Definition def = graph.getDefinition(); if (ASTHelper.isSingleton(def)) { // component is a singleton instanceName = "__component_" + toValidName(def.getName()) + "_singleton_instance"; } else { final ComponentGraph[] parents = graph.getParents(); if (parents.length == 0) { // top level component instanceName = "__component_" + toValidName(def.getName()); path = instanceName; } else { instanceName = path + "_" + graph.getNameInParent(graph.getParents()[0]); path = instanceName; } } graph.setDecoration("instance-name", instanceName); for (final ComponentGraph subComponent : graph.getSubComponents()) { initInstanceName(subComponent, path); } } }
protected void initInstanceName(final ComponentGraph graph, String path) { String instanceName = (String) graph.getDecoration("instance-name"); if (instanceName == null) { final Definition def = graph.getDefinition(); if (ASTHelper.isSingleton(def)) { // component is a singleton instanceName = "__component_" + toValidName(def.getName()) + "_singleton_instance"; } else { if (graph.getParents().length == 0) { // top level component instanceName = "__component_" + toValidName(def.getName()); } else { instanceName = path + "_" + graph.getNameInParent(graph.getParents()[0]); } } graph.setDecoration("instance-name", instanceName); if (graph.getParents().length == 0) { // top level component path = "__component_" + toValidName(def.getName()); } else { path = path + "_" + graph.getNameInParent(graph.getParents()[0]); } for (final ComponentGraph subComponent : graph.getSubComponents()) { initInstanceName(subComponent, path); } } }
diff --git a/src/glfx/GLFX.java b/src/glfx/GLFX.java index 1bcbcd1..ec26c2e 100644 --- a/src/glfx/GLFX.java +++ b/src/glfx/GLFX.java @@ -1,20 +1,20 @@ package glfx; import engine.Engine; public class GLFX { public static void main(String[] args) { // Initialize Engine Engine engine=new Engine(1024,768); - engine.setIcon("/imgs/icon32.png"); + engine.setIcon("imgs/icon32.png"); Engine.setTitle("OpenGL FrameworkX"); engine.testLoop(); } }
true
true
public static void main(String[] args) { // Initialize Engine Engine engine=new Engine(1024,768); engine.setIcon("/imgs/icon32.png"); Engine.setTitle("OpenGL FrameworkX"); engine.testLoop(); }
public static void main(String[] args) { // Initialize Engine Engine engine=new Engine(1024,768); engine.setIcon("imgs/icon32.png"); Engine.setTitle("OpenGL FrameworkX"); engine.testLoop(); }
diff --git a/src/convexhull/main/ConvexHull.java b/src/convexhull/main/ConvexHull.java index e0b6fbf..fe1d258 100644 --- a/src/convexhull/main/ConvexHull.java +++ b/src/convexhull/main/ConvexHull.java @@ -1,314 +1,316 @@ package convexhull.main; import convexhull.algorithms.AklToussaintHeuristic; import convexhull.algorithms.Algorithm; import convexhull.algorithms.GiftWrapping; import convexhull.algorithms.GrahamScan; import convexhull.algorithms.QuickHull; import convexhull.datastructures.LinkedList; import convexhull.datastructures.LinkedListNode; import convexhull.graphics.PointPrinter; import java.awt.geom.Point2D; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.Scanner; import javax.swing.JFrame; /** * * @author Heikki Haapala */ public class ConvexHull { private static long startTime; /** * * @param args[0] input filename * @param args[1] at or noat to choose whether to use the Akl-Toussaint * @param args[2] amount of iterations to do * @param args[3] algorithm chooser string (gift/quick/graham) * @param args[4] output filename, print to "print" to console or "noout" to * do nothing * @param args[5] draw or nodraw to draw points on screen */ public static void main(String[] args) { LinkedList allPoints = null; Scanner in = new Scanner(System.in); String input; boolean ok = false; if (args.length >= 1) { input = args[0]; } else { input = ""; } while (!ok) { // parsing try { allPoints = parseFile(input); ok = true; System.out.println("Points read from file: " + input); System.out.println("Input: a list of " + allPoints.getLength() + " points.\n"); } catch (Exception ex) { System.out.println("Could not read input file. Filename was: \"" + input + "\""); System.out.print("Input a filename to open: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 2) { input = args[1]; } else { input = ""; } ok = false; LinkedList aklPoints = allPoints; while (!ok) { // Akl-Toussaint heuristic if (input.equals("at")) { System.out.println("Using Akl-Toussaint heuristic."); Algorithm akltoussaint = new AklToussaintHeuristic(); startTimer(); aklPoints = akltoussaint.useAlgorithm(allPoints); System.out.println("Akl-Toussaint heuristic ran in " + stopTimer() + "ms."); ok = true; } else if (input.equals("noat")) { System.out.println("Not using Akl-Toussaint heuristic."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("at : use Akl-Toussaint heuristic."); System.out.println("noat : don't use Akl-Toussaint heuristic."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 3) { input = args[2]; } else { input = ""; } ok = false; int iterations = 0; while (!ok) { try { iterations = Integer.parseInt(input); if (iterations < 1) { throw new IllegalArgumentException(); } ok = true; } catch (Exception e) { System.out.println("Bad argument: \"" + input + "\""); + System.out.println("Valid arguments:"); + System.out.println("A number of iterations to run the algorithm for (integer)."); System.out.print("Input new argument: "); input = in.nextLine(); } } if (args.length >= 4) { input = args[3]; } else { input = ""; } ok = false; Algorithm algorithmToUse = null; // algorithm picking while (!ok) { if (input.equals("gift")) { System.out.println("Using Gift Wrapping algorithm."); algorithmToUse = new GiftWrapping(); ok = true; } else if (input.equals("quick")) { System.out.println("Using QuickHull algorithm."); algorithmToUse = new QuickHull(); ok = true; } else if (input.equals("graham")) { System.out.println("Using Graham scan algorithm."); algorithmToUse = new GrahamScan(); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("gift : use Gift Wrapping algorithm."); System.out.println("quick : use QuickHull algorithm."); System.out.println("graham : use Graham scan algorithm."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } LinkedList hullPoints = aklPoints; System.out.println(iterations + " iterations."); startTimer(); for (int i = 0; i < iterations; i++) { hullPoints = algorithmToUse.useAlgorithm(aklPoints); } double totalTime = stopTimer(); System.out.println("Total run time: " + totalTime + " ms."); System.out.println("Average run time: " + (totalTime / iterations) + " ms."); System.out.println("Output: a list of " + hullPoints.getLength() + " points."); System.out.println(); if (args.length >= 5) { input = args[4]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("print")) { System.out.println("Printing hull points to console (x y)."); LinkedListNode node = hullPoints.getHead(); while (node != null) { Point2D.Double point = node.getPoint(); System.out.println(point.getX() + " " + point.getY()); node = node.getNext(); } ok = true; } else if (input.equals("noout")) { // do nothing System.out.println("Not saving or printing points."); ok = true; } else { try { saveToFile(input, hullPoints); ok = true; System.out.println("Points saved to file: " + input); } catch (Exception ex) { System.out.println("Could not write to output file. Filename was: \"" + input + "\""); System.out.print("Input a new filename or print to print to console: "); input = in.nextLine(); } } System.out.println(); } if (args.length >= 6) { input = args[5]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("draw")) { System.out.println("Drawing points on screen."); drawOnScreen(allPoints, aklPoints ,hullPoints); ok = true; } else if (input.equals("nodraw")) { System.out.println("Not drawing points on screen."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("draw : draw points on screen."); System.out.println("nodraw : don't draw points on screen."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } } /** * * @param filename * @return * @throws Exception */ private static LinkedList parseFile(String filename) throws Exception { File file = new File(filename); LinkedList points = new LinkedList(); // open file BufferedReader br = new BufferedReader(new FileReader(file)); String line; while ((line = br.readLine()) != null) { // remove leading and trailing white spaces line = line.trim(); // ignore lines that start with # or / if (line.charAt(0) != '#' && line.charAt(0) != '/') { String[] split = line.split(" "); double x = Double.parseDouble(split[0]); double y = Double.parseDouble(split[1]); Point2D.Double newPoint = new Point2D.Double(x, y); // add to list points.insert(newPoint); } } // close file br.close(); return points; } /** * * @param filename * @param points * @throws Exception */ private static void saveToFile(String filename, LinkedList points) throws Exception { File file = new File(filename); // open file BufferedWriter vw = new BufferedWriter(new FileWriter(file)); // write to file LinkedListNode node = points.getHead(); while (node != null) { Point2D.Double point = node.getPoint(); vw.append(point.getX() + " " + point.getY()); vw.newLine(); node = node.getNext(); } // close file vw.close(); } /** * */ private static void startTimer() { startTime = System.currentTimeMillis(); } /** * * @return */ private static long stopTimer() { long endTime = System.currentTimeMillis(); return endTime - startTime; } private static void drawOnScreen(LinkedList allPoints, LinkedList aklPoints, LinkedList hullPoints) { JFrame frame = new JFrame("Points"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new PointPrinter(allPoints, aklPoints, hullPoints)); frame.setSize(800, 800); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
true
true
public static void main(String[] args) { LinkedList allPoints = null; Scanner in = new Scanner(System.in); String input; boolean ok = false; if (args.length >= 1) { input = args[0]; } else { input = ""; } while (!ok) { // parsing try { allPoints = parseFile(input); ok = true; System.out.println("Points read from file: " + input); System.out.println("Input: a list of " + allPoints.getLength() + " points.\n"); } catch (Exception ex) { System.out.println("Could not read input file. Filename was: \"" + input + "\""); System.out.print("Input a filename to open: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 2) { input = args[1]; } else { input = ""; } ok = false; LinkedList aklPoints = allPoints; while (!ok) { // Akl-Toussaint heuristic if (input.equals("at")) { System.out.println("Using Akl-Toussaint heuristic."); Algorithm akltoussaint = new AklToussaintHeuristic(); startTimer(); aklPoints = akltoussaint.useAlgorithm(allPoints); System.out.println("Akl-Toussaint heuristic ran in " + stopTimer() + "ms."); ok = true; } else if (input.equals("noat")) { System.out.println("Not using Akl-Toussaint heuristic."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("at : use Akl-Toussaint heuristic."); System.out.println("noat : don't use Akl-Toussaint heuristic."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 3) { input = args[2]; } else { input = ""; } ok = false; int iterations = 0; while (!ok) { try { iterations = Integer.parseInt(input); if (iterations < 1) { throw new IllegalArgumentException(); } ok = true; } catch (Exception e) { System.out.println("Bad argument: \"" + input + "\""); System.out.print("Input new argument: "); input = in.nextLine(); } } if (args.length >= 4) { input = args[3]; } else { input = ""; } ok = false; Algorithm algorithmToUse = null; // algorithm picking while (!ok) { if (input.equals("gift")) { System.out.println("Using Gift Wrapping algorithm."); algorithmToUse = new GiftWrapping(); ok = true; } else if (input.equals("quick")) { System.out.println("Using QuickHull algorithm."); algorithmToUse = new QuickHull(); ok = true; } else if (input.equals("graham")) { System.out.println("Using Graham scan algorithm."); algorithmToUse = new GrahamScan(); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("gift : use Gift Wrapping algorithm."); System.out.println("quick : use QuickHull algorithm."); System.out.println("graham : use Graham scan algorithm."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } LinkedList hullPoints = aklPoints; System.out.println(iterations + " iterations."); startTimer(); for (int i = 0; i < iterations; i++) { hullPoints = algorithmToUse.useAlgorithm(aklPoints); } double totalTime = stopTimer(); System.out.println("Total run time: " + totalTime + " ms."); System.out.println("Average run time: " + (totalTime / iterations) + " ms."); System.out.println("Output: a list of " + hullPoints.getLength() + " points."); System.out.println(); if (args.length >= 5) { input = args[4]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("print")) { System.out.println("Printing hull points to console (x y)."); LinkedListNode node = hullPoints.getHead(); while (node != null) { Point2D.Double point = node.getPoint(); System.out.println(point.getX() + " " + point.getY()); node = node.getNext(); } ok = true; } else if (input.equals("noout")) { // do nothing System.out.println("Not saving or printing points."); ok = true; } else { try { saveToFile(input, hullPoints); ok = true; System.out.println("Points saved to file: " + input); } catch (Exception ex) { System.out.println("Could not write to output file. Filename was: \"" + input + "\""); System.out.print("Input a new filename or print to print to console: "); input = in.nextLine(); } } System.out.println(); } if (args.length >= 6) { input = args[5]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("draw")) { System.out.println("Drawing points on screen."); drawOnScreen(allPoints, aklPoints ,hullPoints); ok = true; } else if (input.equals("nodraw")) { System.out.println("Not drawing points on screen."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("draw : draw points on screen."); System.out.println("nodraw : don't draw points on screen."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } }
public static void main(String[] args) { LinkedList allPoints = null; Scanner in = new Scanner(System.in); String input; boolean ok = false; if (args.length >= 1) { input = args[0]; } else { input = ""; } while (!ok) { // parsing try { allPoints = parseFile(input); ok = true; System.out.println("Points read from file: " + input); System.out.println("Input: a list of " + allPoints.getLength() + " points.\n"); } catch (Exception ex) { System.out.println("Could not read input file. Filename was: \"" + input + "\""); System.out.print("Input a filename to open: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 2) { input = args[1]; } else { input = ""; } ok = false; LinkedList aklPoints = allPoints; while (!ok) { // Akl-Toussaint heuristic if (input.equals("at")) { System.out.println("Using Akl-Toussaint heuristic."); Algorithm akltoussaint = new AklToussaintHeuristic(); startTimer(); aklPoints = akltoussaint.useAlgorithm(allPoints); System.out.println("Akl-Toussaint heuristic ran in " + stopTimer() + "ms."); ok = true; } else if (input.equals("noat")) { System.out.println("Not using Akl-Toussaint heuristic."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("at : use Akl-Toussaint heuristic."); System.out.println("noat : don't use Akl-Toussaint heuristic."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } if (args.length >= 3) { input = args[2]; } else { input = ""; } ok = false; int iterations = 0; while (!ok) { try { iterations = Integer.parseInt(input); if (iterations < 1) { throw new IllegalArgumentException(); } ok = true; } catch (Exception e) { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("A number of iterations to run the algorithm for (integer)."); System.out.print("Input new argument: "); input = in.nextLine(); } } if (args.length >= 4) { input = args[3]; } else { input = ""; } ok = false; Algorithm algorithmToUse = null; // algorithm picking while (!ok) { if (input.equals("gift")) { System.out.println("Using Gift Wrapping algorithm."); algorithmToUse = new GiftWrapping(); ok = true; } else if (input.equals("quick")) { System.out.println("Using QuickHull algorithm."); algorithmToUse = new QuickHull(); ok = true; } else if (input.equals("graham")) { System.out.println("Using Graham scan algorithm."); algorithmToUse = new GrahamScan(); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("gift : use Gift Wrapping algorithm."); System.out.println("quick : use QuickHull algorithm."); System.out.println("graham : use Graham scan algorithm."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } LinkedList hullPoints = aklPoints; System.out.println(iterations + " iterations."); startTimer(); for (int i = 0; i < iterations; i++) { hullPoints = algorithmToUse.useAlgorithm(aklPoints); } double totalTime = stopTimer(); System.out.println("Total run time: " + totalTime + " ms."); System.out.println("Average run time: " + (totalTime / iterations) + " ms."); System.out.println("Output: a list of " + hullPoints.getLength() + " points."); System.out.println(); if (args.length >= 5) { input = args[4]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("print")) { System.out.println("Printing hull points to console (x y)."); LinkedListNode node = hullPoints.getHead(); while (node != null) { Point2D.Double point = node.getPoint(); System.out.println(point.getX() + " " + point.getY()); node = node.getNext(); } ok = true; } else if (input.equals("noout")) { // do nothing System.out.println("Not saving or printing points."); ok = true; } else { try { saveToFile(input, hullPoints); ok = true; System.out.println("Points saved to file: " + input); } catch (Exception ex) { System.out.println("Could not write to output file. Filename was: \"" + input + "\""); System.out.print("Input a new filename or print to print to console: "); input = in.nextLine(); } } System.out.println(); } if (args.length >= 6) { input = args[5]; } else { input = ""; } ok = false; while (!ok) { if (input.equals("draw")) { System.out.println("Drawing points on screen."); drawOnScreen(allPoints, aklPoints ,hullPoints); ok = true; } else if (input.equals("nodraw")) { System.out.println("Not drawing points on screen."); ok = true; } else { System.out.println("Bad argument: \"" + input + "\""); System.out.println("Valid arguments:"); System.out.println("draw : draw points on screen."); System.out.println("nodraw : don't draw points on screen."); System.out.print("Input new argument: "); input = in.nextLine(); } System.out.println(); } }
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java index 7d66284..a80b283 100644 --- a/Essentials/src/com/earth2me/essentials/commands/Commandsell.java +++ b/Essentials/src/com/earth2me/essentials/commands/Commandsell.java @@ -1,88 +1,91 @@ package com.earth2me.essentials.commands; import org.bukkit.Server; import com.earth2me.essentials.Essentials; import com.earth2me.essentials.InventoryWorkaround; import com.earth2me.essentials.ItemDb; import com.earth2me.essentials.User; import org.bukkit.Material; import org.bukkit.inventory.ItemStack; public class Commandsell extends EssentialsCommand { public Commandsell() { super("sell"); } @Override public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /sell [itemname|id] [-][amount]"); return; } ItemStack is = ItemDb.get(args[0]); if(is.getType() == Material.AIR) { throw new Exception("You really tried to sell Air? Put an item in your hand."); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); + if (args[1].startsWith("-")) { + amount = -amount; + } } double worth = Essentials.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); if (Double.isNaN(worth)) { throw new Exception("That item cannot be sold to the server."); } if (requireStack && !stack) { throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } max += s.getAmount(); } if (stack) { amount *= 64; } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % 64; } if (amount > max || amount < 1) { user.sendMessage("§cYou do not have enough of that item to sell."); user.sendMessage("§7If you meant to sell all of your items of that type, use /sell itemname"); user.sendMessage("§7/sell itemname -1 will sell all but one item, etc."); return; } user.charge(this); InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability())); user.updateInventory(); user.giveMoney(worth * amount); user.sendMessage("§7Sold for §c$" + (worth * amount) + "§7 (" + amount + " items at $" + worth + " each)"); } }
true
true
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /sell [itemname|id] [-][amount]"); return; } ItemStack is = ItemDb.get(args[0]); if(is.getType() == Material.AIR) { throw new Exception("You really tried to sell Air? Put an item in your hand."); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); } double worth = Essentials.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); if (Double.isNaN(worth)) { throw new Exception("That item cannot be sold to the server."); } if (requireStack && !stack) { throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } max += s.getAmount(); } if (stack) { amount *= 64; } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % 64; } if (amount > max || amount < 1) { user.sendMessage("§cYou do not have enough of that item to sell."); user.sendMessage("§7If you meant to sell all of your items of that type, use /sell itemname"); user.sendMessage("§7/sell itemname -1 will sell all but one item, etc."); return; } user.charge(this); InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability())); user.updateInventory(); user.giveMoney(worth * amount); user.sendMessage("§7Sold for §c$" + (worth * amount) + "§7 (" + amount + " items at $" + worth + " each)"); }
public void run(Server server, Essentials parent, User user, String commandLabel, String[] args) throws Exception { if (args.length < 1) { user.sendMessage("§cUsage: /sell [itemname|id] [-][amount]"); return; } ItemStack is = ItemDb.get(args[0]); if(is.getType() == Material.AIR) { throw new Exception("You really tried to sell Air? Put an item in your hand."); } int id = is.getTypeId(); int amount = 0; if (args.length > 1) { amount = Integer.parseInt(args[1].replaceAll("[^0-9]", "")); if (args[1].startsWith("-")) { amount = -amount; } } double worth = Essentials.getWorth().getPrice(is); boolean stack = args.length > 1 && args[1].endsWith("s"); boolean requireStack = parent.getConfiguration().getBoolean("trade-in-stacks-" + id, false); if (Double.isNaN(worth)) { throw new Exception("That item cannot be sold to the server."); } if (requireStack && !stack) { throw new Exception("Item must be traded in stacks. A quantity of 2s would be two stacks, etc."); } int max = 0; for (ItemStack s : user.getInventory().getContents()) { if (s == null) { continue; } if (s.getTypeId() != is.getTypeId()) { continue; } if (s.getDurability() != is.getDurability()) { continue; } max += s.getAmount(); } if (stack) { amount *= 64; } if (amount < 1) { amount += max; } if (requireStack) { amount -= amount % 64; } if (amount > max || amount < 1) { user.sendMessage("§cYou do not have enough of that item to sell."); user.sendMessage("§7If you meant to sell all of your items of that type, use /sell itemname"); user.sendMessage("§7/sell itemname -1 will sell all but one item, etc."); return; } user.charge(this); InventoryWorkaround.removeItem(user.getInventory(), true, new ItemStack(is.getType(), amount, is.getDurability())); user.updateInventory(); user.giveMoney(worth * amount); user.sendMessage("§7Sold for §c$" + (worth * amount) + "§7 (" + amount + " items at $" + worth + " each)"); }
diff --git a/src/replicatorg/drivers/reprap/RepRap5DDriver.java b/src/replicatorg/drivers/reprap/RepRap5DDriver.java index bed30c41..28bca974 100644 --- a/src/replicatorg/drivers/reprap/RepRap5DDriver.java +++ b/src/replicatorg/drivers/reprap/RepRap5DDriver.java @@ -1,1331 +1,1331 @@ /* RepRap5DDriver.java This is a driver to control a machine that contains a GCode parser and communicates via Serial Port. Part of the ReplicatorG project - http://www.replicat.org Copyright (c) 2008 Zach Smith This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* TODOs: * (M6 T0 (Wait for tool to heat up)) - not supported? Rewrite to other code? * * */ package replicatorg.drivers.reprap; import java.io.UnsupportedEncodingException; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.EnumSet; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.w3c.dom.Node; import replicatorg.app.Base; import replicatorg.app.tools.XML; import replicatorg.app.util.serial.ByteFifo; import replicatorg.app.util.serial.SerialFifoEventListener; import replicatorg.drivers.RealtimeControl; import replicatorg.drivers.RetryException; import replicatorg.drivers.SerialDriver; import replicatorg.drivers.reprap.ExtrusionUpdater.Direction; import replicatorg.machine.model.AxisId; import replicatorg.machine.model.ToolModel; import replicatorg.util.Point5d; public class RepRap5DDriver extends SerialDriver implements SerialFifoEventListener, RealtimeControl { private static Pattern gcodeCommentPattern = Pattern.compile("\\([^)]*\\)|;.*"); private static Pattern resendLinePattern = Pattern.compile("([0-9]+)"); private static Pattern gcodeLineNumberPattern = Pattern.compile("n\\s*([0-9]+)"); public final AtomicReference<Double> feedrate = new AtomicReference<Double>(0.0); public final AtomicReference<Double> ePosition = new AtomicReference<Double>(0.0); private final ReentrantLock sendCommandLock = new ReentrantLock(); /** true if a line containing the start keyword has been received from the firmware*/ private final AtomicBoolean startReceived = new AtomicBoolean(false); /** true if a line containing the ok keyword has been received from the firmware*/ private final AtomicBoolean okReceived = new AtomicBoolean(false); /** * An above zero level shows more info */ private int debugLevel = 0; /** * Temporary. This allows for purposefully injection of noise to speed up debugging of retransmits and recovery. */ private int introduceNoiseEveryN = -1; private int lineIterator = 0; private int numResends = 0; /** * Enables five D GCodes if true. If false reverts to traditional 3D Gcodes */ private boolean fiveD = true; /** * Adds check-sums on to each gcode line sent to the RepRap. */ private boolean hasChecksums = true; /** * Enables pulsing RTS to restart the RepRap on connect. */ private boolean pulseRTS = true; /** * if true the firmware sends "resend: 1234" and then "ok" for * the same line and we need to eat that extra "ok". Teacup does * not do this but Tonokip, Klimentkip and FiveD do */ private boolean okAfterResend = true; /** * if true the firmware sends "start" followed by "ok" on reset * and we need to eat that extra "ok". Teacup is the only known * firmware with this behavior. */ private boolean okAfterStart = false; /** * if true all E moves are relative, so there's no need to snoop * E moves and ePosition stays at 0.0 all the time. Teacup has * always relative E. */ private boolean alwaysRelativeE = false; /** * if true the driver will wait for a "start" signal when pulsing rts low * before initialising the printer. */ private boolean waitForStart = false; /** * configures the time to wait for the first response from the RepRap in ms. */ private long waitForStartTimeout = 1000; private int waitForStartRetries = 3; /** * This allows for real time adjustment of certain printing variables! */ private boolean realtimeControl = false; private double rcFeedrateMultiply = 1; private double rcTravelFeedrateMultiply = 1; private double rcExtrusionMultiply = 1; private double rcFeedrateLimit = 60*300; // 300mm/s still works on Ultimakers! private final ExtrusionUpdater extrusionUpdater = new ExtrusionUpdater(this); /** * the size of the buffer on the GCode host */ private int maxBufferSize = 128; /** * The commands sent but not yet acknowledged by the firmware. Stored so they can be resent * if there is a checksum problem. */ private LinkedList<String> buffer = new LinkedList<String>(); private ReentrantLock bufferLock = new ReentrantLock(); /** locks the readResponse method to prevent multiple concurrent reads */ private ReentrantLock readResponseLock = new ReentrantLock(); protected DecimalFormat df; private AtomicInteger lineNumber = new AtomicInteger(-1); public RepRap5DDriver() { super(); // Support for emergency stop is not assumed until it is detected. Detection of this feature should be in initialization. hasEmergencyStop = false; // Support for soft stop is not assumed until it is detected. Detection of this feature should be in initialization. hasSoftStop = false; // init our variables. setInitialized(false); //Thank you Alexey (http://replicatorg.lighthouseapp.com/users/166956) DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); df = new DecimalFormat("#.######", dfs); } public String getDriverName() { return "RepRap5D"; } public synchronized void loadXML(Node xml) { super.loadXML(xml); // load from our XML config, if we have it. if (XML.hasChildNode(xml, "waitforstart")) { Node startNode = XML.getChildNodeByName(xml, "waitforstart"); String enabled = XML.getAttributeValue(startNode, "enabled"); if (enabled !=null) waitForStart = Boolean.parseBoolean(enabled); String timeout = XML.getAttributeValue(startNode, "timeout"); if (timeout !=null) waitForStartTimeout = Long.parseLong(timeout); String retries = XML.getAttributeValue(startNode, "retries"); if (retries !=null) waitForStartRetries = Integer.parseInt(retries); } if (XML.hasChildNode(xml, "pulserts")) { pulseRTS = Boolean.parseBoolean(XML.getChildNodeValue(xml, "pulserts")); } if (XML.hasChildNode(xml, "checksums")) { hasChecksums = Boolean.parseBoolean(XML.getChildNodeValue(xml, "checksums")); } if (XML.hasChildNode(xml, "fived")) { fiveD = Boolean.parseBoolean(XML.getChildNodeValue(xml, "fived")); } if (XML.hasChildNode(xml, "debugLevel")) { debugLevel = Integer.parseInt(XML.getChildNodeValue(xml, "debugLevel")); } if (XML.hasChildNode(xml, "limitFeedrate")) { rcFeedrateLimit = Double.parseDouble(XML.getChildNodeValue(xml, "limitFeedrate")); } if (XML.hasChildNode(xml, "okAfterResend")) { okAfterResend = Boolean.parseBoolean(XML.getChildNodeValue(xml, "okAfterResend")); } if (XML.hasChildNode(xml, "okAfterStart")) { okAfterStart = Boolean.parseBoolean(XML.getChildNodeValue(xml, "okAfterStart")); } if (XML.hasChildNode(xml, "alwaysRelativeE")) { alwaysRelativeE = Boolean.parseBoolean(XML.getChildNodeValue(xml, "alwaysRelativeE")); } if (XML.hasChildNode(xml, "hasEmergencyStop")) { hasEmergencyStop = Boolean.parseBoolean(XML.getChildNodeValue(xml, "hasEmergencyStop")); } if (XML.hasChildNode(xml, "hasSoftStop")) { hasSoftStop = Boolean.parseBoolean(XML.getChildNodeValue(xml, "hasSoftStop")); } if (XML.hasChildNode(xml, "introduceNoise")) { double introduceNoise = Double.parseDouble(XML.getChildNodeValue(xml, "introduceNoise")); if(introduceNoise != 0) { Base.logger.warning("Purposefully injecting noise into communications. This is NOT for production."); Base.logger.warning("Turn this off by removing introduceNoise from the machines XML file of your machine."); introduceNoiseEveryN = (int) (1/introduceNoise); } } } public void updateManualControl() { try { extrusionUpdater.update(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Send any gcode needed to synchronize the driver state and * the firmware state. Sent on startup and if we see "start" * indicating an uncommanded firmware reset. */ public void sendInitializationGcode(boolean synchronous) { sendCommand("M110", synchronous); // may be duplicate, that's ok // default us to absolute positioning sendCommand("G90", synchronous); sendCommand("G92 X0 Y0 Z0 E0", synchronous); } public synchronized void initialize() { // declare our serial guy. if (serial == null) { Base.logger.severe("No Serial Port found.\n"); return; } // wait till we're initialised if (!isInitialized()) { Base.logger.info("Initializing Serial."); flushBuffer(); if (pulseRTS) { Base.logger.fine("Resetting RepRap: Pulsing RTS.."); int retriesRemaining = waitForStartRetries+1; retryPulse: do { try { pulseRTS(); Base.logger.finer("start received"); break retryPulse; } catch (TimeoutException e) { retriesRemaining--; } if (retriesRemaining == 0) { this.disconnect(); Base.logger.warning("RepRap not responding to RTS reset. Failed to connect."); return; } else { Base.logger.warning("RepRap not responding to RTS reset. Trying again.."); } } while(true); Base.logger.fine("RepRap Reset. RTS pulsing complete."); } // Send a line # reset command, this allows us to catch the "ok" response. // If we get a "start" while trying this we'll go again. synchronized(okReceived) { okReceived.set(false); while (!okReceived.get()) { sendCommand("M110", false); Base.logger.info("GCode sent. waiting for response.."); try { waitForNotification(okReceived, 10000); } catch (RetryException e) { } catch (TimeoutException e) { this.disconnect(); Base.logger.warning("Firmware not responding to gcode. Failed to connect."); return; } } } Base.logger.fine("GCode response received. RepRap connected."); sendInitializationGcode(true); Base.logger.info("Ready."); this.setInitialized(true); } } private void waitForNotification(AtomicBoolean notifier, long timeout) throws TimeoutException, RetryException { //Wait for the RepRap to respond try { notifier.wait(timeout); } catch (InterruptedException e) { //Presumably we're shutting down Thread.currentThread().interrupt(); return; } if (notifier.get() == true) { return; } else { throw new RetryException(); } } private void pulseRTS() throws TimeoutException { // attempt to reset the device, this may slow down the connection time, but it // increases our chances of successfully connecting dramatically. Base.logger.info("Attempting to reset RepRap (pulsing RTS)"); synchronized (startReceived) { startReceived.set(false); serial.pulseRTSLow(); if (waitForStart == false) return; // Wait for the RepRap to respond to the RTS pulse attempt // or for this to timeout. while (!startReceived.get()) { try { waitForNotification(startReceived, waitForStartTimeout); } catch (RetryException e) { continue; } } } } public boolean isPassthroughDriver() { return true; } /** * Actually execute the GCode we just parsed. */ public void executeGCodeLine(String code) { //If we're not initialized (ie. disconnected) do not execute commands on the disconnected machine. if(!isInitialized()) return; // we *DONT* want to use the parents one, // as that will call all sorts of misc functions. // we'll simply pass it along. // super.execute(); sendCommand(code); } /** * Returns null or the first instance of the matching group */ private String getRegexMatch(String regex, String input, int group) { return getRegexMatch(Pattern.compile(regex), input, group); } private String getRegexMatch(Pattern regex, String input, int group) { Matcher matcher = regex.matcher(input); if (!matcher.find() || matcher.groupCount() < group) return null; return matcher.group(group); } /** * Actually sends command over serial. * * Commands sent here are acknowledged asynchronously in another * thread so as to increase our serial GCode throughput. * * Only one command can be sent at a time. If another command is * being sent this method will block until the previous command * is finished sending. */ protected void sendCommand(String next) { _sendCommand(next, true, false); } protected void sendCommand(String next, boolean synchronous) { _sendCommand(next, synchronous, false); } protected void resendCommand(String command) { synchronized (sendCommandLock) { numResends++; if(debugLevel > 0) Base.logger.warning("Resending: \"" + command + "\". Resends in "+ numResends + " of "+lineIterator+" lines."); _sendCommand(command, false, true); } } /** * inner method. not for use outside sendCommand and resendCommand */ protected void _sendCommand(String next, boolean synchronous, boolean resending) { // If this line is uncommented, it simply sends the next line instead of doing a retransmit! if (!resending) { sendCommandLock.lock(); //assert (isInitialized()); // System.out.println("sending: " + next); next = clean(next); next = fix(next); // make it compatible with older versions of the GCode interpeter // skip empty commands. if (next.length() == 0) { sendCommandLock.unlock(); return; } //update the current feedrate String feedrate = getRegexMatch("F(-[0-9\\.]+)", next, 1); if (feedrate!=null) this.feedrate.set(Double.parseDouble(feedrate)); if (!alwaysRelativeE) { //update the current extruder position String e = getRegexMatch("E([-0-9\\.]+)", next, 1); if (e!=null) this.ePosition.set(Double.parseDouble(e)); } else { ePosition.set(0.0); } // applychecksum replaces the line that was to be retransmitted, into the next line. if (hasChecksums) next = applyNandChecksum(next); Base.logger.finest("sending: "+next); } else { Base.logger.finest("resending: "+next); } // Block until we can fit the command on the Arduino /* synchronized(bufferLock) { //wait for the number of commands queued in the buffer to shrink before //adding the next command to it. // NOTE: must compute bufferSize from buffer elements now while(bufferSize + next.length() + 1 > maxBufferSize) { Base.logger.warning("reprap driver buffer full. gcode write slowed."); try { bufferLock.wait(); } catch (InterruptedException e1) { //Presumably we're shutting down Thread.currentThread().interrupt(); return; } } }*/ // debug... let us know whats up! if(debugLevel > 1) Base.logger.info("Sending: " + next); try { synchronized(next) { // do the actual send. serialInUse.lock(); bufferLock.lock(); // record it in our buffer tracker. buffer.addFirst(next); if((introduceNoiseEveryN != -1) && (lineIterator++) >= introduceNoiseEveryN) { Base.logger.info("Introducing noise (lineIterator==" + lineIterator + ",introduceNoiseEveryN=" + introduceNoiseEveryN + ")"); lineIterator = 0; String noisyNext = next.replace('6','7').replace('7','1') + "\n"; serial.write(noisyNext); } else { serial.write(next + "\n"); } bufferLock.unlock(); serialInUse.unlock(); // Synchronous gcode transfer. Waits for the 'ok' ack to be received. if (synchronous) next.wait(); } } catch (InterruptedException e1) { //Presumably we're shutting down Thread.currentThread().interrupt(); if (!resending) sendCommandLock.unlock(); return; } // Wait for the response (synchronous gcode transmission) //while(!isFinished()) {} if (!resending) sendCommandLock.unlock(); } public String clean(String str) { String clean = str; // trim whitespace clean = clean.trim(); // remove spaces //clean = clean.replaceAll(" ", ""); // remove all comments clean = RepRap5DDriver.gcodeCommentPattern.matcher(clean).replaceAll(""); return clean; } public String fix(String str) { String fixed = str; // The 5D firmware expects E codes for extrusion control instead of M101, M102, M103 Pattern r = Pattern.compile("M01[^0-9]"); Matcher m = r.matcher(fixed); if (m.find()) { return ""; } // Remove M10[123] codes // This piece of code causes problems?!? Restarts? r = Pattern.compile("M10[123](.*)"); m = r.matcher(fixed); if (m.find( )) { // System.out.println("Didn't find pattern in: " + str ); // fixed = m.group(1)+m.group(3)+";"; return ""; } // Reorder E and F codes? F-codes need to go LAST! //requires: import java.util.regex.Matcher; and import java.util.regex.Pattern; r = Pattern.compile("^(.*)(F[0-9\\.]*)\\s?E([0-9\\.]*)$"); m = r.matcher(fixed); if (m.find( )) { fixed = m.group(1)+" E"+m.group(3)+" "+m.group(2); } if(realtimeControl) { // Rescale F value r = Pattern.compile("(.*)F([0-9\\.]*)(.*)"); m = r.matcher(fixed); if (m.find( )) { double newvalue = Double.valueOf(m.group(2).trim()).doubleValue(); // FIXME: kind of an ugly way to test for extrusionless "travel" versus extrusion. if (!fixed.contains("E")) { newvalue *= rcTravelFeedrateMultiply; } else { newvalue *= rcFeedrateMultiply; } if(newvalue > rcFeedrateLimit) newvalue = rcFeedrateLimit; DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); NumberFormat formatter = new DecimalFormat("#0.0", dfs); fixed = m.group(1)+" F"+formatter.format(newvalue)+" "+m.group(3); } /* // Rescale E value r = Pattern.compile("(.*)E([0-9\\.]*)(.*)");//E317.52// Z-moves slower! Extrude 10% less? More and more rapid reversing m = r.matcher(fixed); if (m.find( )) { double newEvalue = Double.valueOf(m.group(2).trim()).doubleValue(); newEvalue = newEvalue * 0.040; DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance(); dfs.setDecimalSeparator('.'); NumberFormat formatter = new DecimalFormat("#0.0", dfs); fixed = m.group(1)+" E"+formatter.format(newEvalue)+" "+m.group(3); } */ } return fixed; // no change! } /** * takes a line of gcode and returns that gcode with a line number and checksum */ public String applyNandChecksum(String gcode) { // RepRap Syntax: N<linenumber> <cmd> *<chksum>\n if (gcode.contains("M110")) lineNumber.set(-1); Matcher lineNumberMatcher = gcodeLineNumberPattern.matcher(gcode); if (lineNumberMatcher.matches()) { // reset our line number to the specified one. this is usually a m110 line # reset lineNumber.set( Integer.parseInt( lineNumberMatcher.group(1) ) ); } else { // only add a line number if it is not already specified gcode = "N"+lineNumber.incrementAndGet()+' '+gcode+' '; } return applyChecksum(gcode); } public String applyChecksum(String gcode) { // chksum = 0 xor each byte of the gcode (including the line number and trailing space) byte checksum = 0; byte[] gcodeBytes = gcode.getBytes(); for (int i = 0; i<gcodeBytes.length; i++) { checksum = (byte) (checksum ^ gcodeBytes[i]); } return gcode+'*'+checksum; } public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } - r = Pattern.compile("^ok.*b:([0-9\\.]+)$"); + r = Pattern.compile("^ok.*b:([0-9\\.]+)"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); } public boolean isFinished() { return isBufferEmpty(); } /** * Clear the command buffer and send notifications to everyone * waiting for their completion. */ private void flushBuffer() { bufferLock.lock(); while (!buffer.isEmpty()) { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.fine("Flushing dead command: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); } /** * Is our buffer empty? If don't have a buffer, its always true. */ public boolean isBufferEmpty() { bufferLock.lock(); boolean isEmpty = buffer.isEmpty(); bufferLock.unlock(); return isEmpty; } /** * What is our queue size? Used by extrusion driver */ public int queueSize() { bufferLock.lock(); int queueSize = buffer.size(); bufferLock.unlock(); return queueSize; } private synchronized void disconnect() { bufferLock.lock(); flushBuffer(); closeSerial(); bufferLock.unlock(); } public synchronized void dispose() { bufferLock.lock(); flushBuffer(); super.dispose(); bufferLock.unlock(); } /*************************************************************************** * commands for interfacing with the driver directly * @throws RetryException **************************************************************************/ public void queuePoint(Point5d p) throws RetryException { String cmd = "G1 F" + df.format(getCurrentFeedrate()); sendCommand(cmd); cmd = "G1 X" + df.format(p.x()) + " Y" + df.format(p.y()) + " Z" + df.format(p.z()) + " F" + df.format(getCurrentFeedrate()); sendCommand(cmd); super.queuePoint(p); } public void setCurrentPosition(Point5d p) throws RetryException { sendCommand("G92 X" + df.format(p.x()) + " Y" + df.format(p.y()) + " Z" + df.format(p.z())); super.setCurrentPosition(p); } @Override public void homeAxes(EnumSet<AxisId> axes, boolean positive, double feedrate) throws RetryException { Base.logger.info("homing "+axes.toString()); StringBuffer buf = new StringBuffer("G28"); for (AxisId axis : axes) { buf.append(" "+axis+"0"); } sendCommand(buf.toString()); invalidatePosition(); super.homeAxes(axes,false,0); } public void delay(long millis) { int seconds = Math.round(millis / 1000); sendCommand("G4 P" + seconds); // no super call requried. } public void openClamp(int clampIndex) { sendCommand("M11 Q" + clampIndex); super.openClamp(clampIndex); } public void closeClamp(int clampIndex) { sendCommand("M10 Q" + clampIndex); super.closeClamp(clampIndex); } public void enableDrives() throws RetryException { sendCommand("M17"); super.enableDrives(); } public void disableDrives() throws RetryException { sendCommand("M18"); sendCommand("M84"); // Klimentkip super.disableDrives(); } public void changeGearRatio(int ratioIndex) { // gear ratio codes are M40-M46 int code = 40 + ratioIndex; code = Math.max(40, code); code = Math.min(46, code); sendCommand("M" + code); super.changeGearRatio(ratioIndex); } protected String _getToolCode() { return "T" + machine.currentTool().getIndex() + " "; } /*************************************************************************** * Motor interface functions * @throws RetryException **************************************************************************/ public void setMotorRPM(double rpm, int toolhead) throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M108 R" + df.format(rpm)); } else { extrusionUpdater.setFeedrate(rpm); } super.setMotorRPM(rpm, toolhead); } public void setMotorSpeedPWM(int pwm) throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M108 S" + df.format(pwm)); } super.setMotorSpeedPWM(pwm); } public synchronized void enableMotor() throws RetryException { String command = _getToolCode(); if (fiveD == false) { if (machine.currentTool().getMotorDirection() == ToolModel.MOTOR_CLOCKWISE) command += "M101"; else command += "M102"; sendCommand(command); } else { extrusionUpdater.setDirection( machine.currentTool().getMotorDirection()==1? Direction.forward : Direction.reverse ); extrusionUpdater.startExtruding(); } super.enableMotor(); } /** * Unified enable+delay+disable to allow us to use G1 E */ public synchronized void enableMotor(long millis) throws RetryException { if (fiveD == false) { super.enableMotor(millis); } else { super.enableMotor(); double feedrate = machine.currentTool().getMotorSpeedRPM(); double distance = millis * feedrate / 60 / 1000; if (machine.currentTool().getMotorDirection() != 1) { distance *= -1; } sendCommand(_getToolCode() + "G1 E" + (ePosition.get() + distance) + " F" + feedrate); super.disableMotor(); } } public void disableMotor() throws RetryException { if (fiveD == false) { sendCommand(_getToolCode() + "M103"); } else { extrusionUpdater.stopExtruding(); } super.disableMotor(); } /*************************************************************************** * Spindle interface functions * @throws RetryException **************************************************************************/ public void setSpindleRPM(double rpm) throws RetryException { sendCommand(_getToolCode() + "S" + df.format(rpm)); super.setSpindleRPM(rpm); } public void enableSpindle() throws RetryException { String command = _getToolCode(); if (machine.currentTool().getSpindleDirection() == ToolModel.MOTOR_CLOCKWISE) command += "M3"; else command += "M4"; sendCommand(command); super.enableSpindle(); } public void disableSpindle() throws RetryException { sendCommand(_getToolCode() + "M5"); super.disableSpindle(); } /*************************************************************************** * Temperature interface functions * @throws RetryException **************************************************************************/ public void setTemperature(double temperature) throws RetryException { sendCommand(_getToolCode() + "M104 S" + df.format(temperature)); super.setTemperature(temperature); } public void readTemperature() { sendCommand(_getToolCode() + "M105"); super.readTemperature(); } public double getPlatformTemperature(){ return machine.currentTool().getPlatformCurrentTemperature(); } public void setPlatformTemperature(double temperature) throws RetryException { sendCommand(_getToolCode() + "M140 S" + df.format(temperature)); super.setPlatformTemperature(temperature); } /*************************************************************************** * Flood Coolant interface functions **************************************************************************/ public void enableFloodCoolant() { sendCommand(_getToolCode() + "M7"); super.enableFloodCoolant(); } public void disableFloodCoolant() { sendCommand(_getToolCode() + "M9"); super.disableFloodCoolant(); } /*************************************************************************** * Mist Coolant interface functions **************************************************************************/ public void enableMistCoolant() { sendCommand(_getToolCode() + "M8"); super.enableMistCoolant(); } public void disableMistCoolant() { sendCommand(_getToolCode() + "M9"); super.disableMistCoolant(); } /*************************************************************************** * Fan interface functions * @throws RetryException **************************************************************************/ public void enableFan() throws RetryException { sendCommand(_getToolCode() + "M106"); super.enableFan(); } public void disableFan() throws RetryException { sendCommand(_getToolCode() + "M107"); super.disableFan(); } /*************************************************************************** * Valve interface functions * @throws RetryException **************************************************************************/ public void openValve() throws RetryException { sendCommand(_getToolCode() + "M126"); super.openValve(); } public void closeValve() throws RetryException { sendCommand(_getToolCode() + "M127"); super.closeValve(); } /*************************************************************************** * Collet interface functions **************************************************************************/ public void openCollet() { sendCommand(_getToolCode() + "M21"); super.openCollet(); } public void closeCollet() { sendCommand(_getToolCode() + "M22"); super.closeCollet(); } public void reset() { Base.logger.info("Reset."); setInitialized(false); initialize(); } public void stop(boolean abort) { // No implementation needed for synchronous machines. //sendCommand("M0"); // M0 is the same as emergency stop: will hang all communications. You don't really want that... invalidatePosition(); Base.logger.info("RepRap/Ultimaker Machine stop called."); } protected Point5d reconcilePosition() { sendCommand("M114"); // If the firmware returned a position then the reply parser // already set the current position. Return null to tell // caller not to touch the position if it is now known. // DO NOT RECURSE into getCurrentPosition() or this is an // infinite loop! return null; } /* =============== * This driver has real time control over feedrate and extrusion parameters, allowing real-time tuning! */ public boolean hasFeatureRealtimeControl() { Base.logger.info("Yes, I have a Realtime Control feature." ); return true; } public void enableRealtimeControl(boolean enable) { realtimeControl = enable; Base.logger.info("Realtime Control (RC) is: "+ realtimeControl ); } public double getExtrusionMultiplier() { return rcExtrusionMultiply; } public double getFeedrateMultiplier() { return rcFeedrateMultiply; } public double getTravelFeedrateMultiplier() { return rcTravelFeedrateMultiply; } public boolean setExtrusionMultiplier(double multiplier) { rcExtrusionMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x" ); return true; } public boolean setFeedrateMultiplier(double multiplier) { rcFeedrateMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x" ); return true; } public boolean setTravelFeedrateMultiplier(double multiplier) { rcTravelFeedrateMultiply = multiplier; if(debugLevel == 2) Base.logger.info("RC muplipliers: extrusion="+rcExtrusionMultiply+"x, feedrate="+rcFeedrateMultiply+"x, travel feedrate="+rcTravelFeedrateMultiply+"x" ); return true; } public void setDebugLevel(int level) { debugLevel = level; } public int getDebugLevel() { return debugLevel; } public double getFeedrateLimit() { return rcFeedrateLimit; } public boolean setFeedrateLimit(double limit) { rcFeedrateLimit = limit; return true; } }
true
true
public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } r = Pattern.compile("^ok.*b:([0-9\\.]+)$"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); }
public void serialByteReceivedEvent(ByteFifo fifo) { readResponseLock.lock(); serialInUse.lock(); byte[] response = fifo.dequeueLine(); int responseLength = response.length; serialInUse.unlock(); // 0 is now an acceptable value; it merely means that we timed out // waiting for input if (responseLength < 0) { // This signifies EOF. FIXME: How do we handle this? Base.logger.severe("SerialPassthroughDriver.readResponse(): EOF occured"); readResponseLock.unlock(); return; } else if(responseLength!=0) { String line; try { //convert to string and remove any trailing \r or \n's line = new String(response, 0, responseLength, "US-ASCII") .trim().toLowerCase(); } catch (UnsupportedEncodingException e) { Base.logger.severe("US-ASCII required. Terminating."); readResponseLock.unlock(); throw new RuntimeException(e); } //System.out.println("received: " + line); if(debugLevel > 1) Base.logger.info("<< " + line); if (line.length() == 0) Base.logger.fine("empty line received"); else if (line.startsWith("echo:")) { //if echo is turned on relay it to the user for debugging Base.logger.info(line); } else if (line.startsWith("ok t:")||line.startsWith("t:")) { Pattern r = Pattern.compile("t:([0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find( )) { String temp = m.group(1); machine.currentTool().setCurrentTemperature( Double.parseDouble(temp)); } r = Pattern.compile("^ok.*b:([0-9\\.]+)"); m = r.matcher(line); if (m.find( )) { String bedTemp = m.group(1); machine.currentTool().setPlatformCurrentTemperature( Double.parseDouble(bedTemp)); } } else if (line.startsWith("ok c:")||line.startsWith("c:")) { Pattern r = Pattern.compile("c: *x:?([-0-9\\.]+) *y:?([-0-9\\.]+) *z:?([-0-9\\.]+)"); Matcher m = r.matcher(line); if (m.find()) { double x = Double.parseDouble(m.group(1)); double y = Double.parseDouble(m.group(2)); double z = Double.parseDouble(m.group(3)); // super to avoid parroting back a G92 try { super.setCurrentPosition(new Point5d(x, y, z)); //Base.logger.fine("setting currentposition to:"+x+","+y+","+z+"."); } catch (RetryException e) { // do or do not, there is no retry } } } if (line.startsWith("ok")) { synchronized(okReceived) { okReceived.set(true); okReceived.notifyAll(); } bufferLock.lock(); //Notify the thread waitining in this gcode's sendCommand method that the gcode has been received. if (buffer.isEmpty()) { Base.logger.severe("Received OK with nothing queued!"); } else { String notifier = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("FW Accepted: " + notifier); synchronized(notifier) { notifier.notifyAll(); } } bufferLock.unlock(); synchronized(bufferLock) { /*let any sendCommand method waiting to send know that the buffer is now smaller and may be able to fit their command.*/ bufferLock.notifyAll(); } } // old arduino firmware sends "start" else if (line.contains("start")) { // Reset line number first in case gcode is sent below lineNumber.set(-1); boolean active = !buffer.isEmpty(); flushBuffer(); if (isInitialized()) { sendInitializationGcode(false); // If there were outstanding commands try to abort any print in progress. // This is a poor test: but do we know if we're printing at this level? // tried setInitialized(false); but that didn't work well if (active) { Base.logger.severe("Firmware reset with active commands!"); setError("Firmware reset with active commands!"); } } if (okAfterStart) { // firmware sends "ok" after start, put something here to consume it: bufferLock.lock(); buffer.addLast(";start-ok"); bufferLock.unlock(); } // todo: set version synchronized (startReceived) { startReceived.set(true); startReceived.notifyAll(); } // Wake up connect task to try again synchronized (okReceived) { okReceived.set(false); okReceived.notifyAll(); } } else if (line.startsWith("extruder fail")) { setError("Extruder failed: cannot extrude as this rate."); } else if (line.startsWith("resend:")||line.startsWith("rs ")) { // Bad checksum, resend requested Matcher badLineMatch = resendLinePattern.matcher(line); // Is it a Dud M or G code? String dudLetter = getRegexMatch("dud ([a-z]) code", line, 1); if (badLineMatch.find()) { int badLineNumber = Integer.parseInt( badLineMatch.group(1) ); if(debugLevel > 1) Base.logger.warning("Received resend request for line " + badLineNumber); Queue<String> resend = new LinkedList<String>(); boolean found = false; // Search backwards for the bad line in our buffer. // Firmware flushed everything after this line, so // build a queue of lines to resend. bufferLock.lock(); lineSearch: while (!buffer.isEmpty()) { String bufferedLine = buffer.removeLast(); if(debugLevel > 1) Base.logger.info("Searching: " + bufferedLine); int bufferedLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, bufferedLine.toLowerCase(), 1) ); if (dudLetter != null && bufferedLineNumber == badLineNumber) { Base.logger.info("Dud "+dudLetter+" code: Dropping " + bufferedLine); synchronized (bufferedLine) { bufferedLine.notifyAll(); } found = true; break lineSearch; } resend.add(bufferedLine); if (bufferedLineNumber == badLineNumber) { found = true; break lineSearch; } } if (okAfterResend) { // firmware sends "ok" after resend, put something here to consume it: buffer.addLast(";resend-ok"); } bufferLock.unlock(); if (!found) { int restartLineNumber = Integer.parseInt( getRegexMatch( gcodeLineNumberPattern, resend.element().toLowerCase(), 1) ); Base.logger.severe("resend for line " + badLineNumber + " not in our buffer. Resuming from " + restartLineNumber); this.resendCommand(applyChecksum("N"+(restartLineNumber-1)+" M110")); } // resend the lines while (!resend.isEmpty()) { String bufferedLine = resend.remove(); this.resendCommand(bufferedLine); } } else { // Malformed resend line request received. Resetting the line number Base.logger.warning("malformed line resend request, " +"resetting line number. Malformed Data: \n"+line); this.resendCommand(applyChecksum("N"+(lineNumber.get()-1)+" M110")); } } else if (line.startsWith("t:") || line.startsWith("c:")) { // temperature, position handled above } else { Base.logger.severe("Unknown: " + line); } } readResponseLock.unlock(); }
diff --git a/src/mozeq/irc/bot/plugins/BugzillaPlugin.java b/src/mozeq/irc/bot/plugins/BugzillaPlugin.java index 6f9deba..b058ba4 100644 --- a/src/mozeq/irc/bot/plugins/BugzillaPlugin.java +++ b/src/mozeq/irc/bot/plugins/BugzillaPlugin.java @@ -1,76 +1,76 @@ package mozeq.irc.bot.plugins; import java.net.MalformedURLException; import java.util.ArrayList; import mozeq.irc.bot.ConfigLoader; import mozeq.irc.bot.Configuration; import mozeq.irc.bot.IrcBotPlugin; import mozeq.irc.bot.IrcMessage; import org.apache.xmlrpc.XmlRpcException; import org.mozeq.bugzilla.BugzillaProxy; import org.mozeq.bugzilla.BugzillaTicket; public class BugzillaPlugin extends IrcBotPlugin { private String USERNAME = null; private String PASSWORD = null; private String BZ_URL = null; @Override public void init() { this.commands = new ArrayList<String>(); commands.add(".rhbz#\\d+"); Configuration conf = ConfigLoader.getConfiguration("bzplugin.conf"); if (conf != null) { USERNAME = conf.get("username"); PASSWORD = conf.get("password"); BZ_URL = conf.get("bz_url"); } } @Override public ArrayList<String> run(IrcMessage message, String command) { clearResponses(); - String[] params = message.body.split("#"); + String[] params = command.split("#"); if (params.length < 2) { System.err.println("Can't parse the ticket id from the message"); return responses; } BugzillaProxy bz = new BugzillaProxy(BZ_URL); try { bz.connect(USERNAME, PASSWORD); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int ticketID = 0; try { ticketID = parseNumberFromMsg(params[1]); } catch (NumberFormatException e) { //write this message to the irc? System.err.println("Can't parse number from: " + params[1]); //there is no reason to continue, so return.. } BugzillaTicket bzTicket = null; try { bzTicket = bz.getTicket(ticketID); } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bzTicket != null) { String ticketURL = bz.getURL() + "/show_bug.cgi?id=" + bzTicket.getID(); addResponse("bz#" + bzTicket.getID() + ": ["+ bzTicket.getComponent() +"] " + bzTicket.getSummary() + " <"+ ticketURL +">"); } return responses; } }
true
true
public ArrayList<String> run(IrcMessage message, String command) { clearResponses(); String[] params = message.body.split("#"); if (params.length < 2) { System.err.println("Can't parse the ticket id from the message"); return responses; } BugzillaProxy bz = new BugzillaProxy(BZ_URL); try { bz.connect(USERNAME, PASSWORD); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int ticketID = 0; try { ticketID = parseNumberFromMsg(params[1]); } catch (NumberFormatException e) { //write this message to the irc? System.err.println("Can't parse number from: " + params[1]); //there is no reason to continue, so return.. } BugzillaTicket bzTicket = null; try { bzTicket = bz.getTicket(ticketID); } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bzTicket != null) { String ticketURL = bz.getURL() + "/show_bug.cgi?id=" + bzTicket.getID(); addResponse("bz#" + bzTicket.getID() + ": ["+ bzTicket.getComponent() +"] " + bzTicket.getSummary() + " <"+ ticketURL +">"); } return responses; }
public ArrayList<String> run(IrcMessage message, String command) { clearResponses(); String[] params = command.split("#"); if (params.length < 2) { System.err.println("Can't parse the ticket id from the message"); return responses; } BugzillaProxy bz = new BugzillaProxy(BZ_URL); try { bz.connect(USERNAME, PASSWORD); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } int ticketID = 0; try { ticketID = parseNumberFromMsg(params[1]); } catch (NumberFormatException e) { //write this message to the irc? System.err.println("Can't parse number from: " + params[1]); //there is no reason to continue, so return.. } BugzillaTicket bzTicket = null; try { bzTicket = bz.getTicket(ticketID); } catch (XmlRpcException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (bzTicket != null) { String ticketURL = bz.getURL() + "/show_bug.cgi?id=" + bzTicket.getID(); addResponse("bz#" + bzTicket.getID() + ": ["+ bzTicket.getComponent() +"] " + bzTicket.getSummary() + " <"+ ticketURL +">"); } return responses; }
diff --git a/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java b/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java index 9b5d30532..eb693da0c 100644 --- a/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java +++ b/work-swing-impl/impl/src/main/java/org/cytoscape/work/internal/task/JDialogTaskManager.java @@ -1,276 +1,276 @@ package org.cytoscape.work.internal.task; import java.awt.Window; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import javax.swing.JDialog; import javax.swing.SwingUtilities; import org.cytoscape.work.AbstractTaskManager; import org.cytoscape.work.Task; import org.cytoscape.work.TaskFactory; import org.cytoscape.work.TaskIterator; import org.cytoscape.work.TunableRecorder; import org.cytoscape.work.internal.tunables.JDialogTunableMutator; import org.cytoscape.work.swing.DialogTaskManager; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Uses Swing components to create a user interface for the <code>Task</code>. * * This will not work if the application is running in headless mode. */ public class JDialogTaskManager extends AbstractTaskManager<JDialog,Window> implements DialogTaskManager { private static final Logger logger = LoggerFactory.getLogger(JDialogTaskManager.class); /** * The delay between the execution of the <code>Task</code> and * showing its task dialog. * * When a <code>Task</code> is executed, <code>JDialogTaskManager</code> * will not show its task dialog immediately. It will delay for a * period of time before showing the dialog. This way, short lived * <code>Task</code>s won't have a dialog box. */ static final long DELAY_BEFORE_SHOWING_DIALOG = 1; /** * The time unit of <code>DELAY_BEFORE_SHOWING_DIALOG</code>. */ static final TimeUnit DELAY_TIMEUNIT = TimeUnit.SECONDS; /** * Used for calling <code>Task.run()</code>. */ private ExecutorService taskExecutorService; /** * Used for opening dialogs after a specific amount of delay. */ private ScheduledExecutorService timedDialogExecutorService; /** * Used for calling <code>Task.cancel()</code>. * <code>Task.cancel()</code> must be called in a different * thread from the thread running Swing. This is done to * prevent Swing from freezing if <code>Task.cancel()</code> * takes too long to finish. * * This can be the same as <code>taskExecutorService</code>. */ private ExecutorService cancelExecutorService; // Parent component of Task Monitor GUI. private Window parent; private final JDialogTunableMutator dialogTunableMutator; /** * Construct with default behavior. * <ul> * <li><code>owner</code> is set to null.</li> * <li><code>taskExecutorService</code> is a cached thread pool.</li> * <li><code>timedExecutorService</code> is a single thread executor.</li> * <li><code>cancelExecutorService</code> is the same as <code>taskExecutorService</code>.</li> * </ul> */ public JDialogTaskManager(final JDialogTunableMutator tunableMutator) { super(tunableMutator); this.dialogTunableMutator = tunableMutator; parent = null; taskExecutorService = Executors.newCachedThreadPool(); addShutdownHook(taskExecutorService); timedDialogExecutorService = Executors.newSingleThreadScheduledExecutor(); addShutdownHook(timedDialogExecutorService); cancelExecutorService = taskExecutorService; } /** * Adds a shutdown hook to the JVM that shuts down an * <code>ExecutorService</code>. <code>ExecutorService</code>s * need to be told to shut down, otherwise the JVM won't * cleanly terminate. */ void addShutdownHook(final ExecutorService serviceToShutdown) { // Used to create a thread that is executed by the shutdown hook ThreadFactory threadFactory = Executors.defaultThreadFactory(); Runnable shutdownHook = new Runnable() { public void run() { serviceToShutdown.shutdownNow(); } }; Runtime.getRuntime().addShutdownHook(threadFactory.newThread(shutdownHook)); } /** * @param parent JDialogs created by this TaskManager will use this * to set the parent of the dialog. */ @Override public void setExecutionContext(final Window parent) { this.parent = parent; } @Override public JDialog getConfiguration(TaskFactory factory, Object tunableContext) { throw new UnsupportedOperationException("There is no configuration available for a DialogTaskManager"); } @Override public void execute(final TaskIterator iterator) { execute(iterator, null); } /** * For users of this class. */ public void execute(final TaskIterator taskIterator, Object tunableContext) { final SwingTaskMonitor taskMonitor = new SwingTaskMonitor(cancelExecutorService, parent); final Task first; try { dialogTunableMutator.setConfigurationContext(parent); if ( tunableContext != null && !displayTunables(tunableContext) ) { taskMonitor.cancel(); return; } taskMonitor.setExpectedNumTasks( taskIterator.getNumTasks() ); // Get the first task and display its tunables. This is a bit of a hack. // We do this outside of the thread so that the task monitor only gets // displayed AFTER the first tunables dialog gets displayed. first = taskIterator.next(); if (!displayTunables(first)) { taskMonitor.cancel(); return; } } catch (Exception exception) { logger.warn("Caught exception getting and validating task. ", exception); taskMonitor.showException(exception); return; } // create the task thread final Runnable tasks = new TaskThread(first, taskMonitor, taskIterator); // submit the task thread for execution final Future<?> executorFuture = taskExecutorService.submit(tasks); openTaskMonitorOnDelay(taskMonitor, executorFuture); } // This creates a thread on delay that conditionally displays the task monitor gui // if the task thread has not yet finished. private void openTaskMonitorOnDelay(final SwingTaskMonitor taskMonitor, final Future<?> executorFuture) { final Runnable timedOpen = new Runnable() { public void run() { if (!(executorFuture.isDone() || executorFuture.isCancelled())) { taskMonitor.setFuture(executorFuture); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (!taskMonitor.isClosed()) { taskMonitor.open(); } } }); } } }; timedDialogExecutorService.schedule(timedOpen, DELAY_BEFORE_SHOWING_DIALOG, DELAY_TIMEUNIT); } private class TaskThread implements Runnable { private final SwingTaskMonitor taskMonitor; private final TaskIterator taskIterator; private final Task first; TaskThread(final Task first, final SwingTaskMonitor tm, final TaskIterator ti) { this.first = first; this.taskMonitor = tm; this.taskIterator = ti; } public void run() { try { // actually run the first task // don't dispaly the tunables here - they were handled above. taskMonitor.setTask(first); first.run(taskMonitor); if (taskMonitor.cancelled()) return; // now execute all subsequent tasks while (taskIterator.hasNext()) { final Task task = taskIterator.next(); taskMonitor.setTask(task); // hide the dialog to avoid swing threading issues // while displaying tunables taskMonitor.showDialog(false); if (!displayTunables(task)) { taskMonitor.cancel(); return; } taskMonitor.showDialog(true); task.run(taskMonitor); if (taskMonitor.cancelled()) break; } - } catch (Exception exception) { + } catch (Throwable exception) { logger.warn("Caught exception executing task. ", exception); - taskMonitor.showException(exception); + taskMonitor.showException(new Exception(exception)); } // clean up the task monitor SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (taskMonitor.isOpened() && !taskMonitor.isShowingException()) taskMonitor.close(); } }); } } private boolean displayTunables(final Object task) throws Exception { if (task == null) { return true; } boolean ret = dialogTunableMutator.validateAndWriteBack(task); for ( TunableRecorder ti : tunableRecorders ) ti.recordTunableState(task); return ret; } }
false
true
public void run() { try { // actually run the first task // don't dispaly the tunables here - they were handled above. taskMonitor.setTask(first); first.run(taskMonitor); if (taskMonitor.cancelled()) return; // now execute all subsequent tasks while (taskIterator.hasNext()) { final Task task = taskIterator.next(); taskMonitor.setTask(task); // hide the dialog to avoid swing threading issues // while displaying tunables taskMonitor.showDialog(false); if (!displayTunables(task)) { taskMonitor.cancel(); return; } taskMonitor.showDialog(true); task.run(taskMonitor); if (taskMonitor.cancelled()) break; } } catch (Exception exception) { logger.warn("Caught exception executing task. ", exception); taskMonitor.showException(exception); } // clean up the task monitor SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (taskMonitor.isOpened() && !taskMonitor.isShowingException()) taskMonitor.close(); } }); }
public void run() { try { // actually run the first task // don't dispaly the tunables here - they were handled above. taskMonitor.setTask(first); first.run(taskMonitor); if (taskMonitor.cancelled()) return; // now execute all subsequent tasks while (taskIterator.hasNext()) { final Task task = taskIterator.next(); taskMonitor.setTask(task); // hide the dialog to avoid swing threading issues // while displaying tunables taskMonitor.showDialog(false); if (!displayTunables(task)) { taskMonitor.cancel(); return; } taskMonitor.showDialog(true); task.run(taskMonitor); if (taskMonitor.cancelled()) break; } } catch (Throwable exception) { logger.warn("Caught exception executing task. ", exception); taskMonitor.showException(new Exception(exception)); } // clean up the task monitor SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (taskMonitor.isOpened() && !taskMonitor.isShowingException()) taskMonitor.close(); } }); }
diff --git a/src/aiml/substitutions/DuplicateSubstitutionException.java b/src/aiml/substitutions/DuplicateSubstitutionException.java index 899b721..7915d65 100644 --- a/src/aiml/substitutions/DuplicateSubstitutionException.java +++ b/src/aiml/substitutions/DuplicateSubstitutionException.java @@ -1,33 +1,33 @@ /* jaiml - java AIML library Copyright (C) 2004, 2009 Kim Sullivan This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package aiml.substitutions; /** * This exception is thrown whenever a substitution with an identical pattern is * added to an instance of Substitutions. * * @author Kim Sullivan * */ public class DuplicateSubstitutionException extends Exception { public DuplicateSubstitutionException(String pattern, String replacement) { super( String.format( - "Substitution map already contains the replacement \"$s\" for the pattern \"%s\"", + "Substitution map already contains the replacement \"%s\" for the pattern \"%s\"", replacement, pattern)); } }
true
true
public DuplicateSubstitutionException(String pattern, String replacement) { super( String.format( "Substitution map already contains the replacement \"$s\" for the pattern \"%s\"", replacement, pattern)); }
public DuplicateSubstitutionException(String pattern, String replacement) { super( String.format( "Substitution map already contains the replacement \"%s\" for the pattern \"%s\"", replacement, pattern)); }
diff --git a/percolation/PercolationStats.java b/percolation/PercolationStats.java index a7e4fa1..8679f60 100644 --- a/percolation/PercolationStats.java +++ b/percolation/PercolationStats.java @@ -1,79 +1,79 @@ /** * Maria Pacana (mariapacana) * 10/8/2013 (Algorithms, Part I) * * The PercolationStats class runs Monte Carlo simulations on Percolation systems in order to determine the * "percolation threshold." */ public class PercolationStats { public double[] stats; //An array containing the percentage of open sites for each experiment. public int numExperiments; //Number of experiments being run. //Code for displaying stats (takes command-line args). public static void main(String[] args) { int N = Integer.parseInt(args[0]); int T = Integer.parseInt(args[1]); PercolationStats myStats = new PercolationStats(N,T); System.out.println("mean = "+myStats.mean()); System.out.println("stddev = "+myStats.stddev()); System.out.println("95% confidence interval = "+myStats.confidenceLo()+","+myStats.confidenceHi()); } //Confirms that input is valid. private void validNT(int N, int T) { if (N <= 0 || T <= 0) { throw new IndexOutOfBoundsException(); } } //Perform T independent computational experiments on an N-by-N grid. //Each experiment starts by generating a grid with all sites blocked. //Then, sites are chosen at random and opened until the system percolates. //We track the percentage of sites that are open when the system has percolated. public PercolationStats(int N, int T) { validNT(N,T); stats = new double[T]; numExperiments = T; for (int i=0; i<T; i++) { Percolation myPerc = new Percolation(N); float openSites = 0; while (!myPerc.percolates()) { int randX = StdRandom.uniform(N)+1; int randY = StdRandom.uniform(N)+1; if (!myPerc.isOpen(randX, randY)) { myPerc.open(randX, randY); openSites = openSites + 1; } } - stats[i] = openSites / N; + stats[i] = openSites / (N*N); } } //Sample mean of percolation threshold. public double mean() { return StdStats.mean(stats); } //Sample standard deviation of percolation threshold. public double stddev() { return StdStats.stddev(stats); } //Lower bound of the 95% confidence interval. public double confidenceLo() { return mean() - (1.96*stddev()/Math.pow(numExperiments,.5)); } //Upper bound of the 95% confidence interval. public double confidenceHi(){ return mean() + (1.96*stddev()/Math.pow(numExperiments,.5)); } }
true
true
public PercolationStats(int N, int T) { validNT(N,T); stats = new double[T]; numExperiments = T; for (int i=0; i<T; i++) { Percolation myPerc = new Percolation(N); float openSites = 0; while (!myPerc.percolates()) { int randX = StdRandom.uniform(N)+1; int randY = StdRandom.uniform(N)+1; if (!myPerc.isOpen(randX, randY)) { myPerc.open(randX, randY); openSites = openSites + 1; } } stats[i] = openSites / N; } }
public PercolationStats(int N, int T) { validNT(N,T); stats = new double[T]; numExperiments = T; for (int i=0; i<T; i++) { Percolation myPerc = new Percolation(N); float openSites = 0; while (!myPerc.percolates()) { int randX = StdRandom.uniform(N)+1; int randY = StdRandom.uniform(N)+1; if (!myPerc.isOpen(randX, randY)) { myPerc.open(randX, randY); openSites = openSites + 1; } } stats[i] = openSites / (N*N); } }
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BaseScope.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BaseScope.java index 8cad34cd..ea03bf68 100644 --- a/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BaseScope.java +++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/checks/usage/transmogrify/BaseScope.java @@ -1,97 +1,100 @@ // Transmogrify License // // Copyright (c) 2001, ThoughtWorks, Inc. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the ThoughtWorks, Inc. nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.puppycrawl.tools.checkstyle.checks.usage.transmogrify; /** * the bottom scope of the scope stack, contains some extra information * to make resolution easier. */ public class BaseScope extends DefaultScope { private SymbolTable table; public BaseScope( SymbolTable symbolTable ) { super("~BASE~", null, null); this.table = symbolTable; } public boolean isBaseScope() { return true; } public void addDefinition(IPackage def) { elements.put(def.getName(), def); } /** * gets the package associated with a fully qualified name * * @param fullyQualifiedName the name of the package * * @return the package that was gotten */ public IPackage getPackageDefinition(String fullyQualifiedName) { return (IPackage)(table.getPackages().get(fullyQualifiedName)); } public IClass getClassDefinition(String name) { IClass result = null; result = LiteralResolver.getDefinition(name); if (result == null) { int lastDot = name.lastIndexOf("."); if (lastDot > 0) { String packageName = name.substring(0, lastDot); String className = name.substring(lastDot + 1); IPackage pkg = getPackageDefinition(packageName); if (pkg != null) { result = pkg.getClass(className); } } } if (result == null) { Class theClass = null; try { theClass = ClassManager.getClassLoader().loadClass(name); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // no-op } + catch (NoClassDefFoundError e) { + // no-op, checkstyle bug 842781 + } } return result; } }
true
true
public IClass getClassDefinition(String name) { IClass result = null; result = LiteralResolver.getDefinition(name); if (result == null) { int lastDot = name.lastIndexOf("."); if (lastDot > 0) { String packageName = name.substring(0, lastDot); String className = name.substring(lastDot + 1); IPackage pkg = getPackageDefinition(packageName); if (pkg != null) { result = pkg.getClass(className); } } } if (result == null) { Class theClass = null; try { theClass = ClassManager.getClassLoader().loadClass(name); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // no-op } } return result; }
public IClass getClassDefinition(String name) { IClass result = null; result = LiteralResolver.getDefinition(name); if (result == null) { int lastDot = name.lastIndexOf("."); if (lastDot > 0) { String packageName = name.substring(0, lastDot); String className = name.substring(lastDot + 1); IPackage pkg = getPackageDefinition(packageName); if (pkg != null) { result = pkg.getClass(className); } } } if (result == null) { Class theClass = null; try { theClass = ClassManager.getClassLoader().loadClass(name); result = new ExternalClass(theClass); } catch (ClassNotFoundException e) { // no-op } catch (NoClassDefFoundError e) { // no-op, checkstyle bug 842781 } } return result; }
diff --git a/modules/amazon-ec2-provisioner/src/test/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerTest.java b/modules/amazon-ec2-provisioner/src/test/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerTest.java index ef1535cc..7e924227 100644 --- a/modules/amazon-ec2-provisioner/src/test/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerTest.java +++ b/modules/amazon-ec2-provisioner/src/test/java/com/elasticgrid/platforms/ec2/EC2CloudPlatformManagerTest.java @@ -1,92 +1,92 @@ /** * Elastic Grid * Copyright (C) 2008-2009 Elastic Grid, LLC. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.elasticgrid.platforms.ec2; import com.elasticgrid.model.ClusterAlreadyRunningException; import com.elasticgrid.model.ClusterException; import com.elasticgrid.model.NodeProfile; import com.elasticgrid.model.NodeProfileInfo; import com.elasticgrid.model.ec2.EC2Node; import com.elasticgrid.model.ec2.EC2NodeType; import com.elasticgrid.model.ec2.impl.EC2NodeImpl; import com.elasticgrid.platforms.ec2.discovery.EC2ClusterLocator; import com.elasticgrid.utils.amazon.AWSUtils; import com.elasticgrid.config.EC2Configuration; import org.easymock.EasyMock; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.rmi.RemoteException; import java.util.Arrays; import java.util.HashSet; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeoutException; import java.io.File; import java.io.IOException; public class EC2CloudPlatformManagerTest { private EC2CloudPlatformManager cloudPlatformManager; private EC2Instantiator mockEC2; private EC2ClusterLocator mockLocator; private Properties egProps; @Test(expectedExceptions = ClusterAlreadyRunningException.class) public void testStartingARunningGrid() throws ClusterException, ExecutionException, TimeoutException, InterruptedException, RemoteException { EasyMock.expect(mockLocator.findNodes("test")) .andReturn(null); EasyMock.expect(mockEC2.startInstances(null, 1, 1, Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid"), "CLUSTER_NAME=test,AWS_ACCESS_ID=null,AWS_SECRET_KEY=null," + "AWS_EC2_AMI32=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI32) + "," + "AWS_EC2_AMI64=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI64) + "," + "AWS_EC2_KEYPAIR=" + egProps.getProperty(EC2Configuration.AWS_EC2_KEYPAIR) + "," + "AWS_SQS_SECURED=true,DROP_BUCKET=" + egProps.getProperty(EC2Configuration.EG_DROP_BUCKET), - "eg-keypair", true, EC2NodeType.SMALL)) + egProps.getProperty(EC2Configuration.AWS_EC2_KEYPAIR), true, EC2NodeType.SMALL)) .andReturn(null); EasyMock.expect(mockEC2.getGroupsNames()) .andReturn(Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid")) .times(2); EasyMock.expect(mockLocator.findNodes("test")) .andReturn(new HashSet<EC2Node>(Arrays.asList(new EC2NodeImpl(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL).instanceID("123")))); EasyMock.replay(mockEC2); org.easymock.classextension.EasyMock.replay(mockLocator); NodeProfileInfo monitorAndAgentSmall = new NodeProfileInfo(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL, 1); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); } @BeforeTest @SuppressWarnings("unchecked") public void setUpClusterManager() throws IOException { cloudPlatformManager = new EC2CloudPlatformManager(); mockEC2 = EasyMock.createMock(EC2Instantiator.class); mockLocator = org.easymock.classextension.EasyMock.createMock(EC2ClusterLocator.class); cloudPlatformManager.setNodeInstantiator(mockEC2); cloudPlatformManager.setClusterLocator(mockLocator); egProps = AWSUtils.loadEC2Configuration(); } @AfterTest public void verifyMocks() { EasyMock.verify(mockEC2); org.easymock.classextension.EasyMock.verify(mockLocator); EasyMock.reset(mockEC2); org.easymock.classextension.EasyMock.reset(mockLocator); } }
true
true
public void testStartingARunningGrid() throws ClusterException, ExecutionException, TimeoutException, InterruptedException, RemoteException { EasyMock.expect(mockLocator.findNodes("test")) .andReturn(null); EasyMock.expect(mockEC2.startInstances(null, 1, 1, Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid"), "CLUSTER_NAME=test,AWS_ACCESS_ID=null,AWS_SECRET_KEY=null," + "AWS_EC2_AMI32=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI32) + "," + "AWS_EC2_AMI64=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI64) + "," + "AWS_EC2_KEYPAIR=" + egProps.getProperty(EC2Configuration.AWS_EC2_KEYPAIR) + "," + "AWS_SQS_SECURED=true,DROP_BUCKET=" + egProps.getProperty(EC2Configuration.EG_DROP_BUCKET), "eg-keypair", true, EC2NodeType.SMALL)) .andReturn(null); EasyMock.expect(mockEC2.getGroupsNames()) .andReturn(Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid")) .times(2); EasyMock.expect(mockLocator.findNodes("test")) .andReturn(new HashSet<EC2Node>(Arrays.asList(new EC2NodeImpl(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL).instanceID("123")))); EasyMock.replay(mockEC2); org.easymock.classextension.EasyMock.replay(mockLocator); NodeProfileInfo monitorAndAgentSmall = new NodeProfileInfo(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL, 1); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); }
public void testStartingARunningGrid() throws ClusterException, ExecutionException, TimeoutException, InterruptedException, RemoteException { EasyMock.expect(mockLocator.findNodes("test")) .andReturn(null); EasyMock.expect(mockEC2.startInstances(null, 1, 1, Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid"), "CLUSTER_NAME=test,AWS_ACCESS_ID=null,AWS_SECRET_KEY=null," + "AWS_EC2_AMI32=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI32) + "," + "AWS_EC2_AMI64=" + egProps.getProperty(EC2Configuration.AWS_EC2_AMI64) + "," + "AWS_EC2_KEYPAIR=" + egProps.getProperty(EC2Configuration.AWS_EC2_KEYPAIR) + "," + "AWS_SQS_SECURED=true,DROP_BUCKET=" + egProps.getProperty(EC2Configuration.EG_DROP_BUCKET), egProps.getProperty(EC2Configuration.AWS_EC2_KEYPAIR), true, EC2NodeType.SMALL)) .andReturn(null); EasyMock.expect(mockEC2.getGroupsNames()) .andReturn(Arrays.asList("elastic-grid-cluster-test", "eg-monitor", "eg-agent", "elastic-grid")) .times(2); EasyMock.expect(mockLocator.findNodes("test")) .andReturn(new HashSet<EC2Node>(Arrays.asList(new EC2NodeImpl(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL).instanceID("123")))); EasyMock.replay(mockEC2); org.easymock.classextension.EasyMock.replay(mockLocator); NodeProfileInfo monitorAndAgentSmall = new NodeProfileInfo(NodeProfile.MONITOR_AND_AGENT, EC2NodeType.SMALL, 1); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); cloudPlatformManager.startCluster("test", Arrays.asList(monitorAndAgentSmall)); }
diff --git a/src/net/erbros/lottery/LotteryGame.java b/src/net/erbros/lottery/LotteryGame.java index 8ae6877..837d311 100644 --- a/src/net/erbros/lottery/LotteryGame.java +++ b/src/net/erbros/lottery/LotteryGame.java @@ -1,472 +1,473 @@ package net.erbros.lottery; import java.io.*; import java.util.ArrayList; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import net.erbros.lottery.register.payment.Method; public class LotteryGame { final private Lottery plugin; final private LotteryConfig lConfig; public LotteryGame(final Lottery plugin) { this.plugin = plugin; lConfig = plugin.getLotteryConfig(); } public boolean addPlayer(final Player player, final int maxAmountOfTickets, final int numberOfTickets) { // Do the ticket cost money or item? if (lConfig.useiConomy()) { // Do the player have money? // First checking if the player got an account, if not let's create // it. plugin.Method.hasAccount(player.getName()); final Method.MethodAccount account = plugin.Method.getAccount(player.getName()); // And lets withdraw some money if (account.hasOver(lConfig.getCost() * numberOfTickets)) { // Removing coins from players account. account.subtract(lConfig.getCost() * numberOfTickets); } else { return false; } lConfig.debugMsg("taking " + (lConfig.getCost() * numberOfTickets) + "from account"); } else { // Do the user have the item if (player.getInventory().contains(lConfig.getMaterial(), (int)lConfig.getCost() * numberOfTickets)) { // Remove items. player.getInventory().removeItem( new ItemStack(lConfig.getMaterial(), (int)lConfig.getCost() * numberOfTickets)); } else { return false; } } // If the user paid, continue. Else we would already have sent return // false try { final BufferedWriter out = new BufferedWriter( new FileWriter(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt", true)); for (Integer i = 0; i < numberOfTickets; i++) { out.write(player.getName()); out.newLine(); } out.close(); } catch (IOException e) { } return true; } public Integer playerInList(final Player player) { int numberOfTickets = 0; try { final BufferedReader in = new BufferedReader( new FileReader(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt")); String str; while ((str = in.readLine()) != null) { if (str.equalsIgnoreCase(player.getName())) { numberOfTickets++; } } in.close(); } catch (IOException e) { } return numberOfTickets; } public ArrayList<String> playersInFile(final String file) { final ArrayList<String> players = new ArrayList<String>(); try { final BufferedReader in = new BufferedReader( new FileReader(plugin.getDataFolder() + File.separator + file)); String str; while ((str = in.readLine()) != null) { // add players to array. players.add(str); } in.close(); } catch (IOException e) { } return players; } public double winningAmount() { double amount = 0; final ArrayList<String> players = playersInFile("lotteryPlayers.txt"); amount = players.size() * Etc.formatAmount(lConfig.getCost(), lConfig.useiConomy()); lConfig.debugMsg("playerno: " + players.size() + " amount: " + amount); // Set the net payout as configured in the config. if (lConfig.getNetPayout() > 0) { amount = amount * lConfig.getNetPayout() / 100; } // Add extra money added by admins and mods? amount += lConfig.getExtraInPot(); // Any money in jackpot? lConfig.debugMsg("using config store: " + lConfig.getJackpot()); amount += lConfig.getJackpot(); // format it once again. amount = Etc.formatAmount(amount, lConfig.useiConomy()); return amount; } public int ticketsSold() { int sold; final ArrayList<String> players = playersInFile("lotteryPlayers.txt"); sold = players.size(); return sold; } public boolean removeFromClaimList(final Player player) { // Do the player have something to claim? final ArrayList<String> otherPlayersClaims = new ArrayList<String>(); final ArrayList<String> claimArray = new ArrayList<String>(); try { final BufferedReader in = new BufferedReader( new FileReader(plugin.getDataFolder() + File.separator + "lotteryClaim.txt")); String str; while ((str = in.readLine()) != null) { final String[] split = str.split(":"); if (split[0].equals(player.getName())) { // Adding this to player claim. claimArray.add(str); } else { otherPlayersClaims.add(str); } } in.close(); } catch (IOException e) { } // Did the user have any claims? if (claimArray.isEmpty()) { player.sendMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "You did not have anything unclaimed."); return false; } // Do a bit payout. for (int i = 0; i < claimArray.size(); i++) { final String[] split = claimArray.get(i).split(":"); final int claimAmount = Integer.parseInt(split[1]); final int claimMaterial = Integer.parseInt(split[2]); player.getInventory().addItem(new ItemStack(claimMaterial, claimAmount)); player.sendMessage("You just claimed " + claimAmount + " " + Etc.formatMaterialName(claimMaterial) + "."); } // Add the other players claims to the file again. try { final BufferedWriter out = new BufferedWriter( new FileWriter(plugin.getDataFolder() + File.separator + "lotteryClaim.txt")); for (int i = 0; i < otherPlayersClaims.size(); i++) { out.write(otherPlayersClaims.get(i)); out.newLine(); } out.close(); } catch (IOException e) { } return true; } public boolean addToClaimList(final String playerName, final int winningAmount, final int winningMaterial) { // Then first add new winner, and after that the old winners. try { final BufferedWriter out = new BufferedWriter( new FileWriter(plugin.getDataFolder() + File.separator + "lotteryClaim.txt", true)); out.write(playerName + ":" + winningAmount + ":" + winningMaterial); out.newLine(); out.close(); } catch (IOException e) { } return true; } public boolean addToWinnerList(final String playerName, final Double winningAmount, final int winningMaterial) { // This list should be 10 players long. final ArrayList<String> winnerArray = new ArrayList<String>(); try { final BufferedReader in = new BufferedReader( new FileReader(plugin.getDataFolder() + File.separator + "lotteryWinners.txt")); String str; while ((str = in.readLine()) != null) { winnerArray.add(str); } in.close(); } catch (IOException e) { } // Then first add new winner, and after that the old winners. try { final BufferedWriter out = new BufferedWriter( new FileWriter(plugin.getDataFolder() + File.separator + "lotteryWinners.txt")); out.write(playerName + ":" + winningAmount + ":" + winningMaterial); out.newLine(); // How long is the array? We just want the top 9. Removing index 9 // since its starting at 0. if (!winnerArray.isEmpty()) { if (winnerArray.size() > 9) { winnerArray.remove(9); } // Go trough list and output lines. for (int i = 0; i < winnerArray.size(); i++) { out.write(winnerArray.get(i)); out.newLine(); } } out.close(); } catch (IOException e) { } return true; } public long timeUntil() { final long nextDraw = lConfig.getNextexec(); final long timeLeft = ((nextDraw - System.currentTimeMillis()) / 1000); return timeLeft; } public String timeUntil(final boolean mini) { final long timeLeft = timeUntil(); // If negative number, just tell them its DRAW TIME! if (timeLeft < 0) { // Lets make it draw at once.. ;) plugin.startTimerSchedule(true); // And return some string to let the user know we are doing our best ;) if (mini) { return "Soon"; } return "Draw will occur soon!"; } return Etc.timeUntil(timeLeft, mini); } public boolean getWinner() { final ArrayList<String> players = playersInFile("lotteryPlayers.txt"); if (players.isEmpty()) { Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No tickets sold this round. Thats a shame."); return false; } else { // Find rand. Do minus 1 since its a zero based array. int rand = 0; // is max number of tickets 0? If not, include empty tickets not sold. if (lConfig.getTicketsAvailable() > 0 && ticketsSold() < lConfig.getTicketsAvailable()) { rand = new Random().nextInt(lConfig.getTicketsAvailable()); // If it wasn't a player winning, then do some stuff. If it was a player, just continue below. if (rand > players.size() - 1) { // No winner this time, pot goes on to jackpot! final double jackpot = winningAmount(); lConfig.setJackpot(jackpot); addToWinnerList("Jackpot", jackpot, lConfig.useiConomy() ? 0 : lConfig.getMaterial()); lConfig.setLastwinner("Jackpot"); lConfig.setLastwinneramount(jackpot); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No winner, we have a rollover! " + ChatColor.GREEN + ((lConfig.useiConomy()) ? plugin.Method.format( jackpot) : +jackpot + " " + Etc.formatMaterialName( lConfig.getMaterial())) + ChatColor.WHITE + " went to jackpot!"); clearAfterGettingWinner(); return true; } } else { // Else just continue rand = new Random().nextInt(players.size()); } lConfig.debugMsg("Rand: " + Integer.toString(rand)); double amount = winningAmount(); if (lConfig.useiConomy()) { plugin.Method.hasAccount(players.get(rand)); final Method.MethodAccount account = plugin.Method.getAccount(players.get(rand)); // Just make sure the account exists, or make it with default // value. // Add money to account. account.add(amount); // Announce the winner: Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + plugin.Method.format(amount) + "."); addToWinnerList(players.get(rand), amount, 0); } else { // let's throw it to an int. final int matAmount = (int)Etc.formatAmount(amount, lConfig.useiConomy()); amount = (double)matAmount; Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + matAmount + " " + Etc.formatMaterialName( lConfig.getMaterial()) + "."); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Use " + ChatColor.RED + "/lottery claim" + ChatColor.WHITE + " to claim the winnings."); addToWinnerList(players.get(rand), amount, lConfig.getMaterial()); addToClaimList(players.get(rand), matAmount, lConfig.getMaterial()); } Bukkit.broadcastMessage( - ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "There was in total " + Etc.realPlayersFromList( + ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "There was a total of " + Etc + .realPlayersFromList( players).size() + " " + Etc.pluralWording( "player", Etc.realPlayersFromList( players).size()) + " buying " + players.size() + " " + Etc.pluralWording( "ticket", players.size())); // Add last winner to config. lConfig.setLastwinner(players.get(rand)); lConfig.setLastwinneramount(amount); lConfig.setJackpot(0); clearAfterGettingWinner(); } return true; } public void clearAfterGettingWinner() { // extra money in pot added by admins and mods? // Should this be removed? if (lConfig.clearExtraInPot()) { lConfig.setExtraInPot(0); } // Clear file. try { final BufferedWriter out = new BufferedWriter( new FileWriter(plugin.getDataFolder() + File.separator + "lotteryPlayers.txt", false)); out.write(""); out.close(); } catch (IOException e) { } } public String formatCustomMessageLive(final String message, final Player player) { //Lets give timeLeft back if user provie %draw% String outMessage = message.replaceAll("%draw%", timeUntil(true)); //Lets give timeLeft with full words back if user provie %drawLong% outMessage = outMessage.replaceAll("%drawLong%", timeUntil(false)); // If %player% = Player name outMessage = outMessage.replaceAll("%player%", player.getDisplayName()); // %cost% = cost if (lConfig.useiConomy()) { outMessage = outMessage.replaceAll( "%cost%", String.valueOf( Etc.formatAmount(lConfig.getCost(), lConfig.useiConomy()))); } else { outMessage = outMessage.replaceAll( "%cost%", String.valueOf( (int)Etc.formatAmount(lConfig.getCost(), lConfig.useiConomy()))); } // %pot% outMessage = outMessage.replaceAll("%pot%", Double.toString(winningAmount())); // Lets get some colors on this, shall we? outMessage = outMessage.replaceAll("(&([a-f0-9]))", "\u00A7$2"); return outMessage; } }
true
true
public boolean getWinner() { final ArrayList<String> players = playersInFile("lotteryPlayers.txt"); if (players.isEmpty()) { Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No tickets sold this round. Thats a shame."); return false; } else { // Find rand. Do minus 1 since its a zero based array. int rand = 0; // is max number of tickets 0? If not, include empty tickets not sold. if (lConfig.getTicketsAvailable() > 0 && ticketsSold() < lConfig.getTicketsAvailable()) { rand = new Random().nextInt(lConfig.getTicketsAvailable()); // If it wasn't a player winning, then do some stuff. If it was a player, just continue below. if (rand > players.size() - 1) { // No winner this time, pot goes on to jackpot! final double jackpot = winningAmount(); lConfig.setJackpot(jackpot); addToWinnerList("Jackpot", jackpot, lConfig.useiConomy() ? 0 : lConfig.getMaterial()); lConfig.setLastwinner("Jackpot"); lConfig.setLastwinneramount(jackpot); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No winner, we have a rollover! " + ChatColor.GREEN + ((lConfig.useiConomy()) ? plugin.Method.format( jackpot) : +jackpot + " " + Etc.formatMaterialName( lConfig.getMaterial())) + ChatColor.WHITE + " went to jackpot!"); clearAfterGettingWinner(); return true; } } else { // Else just continue rand = new Random().nextInt(players.size()); } lConfig.debugMsg("Rand: " + Integer.toString(rand)); double amount = winningAmount(); if (lConfig.useiConomy()) { plugin.Method.hasAccount(players.get(rand)); final Method.MethodAccount account = plugin.Method.getAccount(players.get(rand)); // Just make sure the account exists, or make it with default // value. // Add money to account. account.add(amount); // Announce the winner: Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + plugin.Method.format(amount) + "."); addToWinnerList(players.get(rand), amount, 0); } else { // let's throw it to an int. final int matAmount = (int)Etc.formatAmount(amount, lConfig.useiConomy()); amount = (double)matAmount; Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + matAmount + " " + Etc.formatMaterialName( lConfig.getMaterial()) + "."); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Use " + ChatColor.RED + "/lottery claim" + ChatColor.WHITE + " to claim the winnings."); addToWinnerList(players.get(rand), amount, lConfig.getMaterial()); addToClaimList(players.get(rand), matAmount, lConfig.getMaterial()); } Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "There was in total " + Etc.realPlayersFromList( players).size() + " " + Etc.pluralWording( "player", Etc.realPlayersFromList( players).size()) + " buying " + players.size() + " " + Etc.pluralWording( "ticket", players.size())); // Add last winner to config. lConfig.setLastwinner(players.get(rand)); lConfig.setLastwinneramount(amount); lConfig.setJackpot(0); clearAfterGettingWinner(); } return true; }
public boolean getWinner() { final ArrayList<String> players = playersInFile("lotteryPlayers.txt"); if (players.isEmpty()) { Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No tickets sold this round. Thats a shame."); return false; } else { // Find rand. Do minus 1 since its a zero based array. int rand = 0; // is max number of tickets 0? If not, include empty tickets not sold. if (lConfig.getTicketsAvailable() > 0 && ticketsSold() < lConfig.getTicketsAvailable()) { rand = new Random().nextInt(lConfig.getTicketsAvailable()); // If it wasn't a player winning, then do some stuff. If it was a player, just continue below. if (rand > players.size() - 1) { // No winner this time, pot goes on to jackpot! final double jackpot = winningAmount(); lConfig.setJackpot(jackpot); addToWinnerList("Jackpot", jackpot, lConfig.useiConomy() ? 0 : lConfig.getMaterial()); lConfig.setLastwinner("Jackpot"); lConfig.setLastwinneramount(jackpot); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "No winner, we have a rollover! " + ChatColor.GREEN + ((lConfig.useiConomy()) ? plugin.Method.format( jackpot) : +jackpot + " " + Etc.formatMaterialName( lConfig.getMaterial())) + ChatColor.WHITE + " went to jackpot!"); clearAfterGettingWinner(); return true; } } else { // Else just continue rand = new Random().nextInt(players.size()); } lConfig.debugMsg("Rand: " + Integer.toString(rand)); double amount = winningAmount(); if (lConfig.useiConomy()) { plugin.Method.hasAccount(players.get(rand)); final Method.MethodAccount account = plugin.Method.getAccount(players.get(rand)); // Just make sure the account exists, or make it with default // value. // Add money to account. account.add(amount); // Announce the winner: Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + plugin.Method.format(amount) + "."); addToWinnerList(players.get(rand), amount, 0); } else { // let's throw it to an int. final int matAmount = (int)Etc.formatAmount(amount, lConfig.useiConomy()); amount = (double)matAmount; Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Congratulations to " + players.get( rand) + " for winning " + ChatColor.RED + matAmount + " " + Etc.formatMaterialName( lConfig.getMaterial()) + "."); Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "Use " + ChatColor.RED + "/lottery claim" + ChatColor.WHITE + " to claim the winnings."); addToWinnerList(players.get(rand), amount, lConfig.getMaterial()); addToClaimList(players.get(rand), matAmount, lConfig.getMaterial()); } Bukkit.broadcastMessage( ChatColor.GOLD + "[LOTTERY] " + ChatColor.WHITE + "There was a total of " + Etc .realPlayersFromList( players).size() + " " + Etc.pluralWording( "player", Etc.realPlayersFromList( players).size()) + " buying " + players.size() + " " + Etc.pluralWording( "ticket", players.size())); // Add last winner to config. lConfig.setLastwinner(players.get(rand)); lConfig.setLastwinneramount(amount); lConfig.setJackpot(0); clearAfterGettingWinner(); } return true; }
diff --git a/Java/BodyBuggBypass.java b/Java/BodyBuggBypass.java index 8f0b74e..9785749 100644 --- a/Java/BodyBuggBypass.java +++ b/Java/BodyBuggBypass.java @@ -1,61 +1,62 @@ package com.bypass; import com.bodymedia.common.applets.CommandException; import com.bodymedia.common.applets.device.util.LibraryException; import com.bodymedia.device.serial.SerialPort3; import com.bodymedia.device.usb.Usb; import com.bodymedia.common.applets.logger.Logger; import java.io.FileWriter; import java.io.IOException; import java.util.regex.Pattern; import java.util.regex.Matcher; public class BodyBuggBypass { public static void main(String[] args) throws CommandException, LibraryException, IOException { Logger log = Logger.getLogger(); log.setPriority(3); Usb usb = new Usb("bmusbapex5", Usb.ANY); String[] ports = usb.getArmbandPorts(); if(ports.length < 1) { System.out.println("No BodyBuggs detected."); System.exit(1); } else if(ports.length > 1) { System.out.println("Multiple BodyBuggs detected, re-run with only one connected."); System.exit(1); } String serialPort = ports[0]; SerialPort3 ser = new SerialPort3("bmcommapex5", serialPort); ser.setAddr(0x0000000E, 0xFFFFFFFF); ser.open(); ser.writeCommand("get lastdataupdate"); Pattern lastUpdateRegex = Pattern.compile("Last Data Update: ([0-9]+)"); Matcher matcher = lastUpdateRegex.matcher(ser.readResponse().toString()); matcher.find(); String lastUpdate = matcher.group(1); String logPath = String.format("%s.log", lastUpdate); System.out.printf("Writing data to: %s\n", logPath); FileWriter out = new FileWriter(logPath); - ser.writeCommand("retrieve P"); + ser.writeCommand("retrieve PDP"); out.write(ser.readResponse().toString()); out.close(); + System.out.println("Clearing device memory and updating timestamps."); ser.writeCommand("file init"); ser.writeCommand(String.format("set lastdataupdate %d", System.currentTimeMillis() / 1000L)); ser.writeCommand(String.format("set epoch %d", System.currentTimeMillis() / 1000L)); ser.close(); } }
false
true
public static void main(String[] args) throws CommandException, LibraryException, IOException { Logger log = Logger.getLogger(); log.setPriority(3); Usb usb = new Usb("bmusbapex5", Usb.ANY); String[] ports = usb.getArmbandPorts(); if(ports.length < 1) { System.out.println("No BodyBuggs detected."); System.exit(1); } else if(ports.length > 1) { System.out.println("Multiple BodyBuggs detected, re-run with only one connected."); System.exit(1); } String serialPort = ports[0]; SerialPort3 ser = new SerialPort3("bmcommapex5", serialPort); ser.setAddr(0x0000000E, 0xFFFFFFFF); ser.open(); ser.writeCommand("get lastdataupdate"); Pattern lastUpdateRegex = Pattern.compile("Last Data Update: ([0-9]+)"); Matcher matcher = lastUpdateRegex.matcher(ser.readResponse().toString()); matcher.find(); String lastUpdate = matcher.group(1); String logPath = String.format("%s.log", lastUpdate); System.out.printf("Writing data to: %s\n", logPath); FileWriter out = new FileWriter(logPath); ser.writeCommand("retrieve P"); out.write(ser.readResponse().toString()); out.close(); ser.writeCommand("file init"); ser.writeCommand(String.format("set lastdataupdate %d", System.currentTimeMillis() / 1000L)); ser.writeCommand(String.format("set epoch %d", System.currentTimeMillis() / 1000L)); ser.close(); }
public static void main(String[] args) throws CommandException, LibraryException, IOException { Logger log = Logger.getLogger(); log.setPriority(3); Usb usb = new Usb("bmusbapex5", Usb.ANY); String[] ports = usb.getArmbandPorts(); if(ports.length < 1) { System.out.println("No BodyBuggs detected."); System.exit(1); } else if(ports.length > 1) { System.out.println("Multiple BodyBuggs detected, re-run with only one connected."); System.exit(1); } String serialPort = ports[0]; SerialPort3 ser = new SerialPort3("bmcommapex5", serialPort); ser.setAddr(0x0000000E, 0xFFFFFFFF); ser.open(); ser.writeCommand("get lastdataupdate"); Pattern lastUpdateRegex = Pattern.compile("Last Data Update: ([0-9]+)"); Matcher matcher = lastUpdateRegex.matcher(ser.readResponse().toString()); matcher.find(); String lastUpdate = matcher.group(1); String logPath = String.format("%s.log", lastUpdate); System.out.printf("Writing data to: %s\n", logPath); FileWriter out = new FileWriter(logPath); ser.writeCommand("retrieve PDP"); out.write(ser.readResponse().toString()); out.close(); System.out.println("Clearing device memory and updating timestamps."); ser.writeCommand("file init"); ser.writeCommand(String.format("set lastdataupdate %d", System.currentTimeMillis() / 1000L)); ser.writeCommand(String.format("set epoch %d", System.currentTimeMillis() / 1000L)); ser.close(); }
diff --git a/crypto/src/org/bouncycastle/crypto/tls/TlsECKeyExchange.java b/crypto/src/org/bouncycastle/crypto/tls/TlsECKeyExchange.java index ebf1d503..0d4a2f51 100644 --- a/crypto/src/org/bouncycastle/crypto/tls/TlsECKeyExchange.java +++ b/crypto/src/org/bouncycastle/crypto/tls/TlsECKeyExchange.java @@ -1,207 +1,210 @@ package org.bouncycastle.crypto.tls; import java.io.IOException; import java.math.BigInteger; import org.bouncycastle.asn1.DERBitString; import org.bouncycastle.asn1.x509.KeyUsage; import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; import org.bouncycastle.asn1.x509.X509CertificateStructure; import org.bouncycastle.asn1.x509.X509Extension; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.Signer; import org.bouncycastle.crypto.agreement.ECDHBasicAgreement; import org.bouncycastle.crypto.generators.ECKeyPairGenerator; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ECDomainParameters; import org.bouncycastle.crypto.params.ECKeyGenerationParameters; import org.bouncycastle.crypto.params.ECPublicKeyParameters; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.crypto.util.PublicKeyFactory; import org.bouncycastle.math.ec.ECPoint; import org.bouncycastle.util.BigIntegers; /** * Base class for EC key exchange algorithms (see RFC 4492) */ abstract class TlsECKeyExchange implements TlsKeyExchange { protected TlsProtocolHandler handler; protected CertificateVerifyer verifyer; protected short keyExchange; protected TlsSigner tlsSigner; protected AsymmetricKeyParameter serverPublicKey; protected AsymmetricCipherKeyPair clientEphemeralKeyPair; protected ECPublicKeyParameters serverEphemeralPublicKey; protected Certificate clientCert; protected AsymmetricKeyParameter clientPrivateKey = null; TlsECKeyExchange(TlsProtocolHandler handler, CertificateVerifyer verifyer, short keyExchange, // TODO Replace with an interface e.g. TlsClientAuth Certificate clientCert, AsymmetricKeyParameter clientPrivateKey) { switch (keyExchange) { case KE_ECDHE_RSA: this.tlsSigner = new TlsRSASigner(); break; case KE_ECDHE_ECDSA: this.tlsSigner = new TlsECDSASigner(); break; case KE_ECDH_RSA: case KE_ECDH_ECDSA: case KE_ECDH_anon: this.tlsSigner = null; break; default: throw new IllegalArgumentException("unsupported key exchange algorithm"); } this.handler = handler; this.verifyer = verifyer; this.keyExchange = keyExchange; this.clientCert = clientCert; this.clientPrivateKey = clientPrivateKey; } public void skipServerCertificate() throws IOException { handler.failWithError(AlertLevel.fatal, AlertDescription.unexpected_message); } public void processServerCertificate(Certificate serverCertificate) throws IOException { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()? switch (this.keyExchange) { case KE_ECDH_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } - // TODO The algorithm used to sign the certificate should be DSS. + validateKeyUsage(x509Cert, KeyUsage.keyAgreement); + // TODO The algorithm used to sign the certificate should be ECDSA. // x509Cert.getSignatureAlgorithm(); break; case KE_ECDHE_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } - // TODO The algorithm used to sign the certificate should be RSA. -// x509Cert.getSignatureAlgorithm(); + validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case KE_ECDH_RSA: - if (!(this.serverPublicKey instanceof RSAKeyParameters)) + if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } - validateKeyUsage(x509Cert, KeyUsage.digitalSignature); + validateKeyUsage(x509Cert, KeyUsage.keyAgreement); + // TODO The algorithm used to sign the certificate should be RSA. +// x509Cert.getSignatureAlgorithm(); break; case KE_ECDHE_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } + validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case KE_ECDH_anon: // todo break; default: handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(AlertLevel.fatal, AlertDescription.user_canceled); } } AsymmetricCipherKeyPair generateECKeyPair(ECDomainParameters parameters) { ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator(); ECKeyGenerationParameters keyGenerationParameters = new ECKeyGenerationParameters( parameters, handler.getRandom()); keyPairGenerator.init(keyGenerationParameters); AsymmetricCipherKeyPair keyPair = keyPairGenerator.generateKeyPair(); return keyPair; } byte[] externalizeKey(ECPublicKeyParameters keyParameters) throws IOException { // TODO Potentially would like to be able to get the compressed encoding ECPoint ecPoint = keyParameters.getQ(); return ecPoint.getEncoded(); } byte[] calculateECDHEPreMasterSecret(ECPublicKeyParameters publicKey, CipherParameters privateKey) { ECDHBasicAgreement basicAgreement = new ECDHBasicAgreement(); basicAgreement.init(privateKey); BigInteger agreement = basicAgreement.calculateAgreement(publicKey); return BigIntegers.asUnsignedByteArray(agreement); } void validateKeyUsage(X509CertificateStructure c, int keyUsageBits) throws IOException { X509Extensions exts = c.getTBSCertificate().getExtensions(); if (exts != null) { X509Extension ext = exts.getExtension(X509Extensions.KeyUsage); if (ext != null) { DERBitString ku = KeyUsage.getInstance(ext); int bits = ku.getBytes()[0] & 0xff; if ((bits & keyUsageBits) != keyUsageBits) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } } } } Signer initSigner(TlsSigner tlsSigner, SecurityParameters securityParameters) { Signer signer = tlsSigner.createVerifyer(this.serverPublicKey); signer.update(securityParameters.clientRandom, 0, securityParameters.clientRandom.length); signer.update(securityParameters.serverRandom, 0, securityParameters.serverRandom.length); return signer; } }
false
true
public void processServerCertificate(Certificate serverCertificate) throws IOException { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()? switch (this.keyExchange) { case KE_ECDH_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } // TODO The algorithm used to sign the certificate should be DSS. // x509Cert.getSignatureAlgorithm(); break; case KE_ECDHE_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } // TODO The algorithm used to sign the certificate should be RSA. // x509Cert.getSignatureAlgorithm(); break; case KE_ECDH_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case KE_ECDHE_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } break; case KE_ECDH_anon: // todo break; default: handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(AlertLevel.fatal, AlertDescription.user_canceled); } }
public void processServerCertificate(Certificate serverCertificate) throws IOException { X509CertificateStructure x509Cert = serverCertificate.certs[0]; SubjectPublicKeyInfo keyInfo = x509Cert.getSubjectPublicKeyInfo(); try { this.serverPublicKey = PublicKeyFactory.createKey(keyInfo); } catch (RuntimeException e) { handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } // Sanity check the PublicKeyFactory if (this.serverPublicKey.isPrivate()) { handler.failWithError(AlertLevel.fatal, AlertDescription.internal_error); } // TODO /* * Perform various checks per RFC2246 7.4.2: "Unless otherwise specified, the * signing algorithm for the certificate must be the same as the algorithm for the * certificate key." */ // TODO Should the 'instanceof' tests be replaces with stricter checks on keyInfo.getAlgorithmId()? switch (this.keyExchange) { case KE_ECDH_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.keyAgreement); // TODO The algorithm used to sign the certificate should be ECDSA. // x509Cert.getSignatureAlgorithm(); break; case KE_ECDHE_ECDSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case KE_ECDH_RSA: if (!(this.serverPublicKey instanceof ECPublicKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.keyAgreement); // TODO The algorithm used to sign the certificate should be RSA. // x509Cert.getSignatureAlgorithm(); break; case KE_ECDHE_RSA: if (!(this.serverPublicKey instanceof RSAKeyParameters)) { handler.failWithError(AlertLevel.fatal, AlertDescription.certificate_unknown); } validateKeyUsage(x509Cert, KeyUsage.digitalSignature); break; case KE_ECDH_anon: // todo break; default: handler.failWithError(AlertLevel.fatal, AlertDescription.unsupported_certificate); } /* * Verify them. */ if (!this.verifyer.isValid(serverCertificate.getCerts())) { handler.failWithError(AlertLevel.fatal, AlertDescription.user_canceled); } }
diff --git a/src/AVLTree.java b/src/AVLTree.java index 3d15097..98f143f 100644 --- a/src/AVLTree.java +++ b/src/AVLTree.java @@ -1,656 +1,667 @@ import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Stack; /** * A AVLTree implementation class * @author risdenkj * */ public class AVLTree<T extends Comparable<? super T>> implements Iterable<T> { private AVLNode root; private int modCount = 0; private int rotationCount = 0; /** * Constructs a AVLTree * Sets the root to null */ public AVLTree() { root = null; } /** * Checks if the AVLTree has no nodes * * @return true if the AVLTree has no nodes; false if has nodes */ public boolean isEmpty() { return root == null ? true : false; } /** * Default iterator method returns the nodes in preorder * * @return an iterator to traverse the nodes in preorder */ public Iterator<T> iterator() { return new preOrderTreeIterator(root); } /** * Iterator that returns the nodes in inorder * * @return an iterator to traverse the nodes in inorder */ public Iterator<T> inOrderIterator() { return new inOrderTreeIterator(root); } /** * Iterator that returns the nodes in preorder * * @return an iterator to traverse the nodes in preorder */ public Iterator<T> preOrderIterator() { return new preOrderTreeIterator(root); } /** * Method that returns an ArrayList representation of the AVLTree * * @return ArrayList with the nodes in order */ public ArrayList<T> toArrayList() { if(root == null) { return new ArrayList<T>(); } return root.toArrayList(new ArrayList<T>()); } /** * Method that returns an Array representation of the AVLTree * * @return Array with the nodes in order */ public Object[] toArray() { return toArrayList().toArray(); } /** * Method to determine the height of the AVLTree * * @return height of the AVLTree; -1 if AVLTree is empty */ public int height(){ return !isEmpty() ? root.height() : -1; } /** * Method that returns a String representation of the AVLTree * * @return string in [element, element] format with the AVLTree AVLNodes in order */ public String toString() { String temp = ""; if(root == null) { return temp; } Iterator<T> i = iterator(); while(i.hasNext()) { temp += "[" + i.next() + "]"; if(i.hasNext()) { temp += ", "; } } return temp; } //TODO REMOVE public String toStringPre() { String temp = ""; if(root == null) { return temp; } Iterator<T> i = preOrderIterator(); while(i.hasNext()) { temp += "[" + i.next() + "]"; if(i.hasNext()) { temp += ", "; } } return temp; } /** * Method to determine the size of the AVLTree * * @return size of the AVLTree; 0 if AVLTree is empty */ public int size() { return !isEmpty() ? root.size() : 0; } /** * Returns a boolean value representing whether the tree was modified * or not. The item argument must be of the same type that was used * when initiating the AVLTree class. * * @param item the item to be inserted into the AVLTree * @return true if the tree was modified, false if not * @exception IllegalArgumentException if item is null */ public boolean insert(T item) { if(item == null) { throw new IllegalArgumentException(); } if(root != null) { return root.insert(item); } else { root = new AVLNode(item); modCount++; return true; } } /** * Removes the provided item from the AVLTree * * @param item the item that will be removed from the AVLTree * @return true if remove successful; false if not * @exception IllegalArgumentException if item is null */ public boolean remove(T item) { modWrapper mod = new modWrapper(); if(item == null) { throw new IllegalArgumentException(); } if(root != null) { root = root.remove(item, mod); } if(mod.getValue()) { modCount++; } return mod.getValue(); } /** * Method that gets the rotationCount of the AVLTree * * @return rotationCount The number of times the AVLTree has been rotated */ public int getRotationCount() { return rotationCount; } /** * Get method that returns a pointer to the item provided * * @param item item to be found in the AVLTree * @return pointer to item if found; null if not found * @exception IllegalArgumentException if item is null */ public T get(T item) { if(item == null) { throw new IllegalArgumentException(); } return root.get(item); } /** * A AVLNode Implementation Class * @author risdenkj * */ private class AVLNode { private T element; private AVLNode left; private AVLNode right; /** * Constructs a AVLNode * Sets the left and right children to null * * @param initelement The element that becomes the AVLNode */ public AVLNode(T initelement) { element = initelement; left = null; right = null; } /** * Returns the string representation of the current AVLNode * * @return string of the current AVLNode */ public String toString() { return element.toString(); } /** * Recursive method that returns an ArrayList of the AVLNode and its children * * @param list the ArrayList that elements should be added onto * @return ArrayList of the AVLNode and its children */ public ArrayList<T> toArrayList(ArrayList<T> list) { if(left != null) { left.toArrayList(list); } list.add(element); if(right != null) { right.toArrayList(list); } return list; } /** * Method that determines the height of the AVLNode * * @return height of the AVLNode */ public int height() { int leftheight = 0, rightheight = 0; if(left != null) { leftheight = 1 + left.height(); } if(right != null) { rightheight = 1 + right.height(); } if(leftheight > rightheight) { return leftheight; } else { return rightheight; } } /** * Method that determines the size of the AVLNode * * @return size of the AVLNode */ public int size() { int size = 1; if(left != null) { size += left.size(); } if(right != null) { size += right.size(); } return size; } /** * Inserts the provided element as a child to the AVLNode * The item becomes a left child if less than current AVLNode * The item becomes a right child if greater than current AVLNode * If the insert is successful adds 1 to the modCount * * @param item item to be inserted as a child to the AVLNode * @return true if insert successful; false if not */ public boolean insert(T item) { if(item.compareTo(element) < 0) { if(left != null) { boolean temp = left.insert(item); int rightheight = 0; if(right != null) { rightheight = right.height()+1; } if(left.height()+1 - rightheight == 2) { if(item.compareTo(left.element) < 0) { rotateRight(this); } else { rotateLeftRight(this); } } return temp; } else { left = new AVLNode(item); modCount++; return true; } } else if(item.compareTo(element) > 0) { if(right != null) { boolean temp = right.insert(item); int leftheight = 0; if(left != null) { leftheight = left.height()+1; } if(right.height()+1 - leftheight == 2) { if(item.compareTo(right.element) > 0) { rotateLeft(this); } else { rotateRightLeft(this); } } return temp; } else { right = new AVLNode(item); modCount++; return true; } } else { return false; } } /** * Removes the provided item from the AVLNode * In the event of the AVLNode having two children, the * algorithm finds the largest left child. * * @param item the item that will be removed from the AVLNode * @param mod ModWrapper boolean that will be set to true if remove successful * @return AVLNode that is removed */ public AVLNode remove(T item, modWrapper mod) { if(left == null && right == null) { if(item.compareTo(element) == 0) { mod.setTrue(); return null; } return this; } else if(right == null) { if(item.compareTo(element) < 0) { left = left.remove(item, mod); } mod.setTrue(); return left; } else if(left == null) { if(item.compareTo(element) > 0) { right = right.remove(item, mod); } mod.setTrue(); return right; } else { if(item.compareTo(element) > 0) { right = right.remove(item, mod); int rightheight = 0; if(right != null) { rightheight = right.height()+1; } if(left.height()+1 - rightheight == 2) { if(left.right == null) { rotateRight(this); } else { rotateLeftRight(this); } } } else if(item.compareTo(element) < 0) { left = left.remove(item, mod); int leftheight = 0; if(left != null) { leftheight = left.height()+1; } if(right.height()+1 - leftheight == 2) { if(right.left == null) { rotateLeft(this); } else { rotateRightLeft(this); } } } else { T temp = element; AVLNode largestChildNode = findLargestChild(left); element = largestChildNode.element; largestChildNode.element = temp; left = left.remove(temp, mod); + int leftheight = 0; + if(left != null) { + leftheight = left.height()+1; + } + if(right.height()+1 - leftheight == 2) { + if(right.left == null) { + rotateLeft(this); + } else { + rotateRightLeft(this); + } + } } return this; } } /** * Method that finds the largest left child * * @param node AVLNode to look for largest left child * @return the largest left child of the provided AVLNode */ public AVLNode findLargestChild(AVLNode node) { while(node.right != null) { node = node.right; } return node; } public AVLNode rotateRight(AVLNode node) { //System.out.println("rotateRight"); AVLNode temp1 = node.left; AVLNode temp2 = new AVLNode(node.element); temp2.right = node.right; temp2.left = temp1.right; node.left = temp1.left; node.element = temp1.element; node.right = temp2; rotationCount++; return node; } public AVLNode rotateRightLeft(AVLNode node) { System.out.println("rotateRightLeft"); rotateRight(node.right); rotateLeft(node); return node; } public AVLNode rotateLeft(AVLNode node) { //System.out.println("rotateRight"); AVLNode temp1 = node.right; AVLNode temp2 = new AVLNode(node.element); temp2.left = node.left; temp2.right = temp1.left; node.right = temp1.right; node.element = temp1.element; node.left = temp2; rotationCount++; return node; } public AVLNode rotateLeftRight(AVLNode node) { System.out.println("rotateLeftRight"); rotateLeft(node.left); rotateRight(node); return node; } /** * Get method that returns a pointer to the item provided * * @param item item to be found in the AVLNode * @return pointer to item if found; null if not found */ public T get(T item) { if(item.compareTo(element) > 0) { return right.get(item); } else if(item.compareTo(element) < 0) { return left.get(item); } else { return element; } } } /** * Creates a wrapper for the mod boolean * @author risdenkj * */ private class modWrapper { private boolean mod = false; public void setTrue() { this.mod = true; } public boolean getValue() { return mod; } } /** * A preorder AVLTree iterator implementation class * @author risdenkj * */ private class preOrderTreeIterator implements Iterator<T> { private Stack<AVLNode> list = new Stack<AVLNode>(); private AVLNode node = null; private int mod; /** * Constructs a preOrderTreeIterator * Sets the modification boolean flag to false * * @param node AVLNode to start the iterator from */ public preOrderTreeIterator(AVLNode node) { if(node != null) { list.push(node); this.mod = modCount; } } /** * Checks if there is another element in the AVLTree that hasn't been accessed * * @return true if there is another element to return; false if not */ public boolean hasNext() { return !list.empty(); } /** * Method that returns the next AVLNode element from the AVLTree * * @return AVLNode element in the AVLTree * @exception ConcurrentModificationException if the AVLTree was modified after initializing the iterator * @exception NoSuchElementException if there are no more elements to return */ public T next() { if(this.mod != modCount) { throw new ConcurrentModificationException(); } AVLNode item = null; if(!list.empty()) { item = list.pop(); } else { throw new NoSuchElementException(); } if(item.right != null) { list.push(item.right); } if(item.left != null) { list.push(item.left); } node = item; return item.element; } /** * Removes an element from the AVLTree * * @exception IllegalStateException if next() not called before */ public void remove() { if(node == null) { throw new IllegalStateException(); } if(AVLTree.this.remove(node.element)) { node = null; mod++; } } } /** * An in order AVLTree iterator implementation class * @author risdenkj * */ private class inOrderTreeIterator implements Iterator<T> { private Stack<AVLNode> list = new Stack<AVLNode>(); private AVLNode node = null; private int mod; /** * Constructs an inOrderTreeIterator * Sets the modification boolean flag to false * * @param node AVLNode to start the iterator from */ public inOrderTreeIterator(AVLNode node) { this.mod = modCount; checkLeft(node); } /** * Checks if there is another element in the AVLTree that hasn't been accessed * * @return true if there is another element to return; false if not */ public boolean hasNext() { return !list.empty(); } /** * Method that returns the next AVLNode element from the AVLTree * * @return AVLNode element in the AVLTree * @exception ConcurrentModificationException if the AVLTree was modified after initializing the iterator * @exception NoSuchElementException if there are no more elements to return */ public T next() { if(this.mod != modCount) { throw new ConcurrentModificationException(); } AVLNode item = null; if(list.empty()) { throw new NoSuchElementException(); } item = list.pop(); checkLeft(item.right); node = item; return item.element; } /** * Checks if the provided AVLNode has a left child * * @param node node to to check if it has a left child */ public void checkLeft(AVLNode node) { while(node != null) { list.push(node); node = node.left; } } /** * Removes an element from the AVLTree * * @exception IllegalStateException if next() not called before */ public void remove() { if(node == null) { throw new IllegalStateException(); } if(AVLTree.this.remove(node.element)) { node = null; mod++; } } } }
true
true
public AVLNode remove(T item, modWrapper mod) { if(left == null && right == null) { if(item.compareTo(element) == 0) { mod.setTrue(); return null; } return this; } else if(right == null) { if(item.compareTo(element) < 0) { left = left.remove(item, mod); } mod.setTrue(); return left; } else if(left == null) { if(item.compareTo(element) > 0) { right = right.remove(item, mod); } mod.setTrue(); return right; } else { if(item.compareTo(element) > 0) { right = right.remove(item, mod); int rightheight = 0; if(right != null) { rightheight = right.height()+1; } if(left.height()+1 - rightheight == 2) { if(left.right == null) { rotateRight(this); } else { rotateLeftRight(this); } } } else if(item.compareTo(element) < 0) { left = left.remove(item, mod); int leftheight = 0; if(left != null) { leftheight = left.height()+1; } if(right.height()+1 - leftheight == 2) { if(right.left == null) { rotateLeft(this); } else { rotateRightLeft(this); } } } else { T temp = element; AVLNode largestChildNode = findLargestChild(left); element = largestChildNode.element; largestChildNode.element = temp; left = left.remove(temp, mod); } return this; } }
public AVLNode remove(T item, modWrapper mod) { if(left == null && right == null) { if(item.compareTo(element) == 0) { mod.setTrue(); return null; } return this; } else if(right == null) { if(item.compareTo(element) < 0) { left = left.remove(item, mod); } mod.setTrue(); return left; } else if(left == null) { if(item.compareTo(element) > 0) { right = right.remove(item, mod); } mod.setTrue(); return right; } else { if(item.compareTo(element) > 0) { right = right.remove(item, mod); int rightheight = 0; if(right != null) { rightheight = right.height()+1; } if(left.height()+1 - rightheight == 2) { if(left.right == null) { rotateRight(this); } else { rotateLeftRight(this); } } } else if(item.compareTo(element) < 0) { left = left.remove(item, mod); int leftheight = 0; if(left != null) { leftheight = left.height()+1; } if(right.height()+1 - leftheight == 2) { if(right.left == null) { rotateLeft(this); } else { rotateRightLeft(this); } } } else { T temp = element; AVLNode largestChildNode = findLargestChild(left); element = largestChildNode.element; largestChildNode.element = temp; left = left.remove(temp, mod); int leftheight = 0; if(left != null) { leftheight = left.height()+1; } if(right.height()+1 - leftheight == 2) { if(right.left == null) { rotateLeft(this); } else { rotateRightLeft(this); } } } return this; } }
diff --git a/src/test/com/example/Main.java b/src/test/com/example/Main.java index 06bebdc..4fb30b3 100644 --- a/src/test/com/example/Main.java +++ b/src/test/com/example/Main.java @@ -1,42 +1,42 @@ package test.com.example; import net.csdn.common.settings.ImmutableSettings; import net.csdn.common.settings.InternalSettingsPreparer; import net.csdn.common.settings.Settings; import net.csdn.mongo.MongoMongo; import test.com.example.document.Blog; import java.io.InputStream; import static net.csdn.common.collections.WowCollections.map; /** * User: WilliamZhu * Date: 12-10-29 * Time: 下午5:01 */ public class Main { public static void main(String[] args) { //find the config file InputStream inputStream = Main.class.getResourceAsStream("application_for_test.yml"); Settings settings = InternalSettingsPreparer.simplePrepareSettings(ImmutableSettings.Builder.EMPTY_SETTINGS, inputStream); //configure MongoMongo try { - MongoMongo.CSDNMongoConfiguration csdnMongoConfiguration = new MongoMongo.CSDNMongoConfiguration("development", settings, Main.class.getClassLoader()); + MongoMongo.CSDNMongoConfiguration csdnMongoConfiguration = new MongoMongo.CSDNMongoConfiguration("development", settings, Main.class); MongoMongo.configure(csdnMongoConfiguration); } catch (Exception e) { e.printStackTrace(); } //now you can use it Blog blog = Blog.create(map("userName", "yes", "_id", 1000)); blog.save(); blog = Blog.findById(1000); System.out.println(blog.getUserName()); } }
true
true
public static void main(String[] args) { //find the config file InputStream inputStream = Main.class.getResourceAsStream("application_for_test.yml"); Settings settings = InternalSettingsPreparer.simplePrepareSettings(ImmutableSettings.Builder.EMPTY_SETTINGS, inputStream); //configure MongoMongo try { MongoMongo.CSDNMongoConfiguration csdnMongoConfiguration = new MongoMongo.CSDNMongoConfiguration("development", settings, Main.class.getClassLoader()); MongoMongo.configure(csdnMongoConfiguration); } catch (Exception e) { e.printStackTrace(); } //now you can use it Blog blog = Blog.create(map("userName", "yes", "_id", 1000)); blog.save(); blog = Blog.findById(1000); System.out.println(blog.getUserName()); }
public static void main(String[] args) { //find the config file InputStream inputStream = Main.class.getResourceAsStream("application_for_test.yml"); Settings settings = InternalSettingsPreparer.simplePrepareSettings(ImmutableSettings.Builder.EMPTY_SETTINGS, inputStream); //configure MongoMongo try { MongoMongo.CSDNMongoConfiguration csdnMongoConfiguration = new MongoMongo.CSDNMongoConfiguration("development", settings, Main.class); MongoMongo.configure(csdnMongoConfiguration); } catch (Exception e) { e.printStackTrace(); } //now you can use it Blog blog = Blog.create(map("userName", "yes", "_id", 1000)); blog.save(); blog = Blog.findById(1000); System.out.println(blog.getUserName()); }
diff --git a/src/nu/validator/htmlparser/impl/Tokenizer.java b/src/nu/validator/htmlparser/impl/Tokenizer.java index c5f1f4e..49f626f 100755 --- a/src/nu/validator/htmlparser/impl/Tokenizer.java +++ b/src/nu/validator/htmlparser/impl/Tokenizer.java @@ -1,4861 +1,4863 @@ /* * Copyright (c) 2005, 2006, 2007 Henri Sivonen * Copyright (c) 2007-2008 Mozilla Foundation * Portions of comments Copyright 2004-2007 Apple Computer, Inc., Mozilla * Foundation, and Opera Software ASA. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * The comments following this one that use the same comment syntax as this * comment are quotes from the WHATWG HTML 5 spec as of 2 June 2007 * amended as of June 18 2008. * That document came with this statement: * "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and * Opera Software ASA. You are granted a license to use, reproduce and * create derivative works of this document." */ package nu.validator.htmlparser.impl; import java.util.Arrays; import nu.validator.htmlparser.annotation.Local; import nu.validator.htmlparser.annotation.NoLength; import nu.validator.htmlparser.common.TokenHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import org.xml.sax.ErrorHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * An implementation of * http://www.whatwg.org/specs/web-apps/current-work/multipage/section-tokenisation.html * * This class implements the <code>Locator</code> interface. This is not an * incidental implementation detail: Users of this class are encouraged to make * use of the <code>Locator</code> nature. * * By default, the tokenizer may report data that XML 1.0 bans. The tokenizer * can be configured to treat these conditions as fatal or to coerce the infoset * to something that XML 1.0 allows. * * @version $Id$ * @author hsivonen */ public class Tokenizer implements Locator { private static final int DATA = 0; private static final int RCDATA = 1; private static final int CDATA = 2; private static final int PLAINTEXT = 3; private static final int TAG_OPEN = 49; private static final int CLOSE_TAG_OPEN_PCDATA = 50; private static final int TAG_NAME = 57; private static final int BEFORE_ATTRIBUTE_NAME = 4; private static final int ATTRIBUTE_NAME = 5; private static final int AFTER_ATTRIBUTE_NAME = 6; private static final int BEFORE_ATTRIBUTE_VALUE = 7; private static final int ATTRIBUTE_VALUE_DOUBLE_QUOTED = 8; private static final int ATTRIBUTE_VALUE_SINGLE_QUOTED = 9; private static final int ATTRIBUTE_VALUE_UNQUOTED = 10; private static final int AFTER_ATTRIBUTE_VALUE_QUOTED = 11; private static final int BOGUS_COMMENT = 12; private static final int MARKUP_DECLARATION_OPEN = 13; private static final int DOCTYPE = 14; private static final int BEFORE_DOCTYPE_NAME = 15; private static final int DOCTYPE_NAME = 16; private static final int AFTER_DOCTYPE_NAME = 17; private static final int BEFORE_DOCTYPE_PUBLIC_IDENTIFIER = 18; private static final int DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED = 19; private static final int DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED = 20; private static final int AFTER_DOCTYPE_PUBLIC_IDENTIFIER = 21; private static final int BEFORE_DOCTYPE_SYSTEM_IDENTIFIER = 22; private static final int DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED = 23; private static final int DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED = 24; private static final int AFTER_DOCTYPE_SYSTEM_IDENTIFIER = 25; private static final int BOGUS_DOCTYPE = 26; private static final int COMMENT_START = 27; private static final int COMMENT_START_DASH = 28; private static final int COMMENT = 29; private static final int COMMENT_END_DASH = 30; private static final int COMMENT_END = 31; private static final int CLOSE_TAG_OPEN_NOT_PCDATA = 32; private static final int MARKUP_DECLARATION_HYPHEN = 33; private static final int MARKUP_DECLARATION_OCTYPE = 34; private static final int DOCTYPE_UBLIC = 35; private static final int DOCTYPE_YSTEM = 36; private static final int CONSUME_CHARACTER_REFERENCE = 37; private static final int CONSUME_NCR = 38; private static final int CHARACTER_REFERENCE_LOOP = 39; private static final int HEX_NCR_LOOP = 41; private static final int DECIMAL_NRC_LOOP = 42; private static final int HANDLE_NCR_VALUE = 43; private static final int SELF_CLOSING_START_TAG = 44; private static final int CDATA_START = 45; private static final int CDATA_BLOCK = 46; private static final int CDATA_RSQB = 47; private static final int CDATA_RSQB_RSQB = 48; private static final int TAG_OPEN_NON_PCDATA = 51; private static final int ESCAPE_EXCLAMATION = 52; private static final int ESCAPE_EXCLAMATION_HYPHEN = 53; private static final int ESCAPE = 54; private static final int ESCAPE_HYPHEN = 55; private static final int ESCAPE_HYPHEN_HYPHEN = 56; /** * Magic value for UTF-16 operations. */ private static final int LEAD_OFFSET = 0xD800 - (0x10000 >> 10); /** * Magic value for UTF-16 operations. */ private static final int SURROGATE_OFFSET = 0x10000 - (0xD800 << 10) - 0xDC00; /** * UTF-16 code unit array containing less than and greater than for emitting * those characters on certain parse errors. */ private static final char[] LT_GT = { '<', '>' }; /** * UTF-16 code unit array containing less than and solidus for emitting * those characters on certain parse errors. */ private static final char[] LT_SOLIDUS = { '<', '/' }; /** * UTF-16 code unit array containing ]] for emitting those characters on * state transitions. */ private static final char[] RSQB_RSQB = { ']', ']' }; /** * Array version of U+FFFD. */ private static final char[] REPLACEMENT_CHARACTER = { '\uFFFD' }; /** * Array version of space. */ private static final char[] SPACE = { ' ' }; /** * Array version of line feed. */ private static final char[] LF = { '\n' }; /** * Buffer growth parameter. */ private static final int BUFFER_GROW_BY = 1024; /** * Lexically sorted void element names */ private static final String[] VOID_ELEMENTS = { "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param" }; /** * "CDATA[" as <code>char[]</code> */ private static final char[] CDATA_LSQB = "CDATA[".toCharArray(); /** * "octype" as <code>char[]</code> */ private static final char[] OCTYPE = "octype".toCharArray(); /** * "ublic" as <code>char[]</code> */ private static final char[] UBLIC = "ublic".toCharArray(); /** * "ystem" as <code>char[]</code> */ private static final char[] YSTEM = "ystem".toCharArray(); /** * The token handler. */ protected final TokenHandler tokenHandler; /** * The error handler. */ protected ErrorHandler errorHandler; /** * The previous <code>char</code> read from the buffer with infoset * alteration applied except for CR. Used for CRLF normalization and * surrogate pair checking. */ private char prev; /** * The current line number in the current resource being parsed. (First line * is 1.) Passed on as locator data. */ private int line; private int linePrev; /** * The current column number in the current resource being tokenized. (First * column is 1, counted by UTF-16 code units.) Passed on as locator data. */ private int col; private int colPrev; private boolean nextCharOnNewLine; private int stateSave; private int returnStateSave; private int index; private boolean forceQuirks; private char additional; private int entCol; private int lo; private int hi; private int candidate; private int strBufMark; private int prevValue; private int value; private boolean seenDigits; private int pos; private int end; private @NoLength char[] buf; private int cstart; /** * The SAX public id for the resource being tokenized. (Only passed to back * as part of locator data.) */ protected String publicId; /** * The SAX system id for the resource being tokenized. (Only passed to back * as part of locator data.) */ protected String systemId; /** * Buffer for short identifiers. */ private char[] strBuf = new char[64]; /** * Number of significant <code>char</code>s in <code>strBuf</code>. */ private int strBufLen = 0; /** * Buffer for long strings. */ private char[] longStrBuf = new char[1024]; /** * Number of significant <code>char</code>s in <code>longStrBuf</code>. */ private int longStrBufLen = 0; /** * If not U+0000, a pending code unit to be appended to * <code>longStrBuf</code>. */ private char longStrBufPending = '\u0000'; /** * The attribute holder. */ private HtmlAttributes attributes; /** * Buffer for expanding NCRs falling into the Basic Multilingual Plane. */ private final char[] bmpChar = new char[1]; /** * Buffer for expanding astral NCRs. */ private final char[] astralChar = new char[2]; /** * Keeps track of PUA warnings. */ private boolean alreadyWarnedAboutPrivateUseCharacters; /** * http://www.whatwg.org/specs/web-apps/current-work/#content2 */ private ContentModelFlag contentModelFlag = ContentModelFlag.PCDATA; /** * The element whose end tag closes the current CDATA or RCDATA element. */ private ElementName contentModelElement = null; /** * <code>true</code> if tokenizing an end tag */ private boolean endTag; /** * The current tag token name. */ private ElementName tagName = null; /** * The current attribute name. */ private AttributeName attributeName = null; /** * Whether comment tokens are emitted. */ private boolean wantsComments = false; /** * If <code>false</code>, <code>addAttribute*()</code> are no-ops. */ private boolean shouldAddAttributes; /** * <code>true</code> when HTML4-specific additional errors are requested. */ private boolean html4; /** * Used together with <code>nonAsciiProhibited</code>. */ protected boolean alreadyComplainedAboutNonAscii; /** * Whether the stream is past the first 512 bytes. */ private boolean metaBoundaryPassed; /** * The name of the current doctype token. */ private String doctypeName; /** * The public id of the current doctype token. */ private String publicIdentifier; /** * The system id of the current doctype token. */ private String systemIdentifier; /** * The policy for vertical tab and form feed. */ private XmlViolationPolicy contentSpacePolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for non-space non-XML characters. */ private XmlViolationPolicy contentNonXmlCharPolicy = XmlViolationPolicy.ALTER_INFOSET; /** * The policy for comments. */ private XmlViolationPolicy commentPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy xmlnsPolicy = XmlViolationPolicy.ALTER_INFOSET; private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET; private boolean html4ModeCompatibleWithXhtml1Schemata; private int mappingLangToXmlLang; private boolean shouldSuspend; protected Confidence confidence; /** * The constructor. * * @param tokenHandler * the handler for receiving tokens */ public Tokenizer(TokenHandler tokenHandler) { this.tokenHandler = tokenHandler; } /** * Returns the mappingLangToXmlLang. * * @return the mappingLangToXmlLang */ public boolean isMappingLangToXmlLang() { return mappingLangToXmlLang == AttributeName.HTML_LANG; } /** * Sets the mappingLangToXmlLang. * * @param mappingLangToXmlLang * the mappingLangToXmlLang to set */ public void setMappingLangToXmlLang(boolean mappingLangToXmlLang) { this.mappingLangToXmlLang = mappingLangToXmlLang ? AttributeName.HTML_LANG : AttributeName.HTML; } /** * Sets the error handler. * * @see org.xml.sax.XMLReader#setErrorHandler(org.xml.sax.ErrorHandler) */ public void setErrorHandler(ErrorHandler eh) { this.errorHandler = eh; setCharacterHandlerErrorHandler(eh); } protected void setCharacterHandlerErrorHandler(ErrorHandler eh) { } /** * Returns the commentPolicy. * * @return the commentPolicy */ public XmlViolationPolicy getCommentPolicy() { return commentPolicy; } /** * Sets the commentPolicy. * * @param commentPolicy * the commentPolicy to set */ public void setCommentPolicy(XmlViolationPolicy commentPolicy) { this.commentPolicy = commentPolicy; } /** * Returns the contentNonXmlCharPolicy. * * @return the contentNonXmlCharPolicy */ public XmlViolationPolicy getContentNonXmlCharPolicy() { return contentNonXmlCharPolicy; } /** * Sets the contentNonXmlCharPolicy. * * @param contentNonXmlCharPolicy * the contentNonXmlCharPolicy to set */ public void setContentNonXmlCharPolicy( XmlViolationPolicy contentNonXmlCharPolicy) { this.contentNonXmlCharPolicy = contentNonXmlCharPolicy; } /** * Returns the contentSpacePolicy. * * @return the contentSpacePolicy */ public XmlViolationPolicy getContentSpacePolicy() { return contentSpacePolicy; } /** * Sets the contentSpacePolicy. * * @param contentSpacePolicy * the contentSpacePolicy to set */ public void setContentSpacePolicy(XmlViolationPolicy contentSpacePolicy) { this.contentSpacePolicy = contentSpacePolicy; } /** * Sets the xmlnsPolicy. * * @param xmlnsPolicy * the xmlnsPolicy to set */ public void setXmlnsPolicy(XmlViolationPolicy xmlnsPolicy) { if (xmlnsPolicy == XmlViolationPolicy.FATAL) { throw new IllegalArgumentException("Can't use FATAL here."); } this.xmlnsPolicy = xmlnsPolicy; } public void setNamePolicy(XmlViolationPolicy namePolicy) { this.namePolicy = namePolicy; } /** * Sets the html4ModeCompatibleWithXhtml1Schemata. * * @param html4ModeCompatibleWithXhtml1Schemata * the html4ModeCompatibleWithXhtml1Schemata to set */ public void setHtml4ModeCompatibleWithXhtml1Schemata( boolean html4ModeCompatibleWithXhtml1Schemata) { this.html4ModeCompatibleWithXhtml1Schemata = html4ModeCompatibleWithXhtml1Schemata; } // For the token handler to call /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, @Local String contentModelElement) { this.contentModelFlag = contentModelFlag; this.contentModelElement = ElementName.elementNameByLocalName(contentModelElement); } /** * Sets the content model flag and the associated element name. * * @param contentModelFlag * the flag * @param contentModelElement * the element causing the flag to be set */ public void setContentModelFlag(ContentModelFlag contentModelFlag, ElementName contentModelElement) { this.contentModelFlag = contentModelFlag; this.contentModelElement = contentModelElement; } // start Locator impl /** * @see org.xml.sax.Locator#getPublicId() */ public String getPublicId() { return publicId; } /** * @see org.xml.sax.Locator#getSystemId() */ public String getSystemId() { return systemId; } /** * @see org.xml.sax.Locator#getLineNumber() */ public int getLineNumber() { if (line > 0) { return line; } else { return -1; } } /** * @see org.xml.sax.Locator#getColumnNumber() */ public int getColumnNumber() { if (col > 0) { return col; } else { return -1; } } // end Locator impl // end public API public void notifyAboutMetaBoundary() { metaBoundaryPassed = true; } void turnOnAdditionalHtml4Errors() { html4 = true; } HtmlAttributes newAttributes() { return new HtmlAttributes(mappingLangToXmlLang); } /** * Clears the smaller buffer. */ private void clearStrBuf() { strBufLen = 0; } /** * Appends to the smaller buffer. * * @param c * the UTF-16 code unit to append */ private void appendStrBuf(char c) { if (strBufLen == strBuf.length) { char[] newBuf = new char[strBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(strBuf, 0, newBuf, 0, strBuf.length); strBuf = newBuf; } strBuf[strBufLen++] = c; } /** * The smaller buffer as a String. * * @return the smaller buffer as a string */ private String strBufToString() { return StringUtil.stringFromBuffer(strBuf, strBufLen); } /** * Emits the smaller buffer as character tokens. * * @throws SAXException * if the token handler threw */ private void emitStrBuf() throws SAXException { if (strBufLen > 0) { tokenHandler.characters(strBuf, 0, strBufLen); } } /** * Clears the larger buffer. */ private void clearLongStrBuf() { longStrBufLen = 0; longStrBufPending = '\u0000'; } /** * Appends to the larger buffer. * * @param c * the UTF-16 code unit to append */ private void appendLongStrBuf(char c) { if (longStrBufLen == longStrBuf.length) { char[] newBuf = new char[longStrBuf.length + Tokenizer.BUFFER_GROW_BY]; System.arraycopy(longStrBuf, 0, newBuf, 0, longStrBuf.length); longStrBuf = newBuf; } longStrBuf[longStrBufLen++] = c; } /** * Appends to the larger buffer when it is used to buffer a comment. Checks * for two consecutive hyphens. * * @param c * the UTF-16 code unit to append * @throws SAXException */ private void appendToComment(char c) throws SAXException { if (longStrBufPending == '-' && c == '-') { if (commentPolicy == XmlViolationPolicy.FATAL) { fatal("This document is not mappable to XML 1.0 without data loss due to \u201C--\u201D in a comment."); } else { warn("This document is not mappable to XML 1.0 without data loss due to \u201C--\u201D in a comment."); if (wantsComments) { if (commentPolicy == XmlViolationPolicy.ALLOW) { appendLongStrBuf('-'); } else { appendLongStrBuf('-'); appendLongStrBuf(' '); } } longStrBufPending = '-'; } } else { if (longStrBufPending != '\u0000') { if (wantsComments) { appendLongStrBuf(longStrBufPending); } longStrBufPending = '\u0000'; } if (c == '-') { longStrBufPending = '-'; } else { if (wantsComments) { appendLongStrBuf(c); } } } } /** * Appends to the larger buffer. * * @param arr * the UTF-16 code units to append */ private void appendLongStrBuf(char[] arr) { for (int i = 0; i < arr.length; i++) { appendLongStrBuf(arr[i]); } } /** * Append the contents of the smaller buffer to the larger one. */ private void appendStrBufToLongStrBuf() { for (int i = 0; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } /** * The larger buffer as a string. * * @return the larger buffer as a string */ private String longStrBufToString() { if (longStrBufPending != '\u0000') { appendLongStrBuf(longStrBufPending); } return new String(longStrBuf, 0, longStrBufLen); } /** * Emits the current comment token. * * @throws SAXException */ private void emitComment() throws SAXException { if (wantsComments) { if (longStrBufPending != '\u0000') { appendLongStrBuf(longStrBufPending); } } tokenHandler.comment(longStrBuf, longStrBufLen); } private String toUPlusString(char c) { String hexString = Integer.toHexString(c); switch (hexString.length()) { case 1: return "U+000" + hexString; case 2: return "U+00" + hexString; case 3: return "U+0" + hexString; case 4: return "U+" + hexString; default: throw new RuntimeException("Unreachable."); } } /** * Emits a warning about private use characters if the warning has not been * emitted yet. * * @throws SAXException */ private void warnAboutPrivateUseChar() throws SAXException { if (!alreadyWarnedAboutPrivateUseCharacters) { warn("Document uses the Unicode Private Use Area(s), which should not be used in publicly exchanged documents. (Charmod C073)"); alreadyWarnedAboutPrivateUseCharacters = true; } } /** * Tells if the argument is a BMP PUA character. * * @param c * the UTF-16 code unit to check * @return <code>true</code> if PUA character */ private boolean isPrivateUse(char c) { return c >= '\uE000' && c <= '\uF8FF'; } /** * Tells if the argument is an astral PUA character. * * @param c * the code point to check * @return <code>true</code> if astral private use */ private boolean isAstralPrivateUse(int c) { return (c >= 0xF0000 && c <= 0xFFFFD) || (c >= 0x100000 && c <= 0x10FFFD); } /** * Tells if the argument is a non-character (works for BMP and astral). * * @param c * the code point to check * @return <code>true</code> if non-character */ private boolean isNonCharacter(int c) { return (c & 0xFFFE) == 0xFFFE; } /** * Flushes coalesced character tokens. * * @throws SAXException */ private void flushChars() throws SAXException { if (pos > cstart) { int currLine = line; int currCol = col; line = linePrev; col = colPrev; tokenHandler.characters(buf, cstart, pos - cstart); line = currLine; col = currCol; } cstart = Integer.MAX_VALUE; } /** * Reports an condition that would make the infoset incompatible with XML * 1.0 as fatal. * * @param message * the message * @throws SAXException * @throws SAXParseException */ protected void fatal(String message) throws SAXException { SAXParseException spe = new SAXParseException(message, this); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } /** * Reports a Parse Error. * * @param message * the message * @throws SAXException */ protected void err(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.error(spe); } /** * Reports a warning * * @param message * the message * @throws SAXException */ protected void warn(String message) throws SAXException { if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, this); errorHandler.warning(spe); } private boolean currentIsVoid() { return Arrays.binarySearch(Tokenizer.VOID_ELEMENTS, tagName) > -1; } /** * */ private void resetAttributes() { attributes = null; // XXX figure out reuse } private ElementName strBufToElementNameString() { return ElementName.elementNameByBuffer(strBuf, strBufLen); } private int emitCurrentTagToken(boolean selfClosing) throws SAXException { if (selfClosing && endTag) { err("Stray \u201C/\u201D at the end of an end tag."); } int rv = Tokenizer.DATA; HtmlAttributes attrs = (attributes == null ? HtmlAttributes.EMPTY_ATTRIBUTES : attributes); if (endTag) { /* * When an end tag token is emitted, the content model flag must be * switched to the PCDATA state. */ contentModelFlag = ContentModelFlag.PCDATA; if (attrs.getLength() != 0) { /* * When an end tag token is emitted with attributes, that is a * parse error. */ err("End tag had attributes."); } tokenHandler.endTag(tagName); } else { tokenHandler.startTag(tagName, attrs, selfClosing); switch (contentModelFlag) { case PCDATA: rv = Tokenizer.DATA; break; case CDATA: rv = Tokenizer.CDATA; break; case RCDATA: rv = Tokenizer.RCDATA; break; case PLAINTEXT: rv = Tokenizer.PLAINTEXT; } } return rv; } private void attributeNameComplete() throws SAXException { attributeName = AttributeName.nameByBuffer(strBuf, strBufLen, namePolicy != XmlViolationPolicy.ALLOW); // [NOCPP[ if (attributes == null) { attributes = newAttributes(); } // ]NOCPP] /* * When the user agent leaves the attribute name state (and before * emitting the tag token, if appropriate), the complete attribute's * name must be compared to the other attributes on the same token; if * there is already an attribute on the token with the exact same name, * then this is a parse error and the new attribute must be dropped, * along with the value that gets associated with it (if any). */ if (attributes.contains(attributeName)) { shouldAddAttributes = false; err("Duplicate attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D."); } else { shouldAddAttributes = true; // if (namePolicy == XmlViolationPolicy.ALLOW) { // shouldAddAttributes = true; // } else { // if (NCName.isNCName(attributeName)) { // shouldAddAttributes = true; // } else { // if (namePolicy == XmlViolationPolicy.FATAL) { // fatal("Attribute name \u201C" + attributeName // + "\u201D is not an NCName."); // } else { // shouldAddAttributes = false; // warn("Attribute name \u201C" // + attributeName // + "\u201D is not an NCName. Ignoring the attribute."); // } // } // } } } private void addAttributeWithoutValue() throws SAXException { if (metaBoundaryPassed && "charset".equals(attributeName) && "meta".equals(tagName)) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } if (shouldAddAttributes) { if (html4) { if (attributeName.isBoolean()) { if (html4ModeCompatibleWithXhtml1Schemata) { attributes.addAttribute(attributeName, attributeName.getLocal(AttributeName.HTML), xmlnsPolicy); } else { attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { err("Attribute value omitted for a non-boolean attribute. (HTML4-only error.)"); attributes.addAttribute(attributeName, "", xmlnsPolicy); } } else { if (AttributeName.SRC == attributeName || AttributeName.HREF == attributeName) { warn("Attribute \u201C" + attributeName.getLocal(AttributeName.HTML) + "\u201D without an explicit value seen. The attribute may be dropped by IE7."); } attributes.addAttribute(attributeName, "", xmlnsPolicy); } } } private void addAttributeWithValue() throws SAXException { if (metaBoundaryPassed && "meta" == tagName.name && "charset".equals(attributeName)) { err("A \u201Ccharset\u201D attribute on a \u201Cmeta\u201D element found after the first 512 bytes."); } if (shouldAddAttributes) { String value = longStrBufToString(); if (!endTag) { if (html4 && html4ModeCompatibleWithXhtml1Schemata && attributeName.isCaseFolded()) { value = StringUtil.toAsciiLowerCase(value); } } attributes.addAttribute(attributeName, value, xmlnsPolicy); } } public void start() throws SAXException { alreadyComplainedAboutNonAscii = false; contentModelFlag = ContentModelFlag.PCDATA; line = linePrev = 0; col = colPrev = 1; nextCharOnNewLine = true; prev = '\u0000'; html4 = false; alreadyWarnedAboutPrivateUseCharacters = false; metaBoundaryPassed = false; tokenHandler.startTokenization(this); wantsComments = tokenHandler.wantsComments(); switch (contentModelFlag) { case PCDATA: stateSave = Tokenizer.DATA; break; case CDATA: stateSave = Tokenizer.CDATA; break; case RCDATA: stateSave = Tokenizer.RCDATA; break; case PLAINTEXT: stateSave = Tokenizer.PLAINTEXT; } index = 0; forceQuirks = false; additional = '\u0000'; entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; prevValue = -1; value = 0; seenDigits = false; shouldSuspend = false; } public boolean tokenizeBuffer(UTF16Buffer buffer) throws SAXException { buf = buffer.getBuffer(); int state = stateSave; int returnState = returnStateSave; char c = '\u0000'; shouldSuspend = false; int start = buffer.getStart(); /** * The index of the last <code>char</code> read from <code>buf</code>. */ pos = start - 1; /** * The index of the first <code>char</code> in <code>buf</code> that * is part of a coalesced run of character tokens or * <code>Integer.MAX_VALUE</code> if there is not a current run being * coalesced. */ switch (state) { case DATA: case RCDATA: case CDATA: case PLAINTEXT: case CDATA_BLOCK: case ESCAPE: case ESCAPE_EXCLAMATION: case ESCAPE_EXCLAMATION_HYPHEN: case ESCAPE_HYPHEN: case ESCAPE_HYPHEN_HYPHEN: cstart = start; break; default: cstart = Integer.MAX_VALUE; break; } /** * The number of <code>char</code>s in <code>buf</code> that have * meaning. (The rest of the array is garbage and should not be * examined.) */ end = buffer.getEnd(); boolean reconsume = false; stateLoop(state, c, reconsume, returnState); if (pos == end) { // exiting due to end of buffer buffer.setStart(pos); } else { buffer.setStart(pos + 1); } if (prev == '\r') { prev = ' '; return true; } else { return false; } } // WARNING When editing this, makes sure the bytecode length shown by javap // stays under 8000 bytes! private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case PLAINTEXT: plaintextloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBuf(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } // XXX reorder point case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapehyphenloop; // FALL THRU continue // stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case DATA: dataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: c = read(); if (c == '\u0000') { break stateloop; } /* * The behavior of this state depends on the content model * flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ if (c == '!') { /* * U+0021 EXCLAMATION MARK (!) Switch to the markup * declaration open state. */ clearLongStrBuf(); state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; } else if (c == '/') { /* * U+002F SOLIDUS (/) Switch to the close tag open * state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; } else if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBuf(); appendStrBuf((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBuf(); appendStrBuf(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c == '>') { /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token and a * U+003E GREATER-THAN SIGN character token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else if (c == '?') { /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } else { /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokeniser (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM * FEED (FF) + U+0020 SPACE + U+003E GREATER-THAN SIGN * (>) + U+002F SOLIDUS (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.name.length()) { char e = contentModelElement.name.charAt(index); char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { if (html4) { if (!"iframe".equals(contentModelElement)) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C * FORM FEED (FF) U+0020 SPACE Switch to the * before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = Tokenizer.DATA; continue stateloop; } } } case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ appendStrBuf((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the input character, */ appendStrBuf(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } case TAG_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } case BEFORE_ATTRIBUTE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after * attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after attribute * name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case BEFORE_ATTRIBUTE_VALUE: for (;;) { c = read(); // ASSERT! call clearLongStrBuf() before transitioning // to this state! /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } case ATTRIBUTE_VALUE_DOUBLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the additional * allowed character being U+0022 QUOTATION MARK * ("). */ additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_SINGLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the + additional * allowed character being U+0027 APOSTROPHE * ('). */ additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with no + additional * allowed character. */ additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } case AFTER_ATTRIBUTE_VALUE_QUOTED: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current tag * token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case BOGUS_COMMENT: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to the first U+003E * GREATER-THAN SIGN character (>) or the end of the * file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the last * consumed character before the U+003E character, if * any, or up to the end of the file otherwise. (If the * comment was started by the end of the file (EOF), the * token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(); cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: appendToComment(c); continue; } } case MARKUP_DECLARATION_OPEN: c = read(); // ASSERT! call clearLongStrBuf() before coming here! /* * (This can only happen if the content model flag is set to * the PCDATA state.) * * If the next two characters are both U+002D HYPHEN-MINUS * (-) characters, consume those two characters, create a * comment token whose data is the empty string, and switch * to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE state. * * Otherwise, if the insertion mode is "in foreign content" * and the current node is not an element in the HTML * namespace and the next seven characters are a * case-sensitive match for the string "[CDATA[" (the five * uppercase letters "CDATA" with a U+005B LEFT SQUARE * BRACKET character before and after), then consume those * characters and switch to the CDATA block state (which is * unrelated to the content model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, if * any, is the first character that will be in the comment. */ switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.MARKUP_DECLARATION_HYPHEN; continue stateloop; case 'd': case 'D': appendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { appendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.COMMENT_START; continue stateloop; default: err("Bogus comment."); appendToComment('-'); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_OCTYPE: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.OCTYPE.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; continue stateloop; } } case COMMENT_START: c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to the * comment token's data. */ appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ state = Tokenizer.COMMENT_END_DASH; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendToComment(c); /* * Stay in the comment state. */ continue; } } case COMMENT_END_DASH: c = read(); /* * Comment end dash state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ appendToComment('-'); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ appendToComment('-'); appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } case DOCTYPE: if (!reconsume) { c = read(); } reconsume = false; systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before DOCTYPE name * state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ clearStrBuf(); /* * Set the token's name name to the current * input character. */ appendStrBuf(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; continue stateloop; } } case DOCTYPE_NAME: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after DOCTYPE * name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } case AFTER_DOCTYPE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_UBLIC: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < Tokenizer.UBLIC.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; continue stateloop; } } case DOCTYPE_YSTEM: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before DOCTYPE * system identifier state. */ if (index < Tokenizer.YSTEM.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * system identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ forceQuirks = false; state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BOGUS_DOCTYPE: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.CDATA_LSQB.length) { if (c == Tokenizer.CDATA_LSQB[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_BLOCK; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_BLOCK: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the character reference * fails. */ clearStrBuf(); appendStrBuf('&'); /* * This section defines how to consume a character reference. This * definition is used when parsing character references in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; - cstart = pos + 1; + if ((returnState & (~1)) == 0) { + cstart = pos + 1; + } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } } } flushChars(); if (prev == '\r') { pos--; } // Save locals stateSave = state; returnStateSave = returnState; } private void emitOrAppendStrBuf(int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendStrBufToLongStrBuf(); } else { emitStrBuf(); } } private void handleNcrValue(int returnState) throws SAXException { /* * If one or more characters match the range, then take them all and * interpret the string of characters as a number (either hexadecimal or * decimal as appropriate). */ if (value >= 0x80 && value <= 0x9f) { /* * If that number is one of the numbers in the first column of the * following table, then this is a parse error. */ err("A numeric character reference expanded to the C1 controls range."); /* * Find the row with that number in the first column, and return a * character token for the Unicode character given in the second * column of that row. */ char[] val = NamedCharacters.WINDOWS_1252[value - 0x80]; emitOrAppend(val, returnState); } else if (value == 0x0D) { err("A numeric character reference expanded to carriage return."); emitOrAppend(Tokenizer.LF, returnState); } else if (value == 0xC && contentSpacePolicy != XmlViolationPolicy.ALLOW) { if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) { emitOrAppend(Tokenizer.SPACE, returnState); } else if (contentSpacePolicy == XmlViolationPolicy.FATAL) { fatal("A character reference expanded to a form feed which is not legal XML 1.0 white space."); } } else if (value == 0xB && contentNonXmlCharPolicy != XmlViolationPolicy.ALLOW) { if (contentSpacePolicy == XmlViolationPolicy.ALTER_INFOSET) { emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (contentSpacePolicy == XmlViolationPolicy.FATAL) { fatal("A character reference expanded to a vtab which is not a legal XML 1.0 character."); } } else if ((value >= 0x0000 && value <= 0x0008) || (value >= 0x000E && value <= 0x001F) || value == 0x007F) { /* * Otherwise, if the number is in the range 0x0000 to 0x0008, 0x000E * to 0x001F, 0x007F to 0x009F, 0xD800 to 0xDFFF , 0xFDD0 to 0xFDDF, * or is one of 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, * 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, * 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, * 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, * 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, or * 0x10FFFF, or is higher than 0x10FFFF, then this is a parse error; * return a character token for the U+FFFD REPLACEMENT CHARACTER * character instead. */ err("Character reference expands to a control character (" + toUPlusString((char) value) + ")."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if ((value & 0xF800) == 0xD800) { err("Character reference expands to a surrogate."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (isNonCharacter(value)) { err("Character reference expands to a non-character."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } else if (value <= 0xFFFF) { /* * Otherwise, return a character token for the Unicode character * whose code point is that number. */ char ch = (char) value; if (errorHandler != null && isPrivateUse(ch)) { warnAboutPrivateUseChar(); } bmpChar[0] = ch; emitOrAppend(bmpChar, returnState); } else if (value <= 0x10FFFF) { if (errorHandler != null && isAstralPrivateUse(value)) { warnAboutPrivateUseChar(); } astralChar[0] = (char) (Tokenizer.LEAD_OFFSET + (value >> 10)); astralChar[1] = (char) (0xDC00 + (value & 0x3FF)); emitOrAppend(astralChar, returnState); } else { err("Character reference outside the permissible Unicode range."); emitOrAppend(Tokenizer.REPLACEMENT_CHARACTER, returnState); } } public void eof() throws SAXException { int state = stateSave; int returnState = returnStateSave; eofloop: for (;;) { switch (state) { case TAG_OPEN_NON_PCDATA: /* * Otherwise, emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case TAG_OPEN: /* * The behavior of this state depends on the content model * flag. */ /* * Anything else Parse error. */ err("End of file in the tag open state."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ break eofloop; case CLOSE_TAG_OPEN_NOT_PCDATA: break eofloop; case CLOSE_TAG_OPEN_PCDATA: /* EOF Parse error. */ err("Saw \u201C</\u201D immediately before end of file."); /* * Emit a U+003C LESS-THAN SIGN character token and a U+002F * SOLIDUS character token. */ tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); /* * Reconsume the EOF character in the data state. */ break eofloop; case TAG_NAME: /* * EOF Parse error. */ err("End of file seen when looking for tag name"); /* * Emit the current tag token. */ tagName = strBufToElementNameString(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case BEFORE_ATTRIBUTE_NAME: case AFTER_ATTRIBUTE_VALUE_QUOTED: case SELF_CLOSING_START_TAG: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case ATTRIBUTE_NAME: /* * EOF Parse error. */ err("End of file occurred in an attribute name."); /* * Emit the current tag token. */ attributeNameComplete(); addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_ATTRIBUTE_NAME: case BEFORE_ATTRIBUTE_VALUE: /* EOF Parse error. */ err("Saw end of file without the previous tag ending with \u201C>\u201D."); /* * Emit the current tag token. */ addAttributeWithoutValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case ATTRIBUTE_VALUE_DOUBLE_QUOTED: case ATTRIBUTE_VALUE_SINGLE_QUOTED: case ATTRIBUTE_VALUE_UNQUOTED: /* EOF Parse error. */ err("End of file reached when inside an attribute value."); /* Emit the current tag token. */ addAttributeWithValue(); emitCurrentTagToken(false); /* * Reconsume the character in the data state. */ break eofloop; case BOGUS_COMMENT: emitComment(); break eofloop; case MARKUP_DECLARATION_HYPHEN: appendToComment('-'); err("Bogus comment."); emitComment(); break eofloop; case MARKUP_DECLARATION_OPEN: case MARKUP_DECLARATION_OCTYPE: err("Bogus comment."); emitComment(); break eofloop; case COMMENT_START: case COMMENT_START_DASH: case COMMENT: case COMMENT_END_DASH: case COMMENT_END: /* * EOF Parse error. */ err("End of file inside comment."); /* Emit the comment token. */ emitComment(); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE: case BEFORE_DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Create a new DOCTYPE token. Set its force-quirks flag to * on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_NAME: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_UBLIC: case DOCTYPE_YSTEM: case AFTER_DOCTYPE_NAME: case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside public identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: /* EOF Parse error. */ err("End of file inside system identifier."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Reconsume the EOF character in the data state. */ break eofloop; case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: /* EOF Parse error. */ err("End of file inside doctype."); /* * Set the DOCTYPE token's force-quirks flag to on. Emit * that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, true); /* * Reconsume the EOF character in the data state. */ break eofloop; case BOGUS_DOCTYPE: /* * Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Reconsume the EOF character in the data state. */ break eofloop; case CONSUME_CHARACTER_REFERENCE: /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the entity * fails. */ clearStrBuf(); appendStrBuf('&'); /* * This section defines how to consume an entity. This * definition is used when parsing entities in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ emitOrAppendStrBuf(returnState); state = returnState; continue; case CHARACTER_REFERENCE_LOOP: outer: for (;;) { char c = '\u0000'; entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\201D."); emitOrAppendStrBuf(returnState); state = returnState; continue eofloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = '\u0000'; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; continue eofloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } state = returnState; continue eofloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: case DECIMAL_NRC_LOOP: case HEX_NCR_LOOP: /* * If no characters match the range, then don't consume any * characters (and unconsume the U+0023 NUMBER SIGN * character and, if appropriate, the X character). This is * a parse error; nothing is returned. * * Otherwise, if the next character is a U+003B SEMICOLON, * consume that too. If it isn't, there is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); state = returnState; continue; } else { err("Character reference was not terminated by a semicolon."); // FALL THROUGH continue stateloop; } // WARNING previous state sets reconsume handleNcrValue(returnState); state = returnState; continue; case DATA: default: break eofloop; } } // case DATA: /* * EOF Emit an end-of-file token. */ tokenHandler.eof(); return; } private char read() throws SAXException { char c; pos++; if (pos == end) { return '\u0000'; } // [NOCPP[ linePrev = line; colPrev = col; if (nextCharOnNewLine) { line++; col = 1; nextCharOnNewLine = false; } else { col++; } // ]NOCPP] c = buf[pos]; // [NOCPP[ if (errorHandler == null && contentNonXmlCharPolicy == XmlViolationPolicy.ALLOW) { // ]NOCPP] switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ c = buf[pos] = '\uFFFD'; break; } // [NOCPP[ } else { if (confidence == Confidence.TENTATIVE && !alreadyComplainedAboutNonAscii && c > '\u007F') { complainAboutNonAscii(); alreadyComplainedAboutNonAscii = true; } switch (c) { case '\r': nextCharOnNewLine = true; buf[pos] = '\n'; prev = '\r'; return '\n'; case '\n': if (prev == '\r') { pos--; return '\u0000'; } nextCharOnNewLine = true; break; case '\u0000': /* * All U+0000 NULL characters in the input must be replaced * by U+FFFD REPLACEMENT CHARACTERs. Any occurrences of such * characters is a parse error. */ err("Found U+0000 in the character stream."); c = buf[pos] = '\uFFFD'; break; case '\u000C': if (contentNonXmlCharPolicy == XmlViolationPolicy.FATAL) { fatal("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } else { if (contentNonXmlCharPolicy == XmlViolationPolicy.ALTER_INFOSET) { c = buf[pos] = ' '; } warn("This document is not mappable to XML 1.0 without data loss due to " + toUPlusString(c) + " which is not a legal XML 1.0 character."); } break; default: if ((c & 0xFC00) == 0xDC00) { // Got a low surrogate. See if prev was high // surrogate if ((prev & 0xFC00) == 0xD800) { int intVal = (prev << 10) + c + Tokenizer.SURROGATE_OFFSET; if (isNonCharacter(intVal)) { err("Astral non-character."); } if (isAstralPrivateUse(intVal)) { warnAboutPrivateUseChar(); } } else { // XXX figure out what to do about lone high // surrogates err("Found low surrogate without high surrogate."); // c = buf[pos] = '\uFFFD'; } } else if ((c < ' ' || isNonCharacter(c)) && (c != '\t')) { switch (contentNonXmlCharPolicy) { case FATAL: fatal("Forbidden code point " + toUPlusString(c) + "."); break; case ALTER_INFOSET: c = buf[pos] = '\uFFFD'; // fall through case ALLOW: err("Forbidden code point " + toUPlusString(c) + "."); } } else if ((c >= '\u007F') && (c <= '\u009F') || (c >= '\uFDD0') && (c <= '\uFDDF')) { err("Forbidden code point " + toUPlusString(c) + "."); } else if (isPrivateUse(c)) { warnAboutPrivateUseChar(); } } } // ]NOCPP] prev = c; return c; } protected void complainAboutNonAscii() throws SAXException { err("The character encoding of the document was not explicit but the document contains non-ASCII."); } public void internalEncodingDeclaration(String internalCharset) throws SAXException { // XXX NOP } /** * @param val * @throws SAXException */ private void emitOrAppend(char[] val, int returnState) throws SAXException { if ((returnState & (~1)) != 0) { appendLongStrBuf(val); } else { tokenHandler.characters(val, 0, val.length); } } public void end() throws SAXException { systemIdentifier = null; publicIdentifier = null; doctypeName = null; tagName = null; attributeName = null; tokenHandler.endTokenization(); } public void requestSuspension() { shouldSuspend = true; } }
true
true
private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case PLAINTEXT: plaintextloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBuf(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } // XXX reorder point case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapehyphenloop; // FALL THRU continue // stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case DATA: dataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: c = read(); if (c == '\u0000') { break stateloop; } /* * The behavior of this state depends on the content model * flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ if (c == '!') { /* * U+0021 EXCLAMATION MARK (!) Switch to the markup * declaration open state. */ clearLongStrBuf(); state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; } else if (c == '/') { /* * U+002F SOLIDUS (/) Switch to the close tag open * state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; } else if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBuf(); appendStrBuf((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBuf(); appendStrBuf(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c == '>') { /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token and a * U+003E GREATER-THAN SIGN character token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else if (c == '?') { /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } else { /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokeniser (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM * FEED (FF) + U+0020 SPACE + U+003E GREATER-THAN SIGN * (>) + U+002F SOLIDUS (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.name.length()) { char e = contentModelElement.name.charAt(index); char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { if (html4) { if (!"iframe".equals(contentModelElement)) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C * FORM FEED (FF) U+0020 SPACE Switch to the * before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = Tokenizer.DATA; continue stateloop; } } } case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ appendStrBuf((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the input character, */ appendStrBuf(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } case TAG_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } case BEFORE_ATTRIBUTE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after * attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after attribute * name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case BEFORE_ATTRIBUTE_VALUE: for (;;) { c = read(); // ASSERT! call clearLongStrBuf() before transitioning // to this state! /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } case ATTRIBUTE_VALUE_DOUBLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the additional * allowed character being U+0022 QUOTATION MARK * ("). */ additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_SINGLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the + additional * allowed character being U+0027 APOSTROPHE * ('). */ additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with no + additional * allowed character. */ additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } case AFTER_ATTRIBUTE_VALUE_QUOTED: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current tag * token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case BOGUS_COMMENT: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to the first U+003E * GREATER-THAN SIGN character (>) or the end of the * file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the last * consumed character before the U+003E character, if * any, or up to the end of the file otherwise. (If the * comment was started by the end of the file (EOF), the * token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(); cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: appendToComment(c); continue; } } case MARKUP_DECLARATION_OPEN: c = read(); // ASSERT! call clearLongStrBuf() before coming here! /* * (This can only happen if the content model flag is set to * the PCDATA state.) * * If the next two characters are both U+002D HYPHEN-MINUS * (-) characters, consume those two characters, create a * comment token whose data is the empty string, and switch * to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE state. * * Otherwise, if the insertion mode is "in foreign content" * and the current node is not an element in the HTML * namespace and the next seven characters are a * case-sensitive match for the string "[CDATA[" (the five * uppercase letters "CDATA" with a U+005B LEFT SQUARE * BRACKET character before and after), then consume those * characters and switch to the CDATA block state (which is * unrelated to the content model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, if * any, is the first character that will be in the comment. */ switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.MARKUP_DECLARATION_HYPHEN; continue stateloop; case 'd': case 'D': appendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { appendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.COMMENT_START; continue stateloop; default: err("Bogus comment."); appendToComment('-'); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_OCTYPE: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.OCTYPE.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; continue stateloop; } } case COMMENT_START: c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to the * comment token's data. */ appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ state = Tokenizer.COMMENT_END_DASH; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendToComment(c); /* * Stay in the comment state. */ continue; } } case COMMENT_END_DASH: c = read(); /* * Comment end dash state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ appendToComment('-'); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ appendToComment('-'); appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } case DOCTYPE: if (!reconsume) { c = read(); } reconsume = false; systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before DOCTYPE name * state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ clearStrBuf(); /* * Set the token's name name to the current * input character. */ appendStrBuf(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; continue stateloop; } } case DOCTYPE_NAME: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after DOCTYPE * name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } case AFTER_DOCTYPE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_UBLIC: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < Tokenizer.UBLIC.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; continue stateloop; } } case DOCTYPE_YSTEM: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before DOCTYPE * system identifier state. */ if (index < Tokenizer.YSTEM.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * system identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ forceQuirks = false; state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BOGUS_DOCTYPE: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.CDATA_LSQB.length) { if (c == Tokenizer.CDATA_LSQB[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_BLOCK; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_BLOCK: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the character reference * fails. */ clearStrBuf(); appendStrBuf('&'); /* * This section defines how to consume a character reference. This * definition is used when parsing character references in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } } } flushChars(); if (prev == '\r') { pos--; } // Save locals stateSave = state; returnStateSave = returnState; }
private void stateLoop(int state, char c, boolean reconsume, int returnState) throws SAXException { stateloop: for (;;) { switch (state) { case PLAINTEXT: plaintextloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case RCDATA: rcdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; continue stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // XXX reorder point case CDATA: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); returnState = state; state = Tokenizer.TAG_OPEN_NON_PCDATA; break cdataloop; // FALL THRU continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN_NON_PCDATA: tagopennonpcdataloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '!': tokenHandler.characters(Tokenizer.LT_GT, 0, 1); cstart = pos; state = Tokenizer.ESCAPE_EXCLAMATION; break tagopennonpcdataloop; // FALL THRU // continue // stateloop; case '/': /* * If the content model flag is set to the * RCDATA or CDATA states Consume the next input * character. */ if (contentModelElement != null) { /* * If it is a U+002F SOLIDUS (/) character, * switch to the close tag open state. */ index = 0; clearStrBuf(); state = Tokenizer.CLOSE_TAG_OPEN_NOT_PCDATA; continue stateloop; } // else fall through default: /* * Otherwise, emit a U+003C LESS-THAN SIGN * character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in * the data state. */ cstart = pos; state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION: escapeexclamationloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_EXCLAMATION_HYPHEN; break escapeexclamationloop; // FALL THRU // continue // stateloop; default: state = returnState; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_EXCLAMATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; continue stateloop; default: state = returnState; reconsume = true; continue stateloop; } // XXX reorder point case ESCAPE: escapeloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN; break escapeloop; // FALL THRU continue // stateloop; default: continue escapeloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN: escapehyphenloop: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.ESCAPE_HYPHEN_HYPHEN; break escapehyphenloop; // FALL THRU continue // stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case ESCAPE_HYPHEN_HYPHEN: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case '-': continue; case '>': state = returnState; continue stateloop; default: state = Tokenizer.ESCAPE; continue stateloop; } } // XXX reorder point case DATA: dataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case '&': /* * U+0026 AMPERSAND (&) When the content model * flag is set to one of the PCDATA or RCDATA * states and the escape flag is false: switch * to the character reference data state. Otherwise: treat it * as per the "anything else" entry below. */ flushChars(); additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '<': /* * U+003C LESS-THAN SIGN (<) When the content * model flag is set to the PCDATA state: switch * to the tag open state. When the content model * flag is set to either the RCDATA state or the * CDATA state and the escape flag is false: * switch to the tag open state. Otherwise: * treat it as per the "anything else" entry * below. */ flushChars(); resetAttributes(); state = Tokenizer.TAG_OPEN; break dataloop; // FALL THROUGH continue // stateloop; default: /* * Anything else Emit the input character as a * character token. */ /* * Stay in the data state. */ continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case TAG_OPEN: c = read(); if (c == '\u0000') { break stateloop; } /* * The behavior of this state depends on the content model * flag. */ /* * If the content model flag is set to the PCDATA state * Consume the next input character: */ if (c == '!') { /* * U+0021 EXCLAMATION MARK (!) Switch to the markup * declaration open state. */ clearLongStrBuf(); state = Tokenizer.MARKUP_DECLARATION_OPEN; continue stateloop; } else if (c == '/') { /* * U+002F SOLIDUS (/) Switch to the close tag open * state. */ state = Tokenizer.CLOSE_TAG_OPEN_PCDATA; continue stateloop; } else if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ clearStrBuf(); appendStrBuf((char) (c + 0x20)); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new start tag token, */ endTag = false; /* * set its tag name to the input character, */ clearStrBuf(); appendStrBuf(c); /* then switch to the tag name state. */ state = Tokenizer.TAG_NAME; /* * (Don't emit the token yet; further details will be * filled in before it is emitted.) */ continue stateloop; } else if (c == '>') { /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C<>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped start tag."); /* * Emit a U+003C LESS-THAN SIGN character token and a * U+003E GREATER-THAN SIGN character token. */ tokenHandler.characters(Tokenizer.LT_GT, 0, 2); /* Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else if (c == '?') { /* * U+003F QUESTION MARK (?) Parse error. */ err("Saw \u201C<?\u201D. Probable cause: Attempt to use an XML processing instruction in HTML. (XML processing instructions are not supported in HTML.)"); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendLongStrBuf(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } else { /* * Anything else Parse error. */ err("Bad character \u201C" + c + "\u201D after \u201C<\u201D. Probable cause: Unescaped \u201C<\u201D. Try escaping it as \u201C&lt;\u201D."); /* * Emit a U+003C LESS-THAN SIGN character token */ tokenHandler.characters(Tokenizer.LT_GT, 0, 1); /* * and reconsume the current input character in the data * state. */ cstart = pos; state = Tokenizer.DATA; reconsume = true; continue stateloop; } case CLOSE_TAG_OPEN_NOT_PCDATA: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // ASSERT! when entering this state, set index to 0 and // call clearStrBuf() assert (contentModelElement != null); /* * If the content model flag is set to the RCDATA or * CDATA states but no start tag token has ever been * emitted by this instance of the tokeniser (fragment * case), or, if the content model flag is set to the * RCDATA or CDATA states and the next few characters do * not match the tag name of the last start tag token * emitted (case insensitively), or if they do but they * are not immediately followed by one of the following * characters: + U+0009 CHARACTER TABULATION + U+000A * LINE FEED (LF) + + U+000C FORM * FEED (FF) + U+0020 SPACE + U+003E GREATER-THAN SIGN * (>) + U+002F SOLIDUS (/) + EOF * * ...then emit a U+003C LESS-THAN SIGN character token, * a U+002F SOLIDUS character token, and switch to the * data state to process the next input character. */ // Let's implement the above without lookahead. strBuf // holds // characters that need to be emitted if looking for an // end tag // fails. // Duplicating the relevant part of tag name state here // as well. if (index < contentModelElement.name.length()) { char e = contentModelElement.name.charAt(index); char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != e) { if (index > 0 || (folded >= 'a' && folded <= 'z')) { if (html4) { if (!"iframe".equals(contentModelElement)) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } } tokenHandler.characters(Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; state = returnState; reconsume = true; continue stateloop; } appendStrBuf(c); index++; continue; } else { endTag = true; // XXX replace contentModelElement with different // type tagName = contentModelElement; switch (c) { case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE * FEED (LF) U+000C * FORM FEED (FF) U+0020 SPACE Switch to the * before attribute name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the * current tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Parse error unless * this is a permitted slash. */ // never permitted here err("Stray \u201C/\u201D in end tag."); /* * Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; default: if (html4) { err((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but it was not the start of the end tag. (HTML4-only error)"); } else { warn((contentModelFlag == ContentModelFlag.CDATA ? "CDATA" : "RCDATA") + " element \u201C" + contentModelElement + "\u201D contained the string \u201C</\u201D, but this did not close the element."); } tokenHandler.characters( Tokenizer.LT_SOLIDUS, 0, 2); emitStrBuf(); cstart = pos; // don't drop the character state = Tokenizer.DATA; continue stateloop; } } } case CLOSE_TAG_OPEN_PCDATA: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the content model flag is set to the PCDATA * state, or if the next few characters do match that tag * name, consume the next input character: */ if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to U+005A LATIN * CAPITAL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the lowercase version of the * input character (add 0x0020 to the character's code * point), */ appendStrBuf((char) (c + 0x20)); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c >= 'a' && c <= 'z') { /* * U+0061 LATIN SMALL LETTER A through to U+007A LATIN * SMALL LETTER Z Create a new end tag token, */ endTag = true; clearStrBuf(); /* * set its tag name to the input character, */ appendStrBuf(c); /* * then switch to the tag name state. (Don't emit the * token yet; further details will be filled in before * it is emitted.) */ state = Tokenizer.TAG_NAME; continue stateloop; } else if (c == '>') { /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Saw \u201C</>\u201D. Probable causes: Unescaped \u201C<\u201D (escape as \u201C&lt;\u201D) or mistyped end tag."); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; } else { /* Anything else Parse error. */ err("Garbage after \u201C</\u201D."); /* * Switch to the bogus comment state. */ clearLongStrBuf(); appendToComment(c); state = Tokenizer.BOGUS_COMMENT; continue stateloop; } case TAG_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ tagName = strBufToElementNameString(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ tagName = strBufToElementNameString(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ tagName = strBufToElementNameString(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current tag token's * tag name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current tag token's tag * name. */ appendStrBuf(c); } /* * Stay in the tag name state. */ continue; } } case BEFORE_ATTRIBUTE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': case '=': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') U+003D EQUALS SIGN (=) Parse error. */ if (c == '=') { err("Saw \u201C=\u201D when expecting an attribute name. Probable cause: Attribute name missing."); } else { err("Saw \u201C" + c + "\u201D when expecting an attribute name. Probable cause: \u201C=\u201D missing immediately before."); } /* * Treat it as per the "anything else" entry * below. */ default: /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after * attribute name state. */ attributeNameComplete(); state = Tokenizer.AFTER_ATTRIBUTE_NAME; continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ attributeNameComplete(); clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ attributeNameComplete(); addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ attributeNameComplete(); addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; case '\"': case '\'': /* * U+0022 QUOTATION MARK (") U+0027 APOSTROPHE * (') Parse error. */ err("Quote \u201C" + c + "\u201D in attribute name. Probable cause: Matching quote missing somewhere earlier."); /* * Treat it as per the "anything else" entry * below. */ default: if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Append the * lowercase version of the current input * character (add 0x0020 to the character's * code point) to the current attribute's * name. */ appendStrBuf((char) (c + 0x20)); } else { /* * Anything else Append the current input * character to the current attribute's * name. */ appendStrBuf(c); } /* * Stay in the attribute name state. */ continue; } } case AFTER_ATTRIBUTE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after attribute * name state. */ continue; case '=': /* * U+003D EQUALS SIGN (=) Switch to the before * attribute value state. */ clearLongStrBuf(); state = Tokenizer.BEFORE_ATTRIBUTE_VALUE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ addAttributeWithoutValue(); state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: addAttributeWithoutValue(); /* * Anything else Start a new attribute in the * current tag token. */ clearStrBuf(); if (c >= 'A' && c <= 'Z') { /* * U+0041 LATIN CAPITAL LETTER A through to * U+005A LATIN CAPITAL LETTER Z Set that * attribute's name to the lowercase version * of the current input character (add * 0x0020 to the character's code point) */ appendStrBuf((char) (c + 0x20)); } else { /* * Set that attribute's name to the current * input character, */ appendStrBuf(c); } /* * and its value to the empty string. */ // Will do later. /* * Switch to the attribute name state. */ state = Tokenizer.ATTRIBUTE_NAME; continue stateloop; } } case BEFORE_ATTRIBUTE_VALUE: for (;;) { c = read(); // ASSERT! call clearLongStrBuf() before transitioning // to this state! /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before * attribute value state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Switch to the * attribute value (double-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_DOUBLE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the attribute * value (unquoted) state and reconsume this * input character. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; reconsume = true; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the attribute * value (single-quoted) state. */ state = Tokenizer.ATTRIBUTE_VALUE_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithoutValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '=': /* * U+003D EQUALS SIGN (=) Parse error. */ err("\u201C=\u201D in an unquoted attribute value. Probable cause: Stray duplicate equals sign."); /* * Treat it as per the "anything else" entry * below. */ default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Switch to the attribute value (unquoted) * state. */ state = Tokenizer.ATTRIBUTE_VALUE_UNQUOTED; continue stateloop; } } case ATTRIBUTE_VALUE_DOUBLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the additional * allowed character being U+0022 QUOTATION MARK * ("). */ additional = '\"'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_SINGLE_QUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * attribute value (quoted) state. */ addAttributeWithValue(); state = Tokenizer.AFTER_ATTRIBUTE_VALUE_QUOTED; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with the + additional * allowed character being U+0027 APOSTROPHE * ('). */ additional = '\''; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; default: /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (double-quoted) * state. */ continue; } } case ATTRIBUTE_VALUE_UNQUOTED: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the before * attribute name state. */ addAttributeWithValue(); state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '&': /* * U+0026 AMPERSAND (&) Switch to the character reference in * attribute value state, with no + additional * allowed character. */ additional = '\u0000'; returnState = state; state = Tokenizer.CONSUME_CHARACTER_REFERENCE; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * tag token. */ addAttributeWithValue(); cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '<': case '\"': case '\'': case '=': if (c == '<') { warn("\u201C<\u201D in an unquoted attribute value. This does not end the tag. Probable cause: Missing \u201C>\u201D immediately before."); } else { /* * U+0022 QUOTATION MARK (") U+0027 * APOSTROPHE (') U+003D EQUALS SIGN (=) * Parse error. */ err("\u201C" + c + "\u201D in an unquoted attribute value. Probable causes: Attributes running together or a URL query string in an unquoted attribute value."); /* * Treat it as per the "anything else" entry * below. */ } // fall through default: if (html4 && !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_' || c == ':')) { err("Non-name character in an unquoted attribute value. (This is an HTML4-only error.)"); } /* * Anything else Append the current input * character to the current attribute's value. */ appendLongStrBuf(c); /* * Stay in the attribute value (unquoted) state. */ continue; } } case AFTER_ATTRIBUTE_VALUE_QUOTED: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before attribute name * state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current tag * token. */ cstart = pos + 1; state = emitCurrentTagToken(false); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; case '/': /* * U+002F SOLIDUS (/) Switch to the self-closing * start tag state. */ state = Tokenizer.SELF_CLOSING_START_TAG; continue stateloop; default: /* * Anything else Parse error. */ err("No space between attributes."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case SELF_CLOSING_START_TAG: c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Set the self-closing * flag of the current tag token. Emit the current * tag token. */ cstart = pos + 1; state = emitCurrentTagToken(true); if (shouldSuspend) { break stateloop; } /* * Switch to the data state. */ continue stateloop; default: /* Anything else Parse error. */ err("A slash was not immediate followed by \u201C>\u201D."); /* * Reconsume the character in the before attribute * name state. */ state = Tokenizer.BEFORE_ATTRIBUTE_NAME; reconsume = true; continue stateloop; } case BOGUS_COMMENT: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * (This can only happen if the content model flag is * set to the PCDATA state.) * * Consume every character up to the first U+003E * GREATER-THAN SIGN character (>) or the end of the * file (EOF), whichever comes first. Emit a comment * token whose data is the concatenation of all the * characters starting from and including the character * that caused the state machine to switch into the * bogus comment state, up to and including the last * consumed character before the U+003E character, if * any, or up to the end of the file otherwise. (If the * comment was started by the end of the file (EOF), the * token is empty.) * * Switch to the data state. * * If the end of the file was reached, reconsume the EOF * character. */ switch (c) { case '\u0000': break stateloop; case '>': emitComment(); cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: appendToComment(c); continue; } } case MARKUP_DECLARATION_OPEN: c = read(); // ASSERT! call clearLongStrBuf() before coming here! /* * (This can only happen if the content model flag is set to * the PCDATA state.) * * If the next two characters are both U+002D HYPHEN-MINUS * (-) characters, consume those two characters, create a * comment token whose data is the empty string, and switch * to the comment start state. * * Otherwise, if the next seven characters are a * case-insensitive match for the word "DOCTYPE", then * consume those characters and switch to the DOCTYPE state. * * Otherwise, if the insertion mode is "in foreign content" * and the current node is not an element in the HTML * namespace and the next seven characters are a * case-sensitive match for the string "[CDATA[" (the five * uppercase letters "CDATA" with a U+005B LEFT SQUARE * BRACKET character before and after), then consume those * characters and switch to the CDATA block state (which is * unrelated to the content model flag's CDATA state). * * Otherwise, is is a parse error. Switch to the bogus * comment state. The next character that is consumed, if * any, is the first character that will be in the comment. */ switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.MARKUP_DECLARATION_HYPHEN; continue stateloop; case 'd': case 'D': appendToComment(c); index = 0; state = Tokenizer.MARKUP_DECLARATION_OCTYPE; continue stateloop; case '[': if (tokenHandler.inForeign()) { appendToComment(c); index = 0; state = Tokenizer.CDATA_START; continue stateloop; } else { // fall through } default: err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_HYPHEN: c = read(); switch (c) { case '\u0000': break stateloop; case '-': state = Tokenizer.COMMENT_START; continue stateloop; default: err("Bogus comment."); appendToComment('-'); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } case MARKUP_DECLARATION_OCTYPE: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.OCTYPE.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded == Tokenizer.OCTYPE[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.DOCTYPE; reconsume = true; continue stateloop; } } case COMMENT_START: c = read(); /* * Comment start state * * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * start dash state. */ state = Tokenizer.COMMENT_START_DASH; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the input character to the * comment token's data. */ appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_START_DASH: c = read(); /* * Comment start dash state * * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Premature end of comment. Use \u201C-->\u201D to end a comment properly."); /* Emit the comment token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT: for (;;) { c = read(); /* * Comment state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment * end dash state */ state = Tokenizer.COMMENT_END_DASH; continue stateloop; default: /* * Anything else Append the input character to * the comment token's data. */ appendToComment(c); /* * Stay in the comment state. */ continue; } } case COMMENT_END_DASH: c = read(); /* * Comment end dash state Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '-': /* * U+002D HYPHEN-MINUS (-) Switch to the comment end * state */ state = Tokenizer.COMMENT_END; continue stateloop; default: /* * Anything else Append a U+002D HYPHEN-MINUS (-) * character and the input character to the comment * token's data. */ appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } case COMMENT_END: for (;;) { c = read(); /* * Comment end dash state Consume the next input * character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the comment * token. */ emitComment(); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case '-': /* U+002D HYPHEN-MINUS (-) Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append a U+002D HYPHEN-MINUS (-) character to * the comment token's data. */ appendToComment('-'); /* * Stay in the comment end state. */ continue; default: /* * Anything else Parse error. */ err("Consecutive hyphens did not terminate a comment. \u201C--\u201D is not permitted inside a comment, but e.g. \u201C- -\u201D is."); /* * Append two U+002D HYPHEN-MINUS (-) characters * and the input character to the comment * token's data. */ appendToComment('-'); appendToComment('-'); appendToComment(c); /* * Switch to the comment state. */ state = Tokenizer.COMMENT; continue stateloop; } } case DOCTYPE: if (!reconsume) { c = read(); } reconsume = false; systemIdentifier = null; publicIdentifier = null; doctypeName = null; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED (LF) * U+000C FORM FEED (FF) * U+0020 SPACE Switch to the before DOCTYPE name * state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; continue stateloop; default: /* * Anything else Parse error. */ err("Missing space before doctype name."); /* * Reconsume the current character in the before * DOCTYPE name state. */ state = Tokenizer.BEFORE_DOCTYPE_NAME; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_NAME: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("Nameless doctype."); /* * Create a new DOCTYPE token. Set its * force-quirks flag to on. Emit the token. */ tokenHandler.doctype("", null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Create a new DOCTYPE token. */ clearStrBuf(); /* * Set the token's name name to the current * input character. */ appendStrBuf(c); /* * Switch to the DOCTYPE name state. */ state = Tokenizer.DOCTYPE_NAME; continue stateloop; } } case DOCTYPE_NAME: for (;;) { c = read(); /* * First, consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Switch to the after DOCTYPE * name state. */ doctypeName = strBufToString(); state = Tokenizer.AFTER_DOCTYPE_NAME; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(strBufToString(), null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * name. */ appendStrBuf(c); /* * Stay in the DOCTYPE name state. */ continue; } } case AFTER_DOCTYPE_NAME: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * name state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; case 'p': case 'P': index = 0; state = Tokenizer.DOCTYPE_UBLIC; continue stateloop; case 's': case 'S': index = 0; state = Tokenizer.DOCTYPE_YSTEM; continue stateloop; default: /* * Otherwise, this is the parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_UBLIC: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } /* * If the next six characters are a case-insensitive * match for the word "PUBLIC", then consume those * characters and switch to the before DOCTYPE public * identifier state. */ if (index < Tokenizer.UBLIC.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.UBLIC[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue; } else { state = Tokenizer.BEFORE_DOCTYPE_PUBLIC_IDENTIFIER; reconsume = true; continue stateloop; } } case DOCTYPE_YSTEM: c = read(); if (c == '\u0000') { break stateloop; } /* * Otherwise, if the next six characters are a * case-insensitive match for the word "SYSTEM", then * consume those characters and switch to the before DOCTYPE * system identifier state. */ if (index < Tokenizer.YSTEM.length) { char folded = c; if (c >= 'A' && c <= 'Z') { folded += 0x20; } if (folded != Tokenizer.YSTEM[index]) { err("Bogus doctype."); forceQuirks = true; state = Tokenizer.BOGUS_DOCTYPE; reconsume = true; continue stateloop; } index++; continue stateloop; } else { state = Tokenizer.BEFORE_DOCTYPE_SYSTEM_IDENTIFIER; reconsume = true; continue stateloop; } case BEFORE_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's public identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * public identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE public identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a public identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_PUBLIC_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (double-quoted) state. */ continue; } } case DOCTYPE_PUBLIC_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE public identifier state. */ publicIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_PUBLIC_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in public identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, longStrBufToString(), null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * public identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE public identifier * (single-quoted) state. */ continue; } } case AFTER_DOCTYPE_PUBLIC_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * public identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, null, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BEFORE_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the before DOCTYPE * system identifier state. */ continue; case '"': /* * U+0022 QUOTATION MARK (") Set the DOCTYPE * token's system identifier to the empty * string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (double-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED; continue stateloop; case '\'': /* * U+0027 APOSTROPHE (') Set the DOCTYPE token's * system identifier to the empty string (not missing), */ clearLongStrBuf(); /* * then switch to the DOCTYPE system identifier * (single-quoted) state. */ state = Tokenizer.DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED; continue stateloop; case '>': /* U+003E GREATER-THAN SIGN (>) Parse error. */ err("Expected a system identifier but the doctype ended."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, null, null, true); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Set the DOCTYPE token's force-quirks flag to * on. */ forceQuirks = true; /* * Switch to the bogus DOCTYPE state. */ state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case DOCTYPE_SYSTEM_IDENTIFIER_DOUBLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '"': /* * U+0022 QUOTATION MARK (") Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case DOCTYPE_SYSTEM_IDENTIFIER_SINGLE_QUOTED: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '\'': /* * U+0027 APOSTROPHE (') Switch to the after * DOCTYPE system identifier state. */ systemIdentifier = longStrBufToString(); state = Tokenizer.AFTER_DOCTYPE_SYSTEM_IDENTIFIER; continue stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Parse error. */ err("\u201C>\u201D in system identifier."); /* * Set the DOCTYPE token's force-quirks flag to * on. Emit that DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, longStrBufToString(), true); /* * Switch to the data state. * */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Append the current input * character to the current DOCTYPE token's * system identifier. */ appendLongStrBuf(c); /* * Stay in the DOCTYPE system identifier * (double-quoted) state. */ continue; } } case AFTER_DOCTYPE_SYSTEM_IDENTIFIER: for (;;) { c = read(); /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case ' ': case '\t': case '\n': case '\u000C': /* * U+0009 CHARACTER TABULATION U+000A LINE FEED * (LF) U+000C FORM FEED * (FF) U+0020 SPACE Stay in the after DOCTYPE * system identifier state. */ continue; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit the current * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, false); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* Anything else Parse error. */ err("Bogus doctype."); /* * Switch to the bogus DOCTYPE state. (This does * not set the DOCTYPE token's force-quirks flag * to on.) */ forceQuirks = false; state = Tokenizer.BOGUS_DOCTYPE; continue stateloop; } } case BOGUS_DOCTYPE: for (;;) { if (!reconsume) { c = read(); } reconsume = false; /* * Consume the next input character: */ switch (c) { case '\u0000': break stateloop; case '>': /* * U+003E GREATER-THAN SIGN (>) Emit that * DOCTYPE token. */ tokenHandler.doctype(doctypeName, publicIdentifier, systemIdentifier, forceQuirks); /* * Switch to the data state. */ cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: /* * Anything else Stay in the bogus DOCTYPE * state. */ continue; } } case CDATA_START: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } if (index < Tokenizer.CDATA_LSQB.length) { if (c == Tokenizer.CDATA_LSQB[index]) { appendToComment(c); } else { err("Bogus comment."); state = Tokenizer.BOGUS_COMMENT; reconsume = true; continue stateloop; } index++; continue; } else { cstart = pos; // start coalescing state = Tokenizer.CDATA_BLOCK; reconsume = true; break; // FALL THROUGH continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_BLOCK: cdataloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; switch (c) { case '\u0000': break stateloop; case ']': flushChars(); state = Tokenizer.CDATA_RSQB; break cdataloop; // FALL THROUGH default: continue; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB: cdatarsqb: for (;;) { c = read(); switch (c) { case '\u0000': break stateloop; case ']': state = Tokenizer.CDATA_RSQB_RSQB; break cdatarsqb; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 1); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CDATA_RSQB_RSQB: c = read(); switch (c) { case '\u0000': break stateloop; case '>': cstart = pos + 1; state = Tokenizer.DATA; continue stateloop; default: tokenHandler.characters(Tokenizer.RSQB_RSQB, 0, 2); cstart = pos; state = Tokenizer.CDATA_BLOCK; reconsume = true; continue stateloop; } case CONSUME_CHARACTER_REFERENCE: c = read(); if (c == '\u0000') { break stateloop; } /* * Unlike the definition is the spec, this state does not * return a value and never requires the caller to * backtrack. This state takes care of emitting characters * or appending to the current attribute value. It also * takes care of that in the case when consuming the character reference * fails. */ clearStrBuf(); appendStrBuf('&'); /* * This section defines how to consume a character reference. This * definition is used when parsing character references in text and in * attributes. * * The behavior depends on the identity of the next * character (the one immediately after the U+0026 AMPERSAND * character): */ switch (c) { case ' ': case '\t': case '\n': case '\u000C': case '<': case '&': emitOrAppendStrBuf(returnState); cstart = pos; state = returnState; reconsume = true; continue stateloop; case '#': /* * U+0023 NUMBER SIGN (#) Consume the U+0023 NUMBER * SIGN. */ appendStrBuf('#'); state = Tokenizer.CONSUME_NCR; continue stateloop; default: if (c == additional) { emitOrAppendStrBuf(returnState); state = returnState; reconsume = true; continue stateloop; } entCol = -1; lo = 0; hi = (NamedCharacters.NAMES.length - 1); candidate = -1; strBufMark = 0; state = Tokenizer.CHARACTER_REFERENCE_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case CHARACTER_REFERENCE_LOOP: outer: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } entCol++; /* * Anything else Consume the maximum number of * characters possible, with the consumed characters * case-sensitively matching one of the identifiers in * the first column of the named character references table. */ hiloop: for (;;) { if (hi == -1) { break hiloop; } if (entCol == NamedCharacters.NAMES[hi].length) { break hiloop; } if (entCol > NamedCharacters.NAMES[hi].length) { break outer; } else if (c < NamedCharacters.NAMES[hi][entCol]) { hi--; } else { break hiloop; } } loloop: for (;;) { if (hi < lo) { break outer; } if (entCol == NamedCharacters.NAMES[lo].length) { candidate = lo; strBufMark = strBufLen; lo++; } else if (entCol > NamedCharacters.NAMES[lo].length) { break outer; } else if (c > NamedCharacters.NAMES[lo][entCol]) { lo++; } else { break loloop; } } if (hi < lo) { break outer; } appendStrBuf(c); continue; } // TODO warn about apos (IE) and TRADE (Opera) if (candidate == -1) { /* * If no match can be made, then this is a parse error. */ err("Text after \u201C&\u201D did not match an entity name. Probable cause: \u201C&\u201D should have been escaped as \u201C&amp;\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { char[] candidateArr = NamedCharacters.NAMES[candidate]; if (candidateArr[candidateArr.length - 1] != ';') { /* * If the last character matched is not a U+003B * SEMICOLON (;), there is a parse error. */ err("Entity reference was not terminated by a semicolon."); if ((returnState & (~1)) != 0) { /* * If the entity is being consumed as part of an * attribute, and the last character matched is * not a U+003B SEMICOLON (;), */ char ch; if (strBufMark == strBufLen) { ch = c; } else { ch = strBuf[strBufMark]; } if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) { /* * and the next character is in the range * U+0030 DIGIT ZERO to U+0039 DIGIT NINE, * U+0041 LATIN CAPITAL LETTER A to U+005A * LATIN CAPITAL LETTER Z, or U+0061 LATIN * SMALL LETTER A to U+007A LATIN SMALL * LETTER Z, then, for historical reasons, * all the characters that were matched * after the U+0026 AMPERSAND (&) must be * unconsumed, and nothing is returned. */ appendStrBufToLongStrBuf(); state = returnState; reconsume = true; continue stateloop; } } } /* * Otherwise, return a character token for the character * corresponding to the entity name (as given by the * second column of the named character references table). */ char[] val = NamedCharacters.VALUES[candidate]; emitOrAppend(val, returnState); // this is so complicated! if (strBufMark < strBufLen) { if ((returnState & (~1)) != 0) { for (int i = strBufMark; i < strBufLen; i++) { appendLongStrBuf(strBuf[i]); } } else { tokenHandler.characters(strBuf, strBufMark, strBufLen - strBufMark); } } if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; /* * If the markup contains I'm &notit; I tell you, the * entity is parsed as "not", as in, I'm ¬it; I tell * you. But if the markup was I'm &notin; I tell you, * the entity would be parsed as "notin;", resulting in * I'm ∉ I tell you. */ } case CONSUME_NCR: c = read(); prevValue = -1; value = 0; seenDigits = false; /* * The behavior further depends on the character after the * U+0023 NUMBER SIGN: */ switch (c) { case '\u0000': break stateloop; case 'x': case 'X': /* * U+0078 LATIN SMALL LETTER X U+0058 LATIN CAPITAL * LETTER X Consume the X. * * Follow the steps below, but using the range of * characters U+0030 DIGIT ZERO through to U+0039 * DIGIT NINE, U+0061 LATIN SMALL LETTER A through * to U+0066 LATIN SMALL LETTER F, and U+0041 LATIN * CAPITAL LETTER A, through to U+0046 LATIN CAPITAL * LETTER F (in other words, 0-9, A-F, a-f). * * When it comes to interpreting the number, * interpret it as a hexadecimal number. */ appendStrBuf(c); state = Tokenizer.HEX_NCR_LOOP; continue stateloop; default: /* * Anything else Follow the steps below, but using * the range of characters U+0030 DIGIT ZERO through * to U+0039 DIGIT NINE (i.e. just 0-9). * * When it comes to interpreting the number, * interpret it as a decimal number. */ state = Tokenizer.DECIMAL_NRC_LOOP; reconsume = true; // FALL THROUGH continue stateloop; } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case DECIMAL_NRC_LOOP: decimalloop: for (;;) { if (!reconsume) { c = read(); } reconsume = false; if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 10; value += c - '0'; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; if ((returnState & (~1)) == 0) { cstart = pos + 1; } // FALL THROUGH continue stateloop; break decimalloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; if ((returnState & (~1)) == 0) { cstart = pos; } // FALL THROUGH continue stateloop; break decimalloop; } } } // WARNING FALLTHRU CASE TRANSITION: DON'T REORDER case HANDLE_NCR_VALUE: // WARNING previous state sets reconsume // XXX inline this case if the method size can take it handleNcrValue(returnState); state = returnState; continue stateloop; case HEX_NCR_LOOP: for (;;) { c = read(); if (c == '\u0000') { break stateloop; } // Deal with overflow gracefully if (value < prevValue) { value = 0x110000; // Value above Unicode range but // within int // range } prevValue = value; /* * Consume as many characters as match the range of * characters given above. */ if (c >= '0' && c <= '9') { seenDigits = true; value *= 16; value += c - '0'; continue; } else if (c >= 'A' && c <= 'F') { seenDigits = true; value *= 16; value += c - 'A' + 10; continue; } else if (c >= 'a' && c <= 'f') { seenDigits = true; value *= 16; value += c - 'a' + 10; continue; } else if (c == ';') { if (seenDigits) { state = Tokenizer.HANDLE_NCR_VALUE; cstart = pos + 1; continue stateloop; } else { err("No digits after \u201C" + strBufToString() + "\u201D."); appendStrBuf(';'); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos + 1; } state = returnState; continue stateloop; } } else { /* * If no characters match the range, then don't * consume any characters (and unconsume the U+0023 * NUMBER SIGN character and, if appropriate, the X * character). This is a parse error; nothing is * returned. * * Otherwise, if the next character is a U+003B * SEMICOLON, consume that too. If it isn't, there * is a parse error. */ if (!seenDigits) { err("No digits after \u201C" + strBufToString() + "\u201D."); emitOrAppendStrBuf(returnState); if ((returnState & (~1)) == 0) { cstart = pos; } state = returnState; reconsume = true; continue stateloop; } else { err("Character reference was not terminated by a semicolon."); if ((returnState & (~1)) == 0) { cstart = pos; } state = Tokenizer.HANDLE_NCR_VALUE; reconsume = true; continue stateloop; } } } } } flushChars(); if (prev == '\r') { pos--; } // Save locals stateSave = state; returnStateSave = returnState; }
diff --git a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/imports/ImportsManager.java b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/imports/ImportsManager.java index c744a540..7656e656 100644 --- a/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/imports/ImportsManager.java +++ b/net.sf.eclipsefp.haskell.ui/src/net/sf/eclipsefp/haskell/ui/internal/editors/haskell/imports/ImportsManager.java @@ -1,133 +1,136 @@ package net.sf.eclipsefp.haskell.ui.internal.editors.haskell.imports; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.eclipsefp.haskell.browser.items.Documented; import net.sf.eclipsefp.haskell.core.project.HaskellProjectManager; import net.sf.eclipsefp.haskell.core.project.IHaskellProject; import net.sf.eclipsefp.haskell.scion.client.ScionInstance; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jface.text.IDocument; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.Region; public class ImportsManager { private final IFile file; private final IDocument doc; public ImportsManager(final IFile file, final IDocument doc) { this.file = file; this.doc = doc; } public ArrayList<AnImport> parseImports() { ArrayList<AnImport> r = new ArrayList<AnImport>(); int lines = doc.getNumberOfLines(); for (int line = 0; line < lines; line++) { try { IRegion reg = doc.getLineInformation( line ); String contents = doc.get( reg.getOffset(), reg.getLength() ); // Take blanks appart int realInit = reg.getOffset(); int realLength = reg.getLength(); for (int i = 0; i < contents.length(); i++) { if (Character.isWhitespace( i )) { realInit++; realLength--; } else { break; } } // Get contents another time reg = new Region( realInit, realLength ); contents = doc.get( reg.getOffset(), reg.getLength() ); if (contents.startsWith( "import" )) { // We are in an import declaration String[] words = contents.split( "[ \t\n\r]+" ); if (words.length > 1) { // We are in an import with more than "import" on it int namePlace = 1; boolean isQualified = false; // See if we have a "qualified" if (words[1].equals("qualified")) { namePlace = 2; isQualified = true; } // Take the name of the import String name = words[namePlace]; String items = null; String qualifiedName = null; boolean isHiding = false; // See if we have more things if (words.length > namePlace + 1) { int nextThings = namePlace + 1; + // Maybe we have a "as" clause + if (words[nextThings].equals("as")) { + nextThings++; + if (words.length > nextThings) { + qualifiedName = words[nextThings]; + nextThings++; + } + } // Maybe we have a hiding clause if (words[nextThings].equals("hiding")) { nextThings++; isHiding = true; } // Try to find '(' and ')' int beginPar = contents.indexOf( '(' ); if (beginPar != -1) { int endPar = contents.indexOf( ')' ); items = contents.substring( beginPar + 1, endPar ); } - // Try to find "as" - int lastElement = words.length - 1; - if (words[lastElement - 1].equals( "as" )) { - qualifiedName = words[lastElement]; - } } // Create the element AnImport imp = new AnImport( name, reg, items != null, isHiding, isQualified, qualifiedName, items ); r.add(imp); } } } catch (Exception ex) { // We continue with the next line } } return r; } public Map<String, Documented> getDeclarations( final ScionInstance scion ) { ArrayList<AnImport> imports = parseImports(); // Add Prelude import boolean hasPrelude = false; for (AnImport i : imports) { if (i.getName().equals( "Prelude" )) { hasPrelude = true; break; } } if (!hasPrelude) { imports.add( new AnImport( "Prelude", null, true, false, null ) ); } // Add me String meName = "Me"; IProject project = file.getProject(); IHaskellProject pr = HaskellProjectManager.get( project ); for (Map.Entry<String, IFile> f : pr.getModulesFile().entrySet()) { if (f.getValue().getProjectRelativePath().equals( file.getProjectRelativePath() )) { meName = f.getKey(); break; } } imports.add( AnImport.createMe( meName ) ); HashMap<String, Documented> r = new HashMap<String, Documented>(); for (AnImport i : imports) { r.putAll( i.getDeclarations( scion, project, file, doc ) ); } return r; } }
false
true
public ArrayList<AnImport> parseImports() { ArrayList<AnImport> r = new ArrayList<AnImport>(); int lines = doc.getNumberOfLines(); for (int line = 0; line < lines; line++) { try { IRegion reg = doc.getLineInformation( line ); String contents = doc.get( reg.getOffset(), reg.getLength() ); // Take blanks appart int realInit = reg.getOffset(); int realLength = reg.getLength(); for (int i = 0; i < contents.length(); i++) { if (Character.isWhitespace( i )) { realInit++; realLength--; } else { break; } } // Get contents another time reg = new Region( realInit, realLength ); contents = doc.get( reg.getOffset(), reg.getLength() ); if (contents.startsWith( "import" )) { // We are in an import declaration String[] words = contents.split( "[ \t\n\r]+" ); if (words.length > 1) { // We are in an import with more than "import" on it int namePlace = 1; boolean isQualified = false; // See if we have a "qualified" if (words[1].equals("qualified")) { namePlace = 2; isQualified = true; } // Take the name of the import String name = words[namePlace]; String items = null; String qualifiedName = null; boolean isHiding = false; // See if we have more things if (words.length > namePlace + 1) { int nextThings = namePlace + 1; // Maybe we have a hiding clause if (words[nextThings].equals("hiding")) { nextThings++; isHiding = true; } // Try to find '(' and ')' int beginPar = contents.indexOf( '(' ); if (beginPar != -1) { int endPar = contents.indexOf( ')' ); items = contents.substring( beginPar + 1, endPar ); } // Try to find "as" int lastElement = words.length - 1; if (words[lastElement - 1].equals( "as" )) { qualifiedName = words[lastElement]; } } // Create the element AnImport imp = new AnImport( name, reg, items != null, isHiding, isQualified, qualifiedName, items ); r.add(imp); } } } catch (Exception ex) { // We continue with the next line } } return r; }
public ArrayList<AnImport> parseImports() { ArrayList<AnImport> r = new ArrayList<AnImport>(); int lines = doc.getNumberOfLines(); for (int line = 0; line < lines; line++) { try { IRegion reg = doc.getLineInformation( line ); String contents = doc.get( reg.getOffset(), reg.getLength() ); // Take blanks appart int realInit = reg.getOffset(); int realLength = reg.getLength(); for (int i = 0; i < contents.length(); i++) { if (Character.isWhitespace( i )) { realInit++; realLength--; } else { break; } } // Get contents another time reg = new Region( realInit, realLength ); contents = doc.get( reg.getOffset(), reg.getLength() ); if (contents.startsWith( "import" )) { // We are in an import declaration String[] words = contents.split( "[ \t\n\r]+" ); if (words.length > 1) { // We are in an import with more than "import" on it int namePlace = 1; boolean isQualified = false; // See if we have a "qualified" if (words[1].equals("qualified")) { namePlace = 2; isQualified = true; } // Take the name of the import String name = words[namePlace]; String items = null; String qualifiedName = null; boolean isHiding = false; // See if we have more things if (words.length > namePlace + 1) { int nextThings = namePlace + 1; // Maybe we have a "as" clause if (words[nextThings].equals("as")) { nextThings++; if (words.length > nextThings) { qualifiedName = words[nextThings]; nextThings++; } } // Maybe we have a hiding clause if (words[nextThings].equals("hiding")) { nextThings++; isHiding = true; } // Try to find '(' and ')' int beginPar = contents.indexOf( '(' ); if (beginPar != -1) { int endPar = contents.indexOf( ')' ); items = contents.substring( beginPar + 1, endPar ); } } // Create the element AnImport imp = new AnImport( name, reg, items != null, isHiding, isQualified, qualifiedName, items ); r.add(imp); } } } catch (Exception ex) { // We continue with the next line } } return r; }
diff --git a/dspace-api/src/main/java/org/dspace/search/SearchConsumer.java b/dspace-api/src/main/java/org/dspace/search/SearchConsumer.java index 35af56a6f..a56af7e61 100644 --- a/dspace-api/src/main/java/org/dspace/search/SearchConsumer.java +++ b/dspace-api/src/main/java/org/dspace/search/SearchConsumer.java @@ -1,263 +1,263 @@ /* * SearchConsumer.java * * Location: $URL$ * * Version: $Revision$ * * Date: $Date$ * * Copyright (c) 2002-2007, Hewlett-Packard Company and Massachusetts * Institute of Technology. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * - Neither the name of the Hewlett-Packard Company nor the name of the * Massachusetts Institute of Technology nor the names of their * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ package org.dspace.search; import java.util.HashSet; import java.util.Set; import org.apache.log4j.Logger; import org.dspace.content.Bundle; import org.dspace.content.DSpaceObject; import org.dspace.content.Item; import org.dspace.uri.ObjectIdentifier; import org.dspace.uri.IdentifierService; import org.dspace.core.Constants; import org.dspace.core.Context; import org.dspace.event.Consumer; import org.dspace.event.Event; /** * Class for updating search indices from content events. * * @version $Revision$ */ public class SearchConsumer implements Consumer { /** log4j logger */ private static Logger log = Logger.getLogger(SearchConsumer.class); // collect Items, Collections, Communities that need indexing private Set<DSpaceObject> objectsToUpdate = null; // oid to delete since IDs are not useful by now. private Set<ObjectIdentifier> objectsToDelete = null; public void initialize() throws Exception { // No-op } /** * Consume a content event -- just build the sets of objects to add (new) to * the index, update, and delete. * * @param ctx * DSpace context * @param event * Content event */ public void consume(Context ctx, Event event) throws Exception { if (objectsToUpdate == null) { objectsToUpdate = new HashSet<DSpaceObject>(); objectsToDelete = new HashSet<ObjectIdentifier>(); } int st = event.getSubjectType(); if (!(st == Constants.ITEM || st == Constants.BUNDLE || st == Constants.COLLECTION || st == Constants.COMMUNITY)) { log - .warn("SearchConsumer should not have been given this kind of Object in an event, skipping: " + .warn("SearchConsumer should not have been given this kind of Subject in an event, skipping: " + event.toString()); return; } DSpaceObject subject = event.getSubject(ctx); DSpaceObject object = event.getObject(ctx); // If event subject is a Bundle and event was Add or Remove, // transform the event to be a Modify on the owning Item. // It could be a new bitstream in the TEXT bundle which // would change the index. int et = event.getEventType(); if (st == Constants.BUNDLE) { if ((et == Event.ADD || et == Event.REMOVE) && subject != null && ((Bundle) subject).getName().equals("TEXT")) { st = Constants.ITEM; et = Event.MODIFY; subject = ((Bundle) subject).getItems()[0]; if (log.isDebugEnabled()) log.debug("Transforming Bundle event into MODIFY of Item " // + dso.getHandle()); + subject.getID()); } else return; } switch (et) { case Event.CREATE: case Event.MODIFY: case Event.MODIFY_METADATA: if (subject == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getSubjectTypeAsString() + " id=" + String.valueOf(event.getSubjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(subject); break; case Event.REMOVE: case Event.ADD: if (object == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getObjectTypeAsString() + " id=" + String.valueOf(event.getObjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(object); break; case Event.DELETE: String detail = event.getDetail(); if (detail == null) log.warn("got null detail on DELETE event, skipping it."); else objectsToDelete.add(ObjectIdentifier.parseCanonicalForm(detail)); break; default: log.warn("SearchConsumer should not have been " + "given a event of type=" + event.getEventTypeAsString() + " on subject=" + event.getSubjectTypeAsString()); break; } } /** * Process sets of objects to add, update, and delete in index. Correct for * interactions between the sets -- e.g. objects which were deleted do not * need to be added or updated, new objects don't also need an update, etc. */ public void end(Context ctx) throws Exception { if (objectsToUpdate != null && objectsToDelete != null) { // update the changed Items not deleted because they were on create // list for (DSpaceObject iu : objectsToUpdate) { if (iu.getType() != Constants.ITEM || ((Item) iu).isArchived()) { // if handle is NOT in list of deleted objects, index it: ObjectIdentifier oid = iu.getIdentifier(); if (oid != null && !objectsToDelete.contains(oid)) { try { DSIndexer.indexContent(ctx, iu,true); if (log.isDebugEnabled()) log.debug("re-indexed " + Constants.typeText[iu.getType()] + ", id=" + String.valueOf(iu.getID()) + ", oid=" + oid.getCanonicalForm()); } catch (Exception e) { log.error("Failed while re-indexing object: ", e); objectsToUpdate = null; objectsToDelete = null; } } else if (iu.getType() == Constants.ITEM && ( !((Item) iu).isArchived() || ((Item) iu).isWithdrawn())) { try { // If an update to an Item removes it from the // archive we must remove it from the search indices DSIndexer.unIndexContent(ctx, (DSpaceObject) IdentifierService.getResource(ctx, oid)); } catch (Exception e) { log.error("Failed while un-indexing object: " + oid.getCanonicalForm(), e); objectsToUpdate = new HashSet<DSpaceObject>(); objectsToDelete = new HashSet<ObjectIdentifier>(); } } } } for (ObjectIdentifier oid : objectsToDelete) { try { DSIndexer.unIndexContent(ctx, (DSpaceObject) IdentifierService.getResource(ctx, oid)); if (log.isDebugEnabled()) log.debug("un-indexed Item, oid=" + oid.getCanonicalForm()); } catch (Exception e) { log.error("Failed while un-indexing object: " + oid.getCanonicalForm(), e); objectsToUpdate = new HashSet<DSpaceObject>(); objectsToDelete = new HashSet<ObjectIdentifier>(); } } } // "free" the resources objectsToUpdate = null; objectsToDelete = null; } public void finish(Context ctx) throws Exception { // No-op } }
true
true
public void consume(Context ctx, Event event) throws Exception { if (objectsToUpdate == null) { objectsToUpdate = new HashSet<DSpaceObject>(); objectsToDelete = new HashSet<ObjectIdentifier>(); } int st = event.getSubjectType(); if (!(st == Constants.ITEM || st == Constants.BUNDLE || st == Constants.COLLECTION || st == Constants.COMMUNITY)) { log .warn("SearchConsumer should not have been given this kind of Object in an event, skipping: " + event.toString()); return; } DSpaceObject subject = event.getSubject(ctx); DSpaceObject object = event.getObject(ctx); // If event subject is a Bundle and event was Add or Remove, // transform the event to be a Modify on the owning Item. // It could be a new bitstream in the TEXT bundle which // would change the index. int et = event.getEventType(); if (st == Constants.BUNDLE) { if ((et == Event.ADD || et == Event.REMOVE) && subject != null && ((Bundle) subject).getName().equals("TEXT")) { st = Constants.ITEM; et = Event.MODIFY; subject = ((Bundle) subject).getItems()[0]; if (log.isDebugEnabled()) log.debug("Transforming Bundle event into MODIFY of Item " // + dso.getHandle()); + subject.getID()); } else return; } switch (et) { case Event.CREATE: case Event.MODIFY: case Event.MODIFY_METADATA: if (subject == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getSubjectTypeAsString() + " id=" + String.valueOf(event.getSubjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(subject); break; case Event.REMOVE: case Event.ADD: if (object == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getObjectTypeAsString() + " id=" + String.valueOf(event.getObjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(object); break; case Event.DELETE: String detail = event.getDetail(); if (detail == null) log.warn("got null detail on DELETE event, skipping it."); else objectsToDelete.add(ObjectIdentifier.parseCanonicalForm(detail)); break; default: log.warn("SearchConsumer should not have been " + "given a event of type=" + event.getEventTypeAsString() + " on subject=" + event.getSubjectTypeAsString()); break; } }
public void consume(Context ctx, Event event) throws Exception { if (objectsToUpdate == null) { objectsToUpdate = new HashSet<DSpaceObject>(); objectsToDelete = new HashSet<ObjectIdentifier>(); } int st = event.getSubjectType(); if (!(st == Constants.ITEM || st == Constants.BUNDLE || st == Constants.COLLECTION || st == Constants.COMMUNITY)) { log .warn("SearchConsumer should not have been given this kind of Subject in an event, skipping: " + event.toString()); return; } DSpaceObject subject = event.getSubject(ctx); DSpaceObject object = event.getObject(ctx); // If event subject is a Bundle and event was Add or Remove, // transform the event to be a Modify on the owning Item. // It could be a new bitstream in the TEXT bundle which // would change the index. int et = event.getEventType(); if (st == Constants.BUNDLE) { if ((et == Event.ADD || et == Event.REMOVE) && subject != null && ((Bundle) subject).getName().equals("TEXT")) { st = Constants.ITEM; et = Event.MODIFY; subject = ((Bundle) subject).getItems()[0]; if (log.isDebugEnabled()) log.debug("Transforming Bundle event into MODIFY of Item " // + dso.getHandle()); + subject.getID()); } else return; } switch (et) { case Event.CREATE: case Event.MODIFY: case Event.MODIFY_METADATA: if (subject == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getSubjectTypeAsString() + " id=" + String.valueOf(event.getSubjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(subject); break; case Event.REMOVE: case Event.ADD: if (object == null) log.warn(event.getEventTypeAsString() + " event, could not get object for " + event.getObjectTypeAsString() + " id=" + String.valueOf(event.getObjectID()) + ", perhaps it has been deleted."); else objectsToUpdate.add(object); break; case Event.DELETE: String detail = event.getDetail(); if (detail == null) log.warn("got null detail on DELETE event, skipping it."); else objectsToDelete.add(ObjectIdentifier.parseCanonicalForm(detail)); break; default: log.warn("SearchConsumer should not have been " + "given a event of type=" + event.getEventTypeAsString() + " on subject=" + event.getSubjectTypeAsString()); break; } }
diff --git a/src/main/java/com/wesabe/grendel/openpgp/UnlockedSubKey.java b/src/main/java/com/wesabe/grendel/openpgp/UnlockedSubKey.java index 8a5d7ea..75bd512 100644 --- a/src/main/java/com/wesabe/grendel/openpgp/UnlockedSubKey.java +++ b/src/main/java/com/wesabe/grendel/openpgp/UnlockedSubKey.java @@ -1,24 +1,24 @@ package com.wesabe.grendel.openpgp; import org.bouncycastle.openpgp.PGPPrivateKey; import org.bouncycastle.openpgp.PGPSecretKey; public class UnlockedSubKey extends SubKey implements UnlockedKey { private final PGPPrivateKey privateKey; - public UnlockedSubKey(PGPSecretKey key, MasterKey masterKey, PGPPrivateKey privateKey) { + protected UnlockedSubKey(PGPSecretKey key, MasterKey masterKey, PGPPrivateKey privateKey) { super(key, masterKey); this.privateKey = privateKey; } @Override public UnlockedSubKey unlock(char[] passphrase) { return this; } @Override public PGPPrivateKey getPrivateKey() { return privateKey; } }
true
true
public UnlockedSubKey(PGPSecretKey key, MasterKey masterKey, PGPPrivateKey privateKey) { super(key, masterKey); this.privateKey = privateKey; }
protected UnlockedSubKey(PGPSecretKey key, MasterKey masterKey, PGPPrivateKey privateKey) { super(key, masterKey); this.privateKey = privateKey; }
diff --git a/src/jmetest/renderer/loader/TestMilkshapeASCII.java b/src/jmetest/renderer/loader/TestMilkshapeASCII.java index 641f8ba38..3e0a69216 100755 --- a/src/jmetest/renderer/loader/TestMilkshapeASCII.java +++ b/src/jmetest/renderer/loader/TestMilkshapeASCII.java @@ -1,194 +1,194 @@ /* * Copyright (c) 2003, jMonkeyEngine - Mojo Monkey Coding * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the * names of its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ package jmetest.renderer.loader; import com.jme.app.SimpleGame; import com.jme.input.FirstPersonController; import com.jme.input.InputController; import com.jme.light.DirectionalLight; import com.jme.light.SpotLight; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.ColorRGBA; import com.jme.scene.Controller; import com.jme.scene.Node; import com.jme.scene.model.Model; import com.jme.scene.model.msascii.MilkshapeASCIIModel; import com.jme.scene.state.LightState; import com.jme.scene.state.ZBufferState; import com.jme.system.DisplaySystem; import com.jme.system.JmeException; import com.jme.util.Timer; /** * <code>TestBackwardAction</code> * @author Mark Powell * @version */ public class TestMilkshapeASCII extends SimpleGame { private Camera cam; private Node scene; private InputController input; private Model model; private Timer timer; /** * Nothing to update. * @see com.jme.app.AbstractGame#update() */ protected void update(float interpolation) { timer.update(); input.update(timer.getTimePerFrame() * 100); System.out.println(timer.getFrameRate()); scene.updateWorldData(timer.getTimePerFrame()); } /** * Render the scene * @see com.jme.app.AbstractGame#render() */ protected void render(float interpolation) { display.getRenderer().clearBuffers(); display.getRenderer().draw(scene); } /** * set up the display system and camera. * @see com.jme.app.AbstractGame#initSystem() */ protected void initSystem() { try { display = DisplaySystem.getDisplaySystem(properties.getRenderer()); display.createWindow( properties.getWidth(), properties.getHeight(), properties.getDepth(), properties.getFreq(), properties.getFullscreen()); display.setTitle("Joint Animation"); cam = display.getRenderer().getCamera( properties.getWidth(), properties.getHeight()); } catch (JmeException e) { e.printStackTrace(); System.exit(1); } ColorRGBA blackColor = new ColorRGBA(); blackColor.r = 0; blackColor.g = 0; blackColor.b = 0; display.getRenderer().setBackgroundColor(blackColor); cam.setFrustum(1.0f, 1000.0f, -0.55f, 0.55f, 0.4125f, -0.4125f); Vector3f loc = new Vector3f(0.0f, 0.0f, 200.0f); Vector3f left = new Vector3f(-1.0f, 0.0f, 0.0f); Vector3f up = new Vector3f(0.0f, 1.0f, 0.0f); Vector3f dir = new Vector3f(0.0f, 0f, -1.0f); cam.setFrame(loc, left, up, dir); display.getRenderer().setCamera(cam); input = new FirstPersonController(this, cam, "LWJGL"); timer = Timer.getTimer("LWJGL"); } /** * set up the scene * @see com.jme.app.AbstractGame#initGame() */ protected void initGame() { ZBufferState zstate = display.getRenderer().getZBufferState(); zstate.setEnabled(true); - scene = new Node("Milkshape Model"); + scene = new Node("Model"); scene.setRenderState(zstate); - model = new MilkshapeASCIIModel("data/model/msascii/run.txt"); + model = new MilkshapeASCIIModel("Milkshape Model","data/model/msascii/run.txt"); model.getAnimationController().setFrequency(10.0f); model.getAnimationController().setRepeatType(Controller.RT_CYCLE); scene.attachChild(model); SpotLight am = new SpotLight(); am.setDiffuse(new ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f)); am.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am.setDirection(new Vector3f(0, 0, 0)); am.setLocation(new Vector3f(25, 10, 0)); am.setAngle(15); SpotLight am2 = new SpotLight(); am2.setDiffuse(new ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f)); am2.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am2.setDirection(new Vector3f(0, 0, 0)); am2.setLocation(new Vector3f(-25, 10, 0)); am2.setAngle(15); DirectionalLight dr = new DirectionalLight(); dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); dr.setDirection(new Vector3f(0, 0 , -150)); LightState state = display.getRenderer().getLightState(); state.setEnabled(true); state.attach(am); state.attach(dr); state.attach(am2); am.setEnabled(true); am2.setEnabled(true); dr.setEnabled(true); scene.setRenderState(state); cam.update(); scene.updateGeometricState(0,true); } /** * not used. * @see com.jme.app.AbstractGame#reinit() */ protected void reinit() { } /** * not used. * @see com.jme.app.AbstractGame#cleanup() */ protected void cleanup() { } public static void main(String[] args) { TestMilkshapeASCII app = new TestMilkshapeASCII(); app.setDialogBehaviour(ALWAYS_SHOW_PROPS_DIALOG); app.start(); } }
false
true
protected void initGame() { ZBufferState zstate = display.getRenderer().getZBufferState(); zstate.setEnabled(true); scene = new Node("Milkshape Model"); scene.setRenderState(zstate); model = new MilkshapeASCIIModel("data/model/msascii/run.txt"); model.getAnimationController().setFrequency(10.0f); model.getAnimationController().setRepeatType(Controller.RT_CYCLE); scene.attachChild(model); SpotLight am = new SpotLight(); am.setDiffuse(new ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f)); am.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am.setDirection(new Vector3f(0, 0, 0)); am.setLocation(new Vector3f(25, 10, 0)); am.setAngle(15); SpotLight am2 = new SpotLight(); am2.setDiffuse(new ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f)); am2.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am2.setDirection(new Vector3f(0, 0, 0)); am2.setLocation(new Vector3f(-25, 10, 0)); am2.setAngle(15); DirectionalLight dr = new DirectionalLight(); dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); dr.setDirection(new Vector3f(0, 0 , -150)); LightState state = display.getRenderer().getLightState(); state.setEnabled(true); state.attach(am); state.attach(dr); state.attach(am2); am.setEnabled(true); am2.setEnabled(true); dr.setEnabled(true); scene.setRenderState(state); cam.update(); scene.updateGeometricState(0,true); }
protected void initGame() { ZBufferState zstate = display.getRenderer().getZBufferState(); zstate.setEnabled(true); scene = new Node("Model"); scene.setRenderState(zstate); model = new MilkshapeASCIIModel("Milkshape Model","data/model/msascii/run.txt"); model.getAnimationController().setFrequency(10.0f); model.getAnimationController().setRepeatType(Controller.RT_CYCLE); scene.attachChild(model); SpotLight am = new SpotLight(); am.setDiffuse(new ColorRGBA(0.0f, 1.0f, 0.0f, 1.0f)); am.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am.setDirection(new Vector3f(0, 0, 0)); am.setLocation(new Vector3f(25, 10, 0)); am.setAngle(15); SpotLight am2 = new SpotLight(); am2.setDiffuse(new ColorRGBA(1.0f, 0.0f, 0.0f, 1.0f)); am2.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); am2.setDirection(new Vector3f(0, 0, 0)); am2.setLocation(new Vector3f(-25, 10, 0)); am2.setAngle(15); DirectionalLight dr = new DirectionalLight(); dr.setDiffuse(new ColorRGBA(1.0f, 1.0f, 1.0f, 1.0f)); dr.setAmbient(new ColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)); dr.setDirection(new Vector3f(0, 0 , -150)); LightState state = display.getRenderer().getLightState(); state.setEnabled(true); state.attach(am); state.attach(dr); state.attach(am2); am.setEnabled(true); am2.setEnabled(true); dr.setEnabled(true); scene.setRenderState(state); cam.update(); scene.updateGeometricState(0,true); }
diff --git a/src/paulscode/android/mupen64plusae/CoreInterface.java b/src/paulscode/android/mupen64plusae/CoreInterface.java index 55d00668..2dc50d6c 100644 --- a/src/paulscode/android/mupen64plusae/CoreInterface.java +++ b/src/paulscode/android/mupen64plusae/CoreInterface.java @@ -1,574 +1,575 @@ /** * Mupen64PlusAE, an N64 emulator for the Android platform * * Copyright (C) 2013 Paul Lamb * * This file is part of Mupen64PlusAE. * * Mupen64PlusAE is free software: you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Mupen64PlusAE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with Mupen64PlusAE. If * not, see <http://www.gnu.org/licenses/>. * * Authors: Paul Lamb, littleguy77 */ package paulscode.android.mupen64plusae; import java.io.File; import java.util.ArrayList; import java.util.Locale; import paulscode.android.mupen64plusae.persistent.AppData; import paulscode.android.mupen64plusae.persistent.ConfigFile; import paulscode.android.mupen64plusae.persistent.UserPrefs; import paulscode.android.mupen64plusae.util.ErrorLogger; import paulscode.android.mupen64plusae.util.FileUtil; import paulscode.android.mupen64plusae.util.Notifier; import paulscode.android.mupen64plusae.util.SafeMethods; import paulscode.android.mupen64plusae.util.Utility; import android.annotation.TargetApi; import android.app.Activity; import android.content.pm.ActivityInfo; import android.graphics.PixelFormat; import android.media.AudioTrack; import android.os.Vibrator; import android.util.Log; /** * A class that consolidates all interactions with the emulator core. * <p/> * It uses a simple startup/shutdown semantic to ensure all objects are properly synchronized before * the core launches. This is much cleaner and safer than using public static fields (i.e. globals), * since client code need not know how and when to update each global object. * * @see CoreInterfaceNative */ public class CoreInterface { public interface OnStateCallbackListener { /** * Called when an emulator state/parameter has changed * * @param paramChanged The parameter ID. * @param newValue The new value of the parameter. */ public void onStateCallback( int paramChanged, int newValue ); } public interface OnFpsChangedListener { /** * Called when the frame rate has changed. * * @param newValue The new FPS value. */ public void onFpsChanged( int newValue ); } // Public constants // @formatter:off public static final int EMULATOR_STATE_UNKNOWN = 0; public static final int EMULATOR_STATE_STOPPED = 1; public static final int EMULATOR_STATE_RUNNING = 2; public static final int EMULATOR_STATE_PAUSED = 3; public static final int M64CORE_EMU_STATE = 1; public static final int M64CORE_VIDEO_MODE = 2; public static final int M64CORE_SAVESTATE_SLOT = 3; public static final int M64CORE_SPEED_FACTOR = 4; public static final int M64CORE_SPEED_LIMITER = 5; public static final int M64CORE_VIDEO_SIZE = 6; public static final int M64CORE_AUDIO_VOLUME = 7; public static final int M64CORE_AUDIO_MUTE = 8; public static final int M64CORE_INPUT_GAMESHARK = 9; public static final int M64CORE_STATE_LOADCOMPLETE = 10; public static final int M64CORE_STATE_SAVECOMPLETE = 11; public static final int PAK_TYPE_NONE = 1; public static final int PAK_TYPE_MEMORY = 2; public static final int PAK_TYPE_RUMBLE = 5; // @formatter:on // Private constants protected static final long VIBRATE_TIMEOUT = 1000; protected static final int COMMAND_CHANGE_TITLE = 1; // External objects from Java side protected static Activity sActivity = null; protected static GameSurface sSurface = null; protected static final Vibrator[] sVibrators = new Vibrator[4]; protected static AppData sAppData = null; protected static UserPrefs sUserPrefs = null; protected static OnStateCallbackListener sStateCallbackListener = null; // Internal flags/caches protected static boolean sIsRestarting = false; protected static String sCheatOptions = null; // Threading objects protected static Thread sCoreThread; protected static Thread sAudioThread = null; protected static final Object sStateCallbackLock = new Object(); // Audio objects protected static AudioTrack sAudioTrack = null; // Frame rate listener protected static OnFpsChangedListener sFpsListener; protected static int sFpsRecalcPeriod = 0; protected static int sFrameCount = -1; protected static long sLastFpsTime = 0; public static void refresh( Activity activity, GameSurface surface ) { sActivity = activity; sSurface = surface; sAppData = new AppData( sActivity ); sUserPrefs = new UserPrefs( sActivity ); syncConfigFiles( sUserPrefs, sAppData ); } @TargetApi( 11 ) public static void registerVibrator( int player, Vibrator vibrator ) { boolean isUseable = AppData.IS_HONEYCOMB ? vibrator.hasVibrator() : true; if( isUseable && player > 0 && player < 5 ) { sVibrators[player - 1] = vibrator; } } public static void setOnStateCallbackListener( OnStateCallbackListener listener ) { synchronized( sStateCallbackLock ) { sStateCallbackListener = listener; } } public static void setOnFpsChangedListener( OnFpsChangedListener fpsListener, int fpsRecalcPeriod ) { sFpsListener = fpsListener; sFpsRecalcPeriod = fpsRecalcPeriod; } public static void setStartupMode( String cheatArgs, boolean isRestarting ) { if( cheatArgs != null && isRestarting ) sCheatOptions = cheatArgs; // Restart game with selected cheats else sCheatOptions = null; sIsRestarting = isRestarting; } public static void startupEmulator() { if( sCoreThread == null ) { // Start the core thread if not already running sCoreThread = new Thread( new Runnable() { @Override public void run() { // Initialize input-android plugin if and only if it is selected // TODO: Find a more elegant solution, and be careful about lib name change if( sUserPrefs.inputPlugin.name.equals( "libinput-android.so" ) ) { CoreInterfaceNative.jniInitInput(); CoreInterfaceNative.setControllerConfig( 0, sUserPrefs.isPlugged1, sUserPrefs.getPakType( 1 ) ); CoreInterfaceNative.setControllerConfig( 1, sUserPrefs.isPlugged2, sUserPrefs.getPakType( 2 ) ); CoreInterfaceNative.setControllerConfig( 2, sUserPrefs.isPlugged3, sUserPrefs.getPakType( 3 ) ); CoreInterfaceNative.setControllerConfig( 3, sUserPrefs.isPlugged4, sUserPrefs.getPakType( 4 ) ); } ArrayList<String> arglist = new ArrayList<String>(); arglist.add( "mupen64plus" ); arglist.add( "--configdir" ); arglist.add( sAppData.dataDir ); if( !sUserPrefs.isFramelimiterEnabled ) { arglist.add( "--nospeedlimit" ); } if( sCheatOptions != null ) { arglist.add( "--cheats" ); arglist.add( sCheatOptions ); } arglist.add( getROMPath() ); CoreInterfaceNative.sdlInit( arglist.toArray() ); } }, "CoreThread" ); sCoreThread.start(); // Wait for the emulator to start running waitForEmuState( CoreInterface.EMULATOR_STATE_RUNNING ); // Auto-load state and resume if( !sIsRestarting ) { // Clear the flag so that subsequent calls don't reset sIsRestarting = false; Notifier.showToast( sActivity, R.string.toast_loadingSession ); CoreInterfaceNative.emuLoadFile( sUserPrefs.selectedGameAutoSavefile ); } resumeEmulator(); } } public static void shutdownEmulator() { if( sCoreThread != null ) { // Pause and auto-save state pauseEmulator( true ); // Tell the core to quit CoreInterfaceNative.sdlQuit(); // Now wait for the core thread to quit try { sCoreThread.join(); } catch( InterruptedException e ) { Log.i( "CoreInterface", "Problem stopping core thread: " + e ); } sCoreThread = null; } // Clean up other resources CoreInterfaceNative.audioQuit(); } public static void resumeEmulator() { if( sCoreThread != null ) { CoreInterfaceNative.emuResume(); } } public static void pauseEmulator( boolean autoSave ) { if( sCoreThread != null ) { CoreInterfaceNative.emuPause(); // Auto-save in case device doesn't resume properly (e.g. OS kills process, battery dies, etc.) if( autoSave ) { Notifier.showToast( sActivity, R.string.toast_savingSession ); CoreInterfaceNative.emuSaveFile( sUserPrefs.selectedGameAutoSavefile ); } } } public static void onResize( int format, int width, int height ) { // Pixel format constants changed in SDL changesets 6683, 6957 (C, Java) on SDL 2.0 branch if( CoreInterfaceNative.sdlVersionAtLeast( 2, 0, 0 ) ) { onResize_2_0( format, width, height ); } else { onResize_1_3( format, width, height ); } } @SuppressWarnings( "deprecation" ) private static void onResize_1_3( int format, int width, int height ) { // SDL 1.3 int sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 by default switch( format ) { case PixelFormat.A_8: break; case PixelFormat.LA_88: break; case PixelFormat.L_8: break; case PixelFormat.RGBA_4444: sdlFormat = 0x85421002; // SDL_PIXELFORMAT_RGBA4444 break; case PixelFormat.RGBA_5551: sdlFormat = 0x85441002; // SDL_PIXELFORMAT_RGBA5551 break; case PixelFormat.RGBA_8888: sdlFormat = 0x86462004; // SDL_PIXELFORMAT_RGBA8888 break; case PixelFormat.RGBX_8888: sdlFormat = 0x86262004; // SDL_PIXELFORMAT_RGBX8888 break; case PixelFormat.RGB_332: sdlFormat = 0x84110801; // SDL_PIXELFORMAT_RGB332 break; case PixelFormat.RGB_565: sdlFormat = 0x85151002; // SDL_PIXELFORMAT_RGB565 break; case PixelFormat.RGB_888: // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? sdlFormat = 0x86161804; // SDL_PIXELFORMAT_RGB888 break; case PixelFormat.OPAQUE: /* * TODO: Not sure this is right, Android API says, * "System chooses an opaque format", but how do we know which one?? */ break; default: Log.w( "CoreInterface", "Pixel format unknown: " + format ); break; } CoreInterfaceNative.sdlOnResize( width, height, sdlFormat ); } @SuppressWarnings( "deprecation" ) private static void onResize_2_0( int format, int width, int height ) { // SDL 2.0 int sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 by default switch( format ) { case PixelFormat.A_8: break; case PixelFormat.LA_88: break; case PixelFormat.L_8: break; case PixelFormat.RGBA_4444: sdlFormat = 0x15421002; // SDL_PIXELFORMAT_RGBA4444 break; case PixelFormat.RGBA_5551: sdlFormat = 0x15441002; // SDL_PIXELFORMAT_RGBA5551 break; case PixelFormat.RGBA_8888: sdlFormat = 0x16462004; // SDL_PIXELFORMAT_RGBA8888 break; case PixelFormat.RGBX_8888: sdlFormat = 0x16261804; // SDL_PIXELFORMAT_RGBX8888 break; case PixelFormat.RGB_332: sdlFormat = 0x14110801; // SDL_PIXELFORMAT_RGB332 break; case PixelFormat.RGB_565: sdlFormat = 0x15151002; // SDL_PIXELFORMAT_RGB565 break; case PixelFormat.RGB_888: // Not sure this is right, maybe SDL_PIXELFORMAT_RGB24 instead? sdlFormat = 0x16161804; // SDL_PIXELFORMAT_RGB888 break; case PixelFormat.OPAQUE: /* * TODO: Not sure this is right, Android API says, * "System chooses an opaque format", but how do we know which one?? */ break; default: Log.w( "CoreInterface", "Pixel format unknown: " + format ); break; } CoreInterfaceNative.sdlOnResize( width, height, sdlFormat ); } public static void waitForEmuState( final int state ) { final Object lock = new Object(); setOnStateCallbackListener( new OnStateCallbackListener() { @Override public void onStateCallback( int paramChanged, int newValue ) { if( paramChanged == M64CORE_EMU_STATE && newValue == state ) { setOnStateCallbackListener( null ); synchronized( lock ) { lock.notify(); } } } } ); synchronized( lock ) { try { lock.wait(); } catch( InterruptedException ignored ) { } } } /** * Populates the core configuration files with the user preferences. */ private static void syncConfigFiles( UserPrefs user, AppData appData ) { //@formatter:off // GLES2N64 config file ConfigFile gles2n64_conf = new ConfigFile( appData.gles2n64_conf ); gles2n64_conf.put( "[<sectionless!>]", "enable fog", booleanToString( user.isGles2N64FogEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "enable alpha test", booleanToString( user.isGles2N64AlphaTestEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "force screen clear", booleanToString( user.isGles2N64ScreenClearEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "hack z", booleanToString( !user.isGles2N64DepthTestEnabled ) ); // hack z enabled means that depth test is disabled // GLES2GLIDE64 config file ConfigFile gles2glide64_conf = new ConfigFile( appData.gles2glide64_conf ); if( user.isStretched ) gles2glide64_conf.put( "DEFAULT", "aspect", "2" ); else gles2glide64_conf.put( "DEFAULT", "aspect", "0" ); // Core and GLES2RICE config file ConfigFile mupen64plus_cfg = new ConfigFile( appData.mupen64plus_cfg ); mupen64plus_cfg.put( "Core", "Version", "1.00" ); mupen64plus_cfg.put( "Core", "OnScreenDisplay", "False" ); mupen64plus_cfg.put( "Core", "R4300Emulator", user.r4300Emulator ); mupen64plus_cfg.put( "Core", "NoCompiledJump", "False" ); mupen64plus_cfg.put( "Core", "DisableExtraMem", "False" ); mupen64plus_cfg.put( "Core", "AutoStateSlotIncrement", "False" ); mupen64plus_cfg.put( "Core", "EnableDebugger", "False" ); mupen64plus_cfg.put( "Core", "CurrentStateSlot", "0" ); mupen64plus_cfg.put( "Core", "ScreenshotPath", "\"\"" ); mupen64plus_cfg.put( "Core", "SaveStatePath", '"' + user.slotSaveDir + '"' ); mupen64plus_cfg.put( "Core", "SharedDataPath", "\"\"" ); mupen64plus_cfg.put( "CoreEvents", "Version", "1.00" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Stop", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fullscreen", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Save State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Load State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increment Slot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Reset", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Down", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Up", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Screenshot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Pause", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Mute", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increase Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Decrease Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fast Forward", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Frame Advance", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Gameshark", "0" ); mupen64plus_cfg.put( "Audio-SDL", "Version", "1.00" ); mupen64plus_cfg.put( "Audio-SDL", "SWAP_CHANNELS", booleanToString( user.audioSwapChannels ) ); mupen64plus_cfg.put( "Audio-SDL", "RESAMPLE", user.audioResampleAlg); mupen64plus_cfg.put( "UI-Console", "Version", "1.00" ); mupen64plus_cfg.put( "UI-Console", "PluginDir", '"' + appData.libsDir + '"' ); mupen64plus_cfg.put( "UI-Console", "VideoPlugin", '"' + user.videoPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "AudioPlugin", '"' + user.audioPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "InputPlugin", '"' + user.inputPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "RspPlugin", '"' + user.rspPlugin.path + '"' ); mupen64plus_cfg.put( "Video-General", "Version", "1.00" ); if( user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT ) { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.y ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.x ) ); } else { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.x ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.y ) ); } + mupen64plus_cfg.put( "Video-General", "VerticalSync", Integer.toString( 0 ) ); mupen64plus_cfg.put( "Video-Rice", "Version", "1.00" ); mupen64plus_cfg.put( "Video-Rice", "SkipFrame", booleanToString( user.isGles2RiceAutoFrameskipEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureLoading", booleanToString( user.isGles2RiceFastTextureLoadingEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureCRC", booleanToString( user.isGles2RiceFastTextureCrcEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "LoadHiResTextures", booleanToString( user.isGles2RiceHiResTexturesEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "Mipmapping", user.gles2RiceMipmappingAlg ); mupen64plus_cfg.put( "Video-Rice", "ScreenUpdateSetting", user.gles2RiceScreenUpdateType ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancement", user.gles2RiceTextureEnhancement ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancementControl", "1" ); if( user.isGles2RiceForceTextureFilterEnabled ) mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "2"); else mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "0"); gles2n64_conf.save(); gles2glide64_conf.save(); mupen64plus_cfg.save(); //@formatter:on } private static String booleanToString( boolean b ) { return b ? "1" : "0"; } private static String getROMPath() { String selectedGame = sUserPrefs.selectedGame; boolean isSelectedGameNull = selectedGame == null || !( new File( selectedGame ) ).exists(); boolean isSelectedGameZipped = !isSelectedGameNull && selectedGame.length() >= 5 && selectedGame.toLowerCase( Locale.US ).endsWith( ".zip" ); if( sActivity == null ) return null; if( isSelectedGameNull ) { SafeMethods.exit( "Invalid ROM", sActivity, 2000 ); } else if( isSelectedGameZipped ) { // Create the temp folder if it doesn't exist: String tmpFolderName = sAppData.dataDir + "/tmp"; File tmpFolder = new File( tmpFolderName ); tmpFolder.mkdir(); // Clear the folder if anything is in there: String[] children = tmpFolder.list(); for( String child : children ) { FileUtil.deleteFolder( new File( tmpFolder, child ) ); } // Unzip the ROM String selectedGameUnzipped = Utility.unzipFirstROM( new File( selectedGame ), tmpFolderName ); if( selectedGameUnzipped == null ) { Log.v( "CoreInterface", "Cannot play zipped ROM: '" + selectedGame + "'" ); Notifier.clear(); if( ErrorLogger.hasError() ) ErrorLogger.putLastError( "OPEN_ROM", "fail_crash" ); // Kick back out to the main menu sActivity.finish(); } else { return selectedGameUnzipped; } } return selectedGame; } }
true
true
private static void syncConfigFiles( UserPrefs user, AppData appData ) { //@formatter:off // GLES2N64 config file ConfigFile gles2n64_conf = new ConfigFile( appData.gles2n64_conf ); gles2n64_conf.put( "[<sectionless!>]", "enable fog", booleanToString( user.isGles2N64FogEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "enable alpha test", booleanToString( user.isGles2N64AlphaTestEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "force screen clear", booleanToString( user.isGles2N64ScreenClearEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "hack z", booleanToString( !user.isGles2N64DepthTestEnabled ) ); // hack z enabled means that depth test is disabled // GLES2GLIDE64 config file ConfigFile gles2glide64_conf = new ConfigFile( appData.gles2glide64_conf ); if( user.isStretched ) gles2glide64_conf.put( "DEFAULT", "aspect", "2" ); else gles2glide64_conf.put( "DEFAULT", "aspect", "0" ); // Core and GLES2RICE config file ConfigFile mupen64plus_cfg = new ConfigFile( appData.mupen64plus_cfg ); mupen64plus_cfg.put( "Core", "Version", "1.00" ); mupen64plus_cfg.put( "Core", "OnScreenDisplay", "False" ); mupen64plus_cfg.put( "Core", "R4300Emulator", user.r4300Emulator ); mupen64plus_cfg.put( "Core", "NoCompiledJump", "False" ); mupen64plus_cfg.put( "Core", "DisableExtraMem", "False" ); mupen64plus_cfg.put( "Core", "AutoStateSlotIncrement", "False" ); mupen64plus_cfg.put( "Core", "EnableDebugger", "False" ); mupen64plus_cfg.put( "Core", "CurrentStateSlot", "0" ); mupen64plus_cfg.put( "Core", "ScreenshotPath", "\"\"" ); mupen64plus_cfg.put( "Core", "SaveStatePath", '"' + user.slotSaveDir + '"' ); mupen64plus_cfg.put( "Core", "SharedDataPath", "\"\"" ); mupen64plus_cfg.put( "CoreEvents", "Version", "1.00" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Stop", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fullscreen", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Save State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Load State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increment Slot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Reset", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Down", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Up", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Screenshot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Pause", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Mute", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increase Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Decrease Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fast Forward", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Frame Advance", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Gameshark", "0" ); mupen64plus_cfg.put( "Audio-SDL", "Version", "1.00" ); mupen64plus_cfg.put( "Audio-SDL", "SWAP_CHANNELS", booleanToString( user.audioSwapChannels ) ); mupen64plus_cfg.put( "Audio-SDL", "RESAMPLE", user.audioResampleAlg); mupen64plus_cfg.put( "UI-Console", "Version", "1.00" ); mupen64plus_cfg.put( "UI-Console", "PluginDir", '"' + appData.libsDir + '"' ); mupen64plus_cfg.put( "UI-Console", "VideoPlugin", '"' + user.videoPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "AudioPlugin", '"' + user.audioPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "InputPlugin", '"' + user.inputPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "RspPlugin", '"' + user.rspPlugin.path + '"' ); mupen64plus_cfg.put( "Video-General", "Version", "1.00" ); if( user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT ) { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.y ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.x ) ); } else { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.x ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.y ) ); } mupen64plus_cfg.put( "Video-Rice", "Version", "1.00" ); mupen64plus_cfg.put( "Video-Rice", "SkipFrame", booleanToString( user.isGles2RiceAutoFrameskipEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureLoading", booleanToString( user.isGles2RiceFastTextureLoadingEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureCRC", booleanToString( user.isGles2RiceFastTextureCrcEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "LoadHiResTextures", booleanToString( user.isGles2RiceHiResTexturesEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "Mipmapping", user.gles2RiceMipmappingAlg ); mupen64plus_cfg.put( "Video-Rice", "ScreenUpdateSetting", user.gles2RiceScreenUpdateType ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancement", user.gles2RiceTextureEnhancement ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancementControl", "1" ); if( user.isGles2RiceForceTextureFilterEnabled ) mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "2"); else mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "0"); gles2n64_conf.save(); gles2glide64_conf.save(); mupen64plus_cfg.save(); //@formatter:on }
private static void syncConfigFiles( UserPrefs user, AppData appData ) { //@formatter:off // GLES2N64 config file ConfigFile gles2n64_conf = new ConfigFile( appData.gles2n64_conf ); gles2n64_conf.put( "[<sectionless!>]", "enable fog", booleanToString( user.isGles2N64FogEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "enable alpha test", booleanToString( user.isGles2N64AlphaTestEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "force screen clear", booleanToString( user.isGles2N64ScreenClearEnabled ) ); gles2n64_conf.put( "[<sectionless!>]", "hack z", booleanToString( !user.isGles2N64DepthTestEnabled ) ); // hack z enabled means that depth test is disabled // GLES2GLIDE64 config file ConfigFile gles2glide64_conf = new ConfigFile( appData.gles2glide64_conf ); if( user.isStretched ) gles2glide64_conf.put( "DEFAULT", "aspect", "2" ); else gles2glide64_conf.put( "DEFAULT", "aspect", "0" ); // Core and GLES2RICE config file ConfigFile mupen64plus_cfg = new ConfigFile( appData.mupen64plus_cfg ); mupen64plus_cfg.put( "Core", "Version", "1.00" ); mupen64plus_cfg.put( "Core", "OnScreenDisplay", "False" ); mupen64plus_cfg.put( "Core", "R4300Emulator", user.r4300Emulator ); mupen64plus_cfg.put( "Core", "NoCompiledJump", "False" ); mupen64plus_cfg.put( "Core", "DisableExtraMem", "False" ); mupen64plus_cfg.put( "Core", "AutoStateSlotIncrement", "False" ); mupen64plus_cfg.put( "Core", "EnableDebugger", "False" ); mupen64plus_cfg.put( "Core", "CurrentStateSlot", "0" ); mupen64plus_cfg.put( "Core", "ScreenshotPath", "\"\"" ); mupen64plus_cfg.put( "Core", "SaveStatePath", '"' + user.slotSaveDir + '"' ); mupen64plus_cfg.put( "Core", "SharedDataPath", "\"\"" ); mupen64plus_cfg.put( "CoreEvents", "Version", "1.00" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Stop", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fullscreen", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Save State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Load State", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increment Slot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Reset", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Down", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Speed Up", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Screenshot", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Pause", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Mute", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Increase Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Decrease Volume", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Fast Forward", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Frame Advance", "0" ); mupen64plus_cfg.put( "CoreEvents", "Kbd Mapping Gameshark", "0" ); mupen64plus_cfg.put( "Audio-SDL", "Version", "1.00" ); mupen64plus_cfg.put( "Audio-SDL", "SWAP_CHANNELS", booleanToString( user.audioSwapChannels ) ); mupen64plus_cfg.put( "Audio-SDL", "RESAMPLE", user.audioResampleAlg); mupen64plus_cfg.put( "UI-Console", "Version", "1.00" ); mupen64plus_cfg.put( "UI-Console", "PluginDir", '"' + appData.libsDir + '"' ); mupen64plus_cfg.put( "UI-Console", "VideoPlugin", '"' + user.videoPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "AudioPlugin", '"' + user.audioPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "InputPlugin", '"' + user.inputPlugin.path + '"' ); mupen64plus_cfg.put( "UI-Console", "RspPlugin", '"' + user.rspPlugin.path + '"' ); mupen64plus_cfg.put( "Video-General", "Version", "1.00" ); if( user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT || user.videoOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT ) { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.y ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.x ) ); } else { gles2n64_conf.put( "[<sectionless!>]", "window width", Integer.toString( appData.screenSize.x ) ); gles2n64_conf.put( "[<sectionless!>]", "window height", Integer.toString( appData.screenSize.y ) ); mupen64plus_cfg.put( "Video-General", "ScreenWidth", Integer.toString( appData.screenSize.x ) ); mupen64plus_cfg.put( "Video-General", "ScreenHeight", Integer.toString( appData.screenSize.y ) ); } mupen64plus_cfg.put( "Video-General", "VerticalSync", Integer.toString( 0 ) ); mupen64plus_cfg.put( "Video-Rice", "Version", "1.00" ); mupen64plus_cfg.put( "Video-Rice", "SkipFrame", booleanToString( user.isGles2RiceAutoFrameskipEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureLoading", booleanToString( user.isGles2RiceFastTextureLoadingEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "FastTextureCRC", booleanToString( user.isGles2RiceFastTextureCrcEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "LoadHiResTextures", booleanToString( user.isGles2RiceHiResTexturesEnabled ) ); mupen64plus_cfg.put( "Video-Rice", "Mipmapping", user.gles2RiceMipmappingAlg ); mupen64plus_cfg.put( "Video-Rice", "ScreenUpdateSetting", user.gles2RiceScreenUpdateType ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancement", user.gles2RiceTextureEnhancement ); mupen64plus_cfg.put( "Video-Rice", "TextureEnhancementControl", "1" ); if( user.isGles2RiceForceTextureFilterEnabled ) mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "2"); else mupen64plus_cfg.put( "Video-Rice", "ForceTextureFilter", "0"); gles2n64_conf.save(); gles2glide64_conf.save(); mupen64plus_cfg.save(); //@formatter:on }
diff --git a/server/src/test/java/org/uiautomation/ios/e2e/IDETests.java b/server/src/test/java/org/uiautomation/ios/e2e/IDETests.java index 688f52ce..1b5453c2 100644 --- a/server/src/test/java/org/uiautomation/ios/e2e/IDETests.java +++ b/server/src/test/java/org/uiautomation/ios/e2e/IDETests.java @@ -1,20 +1,20 @@ package org.uiautomation.ios.e2e; import org.uiautomation.ios.server.IOSServer; import org.uiautomation.ios.server.IOSServerConfiguration; public class IDETests { private static IOSServer server; private static String[] args = {"-port", "4444", "-host", "localhost"}; private static IOSServerConfiguration config = IOSServerConfiguration.create(args); public static void main(String[] args) throws Exception { server = new IOSServer(config); - server.init(config); + server.init(); server.start(); System.out.println("started"); } }
true
true
public static void main(String[] args) throws Exception { server = new IOSServer(config); server.init(config); server.start(); System.out.println("started"); }
public static void main(String[] args) throws Exception { server = new IOSServer(config); server.init(); server.start(); System.out.println("started"); }
diff --git a/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/UserViews/SignCert.java b/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/UserViews/SignCert.java index 61430ad..fdf252c 100644 --- a/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/UserViews/SignCert.java +++ b/org.jcryptool.visual.jctca/src/org/jcryptool/visual/jctca/UserViews/SignCert.java @@ -1,170 +1,170 @@ package org.jcryptool.visual.jctca.UserViews; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Text; import org.jcryptool.crypto.keystore.backend.KeyStoreAlias; import org.jcryptool.crypto.keystore.backend.KeyStoreManager; import org.jcryptool.crypto.keystore.keys.IKeyStoreAlias; import org.jcryptool.visual.jctca.Util; import org.jcryptool.visual.jctca.listeners.RadioButtonListener; import org.jcryptool.visual.jctca.listeners.SelectFileListener; import org.jcryptool.visual.jctca.listeners.SigVisPluginOpenListener; public class SignCert implements Views { Color dark_gray = Display.getDefault().getSystemColor( SWT.COLOR_DARK_GRAY); Composite composite; Combo cmb_priv_key; Group selectSthGroup; Label selected_file; public SignCert(Composite content, Composite exp) { this.composite = new Composite(content, SWT.NONE); this.composite.setLayout(new GridLayout(1, false)); GridData gd_comp = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(gd_comp); Group cmp_mini = new Group(composite, SWT.NONE); cmp_mini.setLayout(new GridLayout(2,false)); cmp_mini.setLayoutData(gd_comp); cmp_mini.setText(Messages.SignCert_chose_method); selectSthGroup = new Group (composite, SWT.None); selectSthGroup.setLayout(new GridLayout(1, false)); selectSthGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); selectSthGroup.setText(Messages.SignCert_what_to_sign); Group signCertGroup = new Group(composite, SWT.NONE); signCertGroup.setLayout(new GridLayout(1, false)); signCertGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); signCertGroup.setText(Messages.SignCert_headline); Composite signBtnComp = new Composite(composite, SWT.NONE); signBtnComp.setLayout(new GridLayout(1, false)); signBtnComp.setLayoutData(gd_comp); Composite selectSthComp = new Composite(selectSthGroup, SWT.NONE); selectSthComp.setLayout(new GridLayout(3, false)); selectSthComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); Button btn_detail = new Button(cmp_mini, SWT.RADIO); btn_detail.setText(Messages.SignCert_checkbox_show_sigvis); btn_detail.setData("detail"); //$NON-NLS-1$ btn_detail.setSelection(true); Button btn_non_detail = new Button(cmp_mini, SWT.RADIO); btn_non_detail.setText(Messages.SignCert_sign_directly); btn_non_detail.setData("detail"); //$NON-NLS-1$ Composite cmp_minimi = new Composite(cmp_mini, SWT.NONE); cmp_minimi.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 2,1)); cmp_minimi.setLayout(new GridLayout(2, false)); Label filler = new Label(cmp_minimi, SWT.None); filler.setText(""); //$NON-NLS-1$ GridData gd = new GridData(); gd.widthHint=7; filler.setLayoutData(gd); Label lbl_detail = new Label(cmp_minimi, SWT.WRAP); lbl_detail.setText(Messages.SignCert_footnote_input_in_signvis); lbl_detail.setForeground(dark_gray); lbl_detail.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 1,1)); Button btn_radio_signFile = new Button(selectSthComp, SWT.RADIO); btn_radio_signFile.setText(Messages.SignCert_file); btn_radio_signFile.setData("file"); //$NON-NLS-1$ btn_radio_signFile.setEnabled(false); Button btn_select_file = new Button(selectSthComp, SWT.PUSH); btn_select_file.setText(Messages.SignCert_btn_chose_file); btn_select_file.setData("select");//$NON-NLS-1$ btn_select_file.setEnabled(false); selected_file = new Label(selectSthComp, SWT.NONE); //selectSthGroup selected_file.setText(""); //$NON-NLS-1$ selected_file.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); GridData gd_btn = new GridData(); Button btn_radio_signText = new Button(selectSthComp, SWT.RADIO); btn_radio_signText.setText(Messages.SignCert_text); btn_radio_signText.setData("text"); //$NON-NLS-1$ btn_radio_signText.setLayoutData(gd_btn); btn_radio_signText.setEnabled(false); GridData gd_txt = new GridData(SWT.FILL, SWT.FILL, false, true, 2,20); Text txt_sign = new Text(selectSthComp, SWT.LEFT | SWT.MULTI | SWT.BORDER); txt_sign.setText(Messages.SignCert_textbox_sample_text); txt_sign.setLayoutData(gd_txt); txt_sign.setEnabled(false); txt_sign.setForeground(dark_gray); btn_radio_signFile.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_radio_signText.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_select_file.addSelectionListener(new SelectFileListener(selected_file, txt_sign )); - btn_non_detail.addSelectionListener(new RadioButtonListener(true, btn_radio_signFile, btn_radio_signText, btn_select_file, selected_file, txt_sign)); - btn_detail.addSelectionListener(new RadioButtonListener(false, btn_radio_signFile, btn_radio_signText, btn_select_file,selected_file, txt_sign)); + btn_non_detail.addSelectionListener(new RadioButtonListener(true, btn_radio_signFile, btn_radio_signText, btn_select_file, selected_file, txt_sign,btn_select_file)); + btn_detail.addSelectionListener(new RadioButtonListener(false, btn_radio_signFile, btn_radio_signText, btn_select_file,selected_file, txt_sign,btn_select_file)); cmb_priv_key = new Combo(signCertGroup, SWT.DROP_DOWN); cmb_priv_key.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false,1,1)); addRSAPrivateKeysToDropdown(); cmb_priv_key.select(0); Button btn_sign = new Button(signBtnComp, SWT.PUSH); btn_sign.setLayoutData(gd_comp); btn_sign.setText(Messages.SignCert_btn_sign_with_key); btn_sign.addSelectionListener(new SigVisPluginOpenListener(btn_detail, selected_file, txt_sign, cmb_priv_key)); StyledText stl_exp = (StyledText) exp.getChildren()[0]; stl_exp.setText(Messages.SignCert_explain_text); composite.setVisible(false); } private void addRSAPrivateKeysToDropdown(){ KeyStoreManager ksm = KeyStoreManager.getInstance(); for (KeyStoreAlias ksAlias : Util.getAllRSAPublicKeys(ksm)) { if (Util.isSignedByJCTCA(ksAlias) == false) { continue; } String listEntry = ksAlias.getContactName() + " (" + ksAlias.getKeyLength() + "bit "; //$NON-NLS-1$ //$NON-NLS-2$ if (ksAlias.getOperation().contains("RSA")) { //$NON-NLS-1$ listEntry += "RSA"; //$NON-NLS-1$ } listEntry+=", Hash: " + Util.formatHash(ksAlias.getHashValue()) + ")"; //$NON-NLS-1$ //$NON-NLS-2$ cmb_priv_key.setData(listEntry, ksAlias); cmb_priv_key.add(listEntry); } } @Override public void setVisible(boolean visible) { composite.setVisible(visible); } @Override public void dispose() { composite.dispose(); } }
true
true
public SignCert(Composite content, Composite exp) { this.composite = new Composite(content, SWT.NONE); this.composite.setLayout(new GridLayout(1, false)); GridData gd_comp = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(gd_comp); Group cmp_mini = new Group(composite, SWT.NONE); cmp_mini.setLayout(new GridLayout(2,false)); cmp_mini.setLayoutData(gd_comp); cmp_mini.setText(Messages.SignCert_chose_method); selectSthGroup = new Group (composite, SWT.None); selectSthGroup.setLayout(new GridLayout(1, false)); selectSthGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); selectSthGroup.setText(Messages.SignCert_what_to_sign); Group signCertGroup = new Group(composite, SWT.NONE); signCertGroup.setLayout(new GridLayout(1, false)); signCertGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); signCertGroup.setText(Messages.SignCert_headline); Composite signBtnComp = new Composite(composite, SWT.NONE); signBtnComp.setLayout(new GridLayout(1, false)); signBtnComp.setLayoutData(gd_comp); Composite selectSthComp = new Composite(selectSthGroup, SWT.NONE); selectSthComp.setLayout(new GridLayout(3, false)); selectSthComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); Button btn_detail = new Button(cmp_mini, SWT.RADIO); btn_detail.setText(Messages.SignCert_checkbox_show_sigvis); btn_detail.setData("detail"); //$NON-NLS-1$ btn_detail.setSelection(true); Button btn_non_detail = new Button(cmp_mini, SWT.RADIO); btn_non_detail.setText(Messages.SignCert_sign_directly); btn_non_detail.setData("detail"); //$NON-NLS-1$ Composite cmp_minimi = new Composite(cmp_mini, SWT.NONE); cmp_minimi.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 2,1)); cmp_minimi.setLayout(new GridLayout(2, false)); Label filler = new Label(cmp_minimi, SWT.None); filler.setText(""); //$NON-NLS-1$ GridData gd = new GridData(); gd.widthHint=7; filler.setLayoutData(gd); Label lbl_detail = new Label(cmp_minimi, SWT.WRAP); lbl_detail.setText(Messages.SignCert_footnote_input_in_signvis); lbl_detail.setForeground(dark_gray); lbl_detail.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 1,1)); Button btn_radio_signFile = new Button(selectSthComp, SWT.RADIO); btn_radio_signFile.setText(Messages.SignCert_file); btn_radio_signFile.setData("file"); //$NON-NLS-1$ btn_radio_signFile.setEnabled(false); Button btn_select_file = new Button(selectSthComp, SWT.PUSH); btn_select_file.setText(Messages.SignCert_btn_chose_file); btn_select_file.setData("select");//$NON-NLS-1$ btn_select_file.setEnabled(false); selected_file = new Label(selectSthComp, SWT.NONE); //selectSthGroup selected_file.setText(""); //$NON-NLS-1$ selected_file.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); GridData gd_btn = new GridData(); Button btn_radio_signText = new Button(selectSthComp, SWT.RADIO); btn_radio_signText.setText(Messages.SignCert_text); btn_radio_signText.setData("text"); //$NON-NLS-1$ btn_radio_signText.setLayoutData(gd_btn); btn_radio_signText.setEnabled(false); GridData gd_txt = new GridData(SWT.FILL, SWT.FILL, false, true, 2,20); Text txt_sign = new Text(selectSthComp, SWT.LEFT | SWT.MULTI | SWT.BORDER); txt_sign.setText(Messages.SignCert_textbox_sample_text); txt_sign.setLayoutData(gd_txt); txt_sign.setEnabled(false); txt_sign.setForeground(dark_gray); btn_radio_signFile.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_radio_signText.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_select_file.addSelectionListener(new SelectFileListener(selected_file, txt_sign )); btn_non_detail.addSelectionListener(new RadioButtonListener(true, btn_radio_signFile, btn_radio_signText, btn_select_file, selected_file, txt_sign)); btn_detail.addSelectionListener(new RadioButtonListener(false, btn_radio_signFile, btn_radio_signText, btn_select_file,selected_file, txt_sign)); cmb_priv_key = new Combo(signCertGroup, SWT.DROP_DOWN); cmb_priv_key.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false,1,1)); addRSAPrivateKeysToDropdown(); cmb_priv_key.select(0); Button btn_sign = new Button(signBtnComp, SWT.PUSH); btn_sign.setLayoutData(gd_comp); btn_sign.setText(Messages.SignCert_btn_sign_with_key); btn_sign.addSelectionListener(new SigVisPluginOpenListener(btn_detail, selected_file, txt_sign, cmb_priv_key)); StyledText stl_exp = (StyledText) exp.getChildren()[0]; stl_exp.setText(Messages.SignCert_explain_text); composite.setVisible(false); }
public SignCert(Composite content, Composite exp) { this.composite = new Composite(content, SWT.NONE); this.composite.setLayout(new GridLayout(1, false)); GridData gd_comp = new GridData(SWT.FILL, SWT.FILL, true, false); composite.setLayoutData(gd_comp); Group cmp_mini = new Group(composite, SWT.NONE); cmp_mini.setLayout(new GridLayout(2,false)); cmp_mini.setLayoutData(gd_comp); cmp_mini.setText(Messages.SignCert_chose_method); selectSthGroup = new Group (composite, SWT.None); selectSthGroup.setLayout(new GridLayout(1, false)); selectSthGroup.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); selectSthGroup.setText(Messages.SignCert_what_to_sign); Group signCertGroup = new Group(composite, SWT.NONE); signCertGroup.setLayout(new GridLayout(1, false)); signCertGroup.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL)); signCertGroup.setText(Messages.SignCert_headline); Composite signBtnComp = new Composite(composite, SWT.NONE); signBtnComp.setLayout(new GridLayout(1, false)); signBtnComp.setLayoutData(gd_comp); Composite selectSthComp = new Composite(selectSthGroup, SWT.NONE); selectSthComp.setLayout(new GridLayout(3, false)); selectSthComp.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.GRAB_HORIZONTAL)); Button btn_detail = new Button(cmp_mini, SWT.RADIO); btn_detail.setText(Messages.SignCert_checkbox_show_sigvis); btn_detail.setData("detail"); //$NON-NLS-1$ btn_detail.setSelection(true); Button btn_non_detail = new Button(cmp_mini, SWT.RADIO); btn_non_detail.setText(Messages.SignCert_sign_directly); btn_non_detail.setData("detail"); //$NON-NLS-1$ Composite cmp_minimi = new Composite(cmp_mini, SWT.NONE); cmp_minimi.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 2,1)); cmp_minimi.setLayout(new GridLayout(2, false)); Label filler = new Label(cmp_minimi, SWT.None); filler.setText(""); //$NON-NLS-1$ GridData gd = new GridData(); gd.widthHint=7; filler.setLayoutData(gd); Label lbl_detail = new Label(cmp_minimi, SWT.WRAP); lbl_detail.setText(Messages.SignCert_footnote_input_in_signvis); lbl_detail.setForeground(dark_gray); lbl_detail.setLayoutData(new GridData(SWT.NONE, SWT.NONE, false, false, 1,1)); Button btn_radio_signFile = new Button(selectSthComp, SWT.RADIO); btn_radio_signFile.setText(Messages.SignCert_file); btn_radio_signFile.setData("file"); //$NON-NLS-1$ btn_radio_signFile.setEnabled(false); Button btn_select_file = new Button(selectSthComp, SWT.PUSH); btn_select_file.setText(Messages.SignCert_btn_chose_file); btn_select_file.setData("select");//$NON-NLS-1$ btn_select_file.setEnabled(false); selected_file = new Label(selectSthComp, SWT.NONE); //selectSthGroup selected_file.setText(""); //$NON-NLS-1$ selected_file.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); GridData gd_btn = new GridData(); Button btn_radio_signText = new Button(selectSthComp, SWT.RADIO); btn_radio_signText.setText(Messages.SignCert_text); btn_radio_signText.setData("text"); //$NON-NLS-1$ btn_radio_signText.setLayoutData(gd_btn); btn_radio_signText.setEnabled(false); GridData gd_txt = new GridData(SWT.FILL, SWT.FILL, false, true, 2,20); Text txt_sign = new Text(selectSthComp, SWT.LEFT | SWT.MULTI | SWT.BORDER); txt_sign.setText(Messages.SignCert_textbox_sample_text); txt_sign.setLayoutData(gd_txt); txt_sign.setEnabled(false); txt_sign.setForeground(dark_gray); btn_radio_signFile.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_radio_signText.addSelectionListener(new RadioButtonListener(selected_file, txt_sign, btn_select_file)); btn_select_file.addSelectionListener(new SelectFileListener(selected_file, txt_sign )); btn_non_detail.addSelectionListener(new RadioButtonListener(true, btn_radio_signFile, btn_radio_signText, btn_select_file, selected_file, txt_sign,btn_select_file)); btn_detail.addSelectionListener(new RadioButtonListener(false, btn_radio_signFile, btn_radio_signText, btn_select_file,selected_file, txt_sign,btn_select_file)); cmb_priv_key = new Combo(signCertGroup, SWT.DROP_DOWN); cmb_priv_key.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false,1,1)); addRSAPrivateKeysToDropdown(); cmb_priv_key.select(0); Button btn_sign = new Button(signBtnComp, SWT.PUSH); btn_sign.setLayoutData(gd_comp); btn_sign.setText(Messages.SignCert_btn_sign_with_key); btn_sign.addSelectionListener(new SigVisPluginOpenListener(btn_detail, selected_file, txt_sign, cmb_priv_key)); StyledText stl_exp = (StyledText) exp.getChildren()[0]; stl_exp.setText(Messages.SignCert_explain_text); composite.setVisible(false); }
diff --git a/src/org/openmrs/module/xforms/XformObsEdit.java b/src/org/openmrs/module/xforms/XformObsEdit.java index 14e486e..387eee1 100644 --- a/src/org/openmrs/module/xforms/XformObsEdit.java +++ b/src/org/openmrs/module/xforms/XformObsEdit.java @@ -1,745 +1,747 @@ package org.openmrs.module.xforms; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.lang.reflect.Method; import java.text.DateFormat; import java.text.ParseException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Locale; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.kxml2.kdom.Document; import org.kxml2.kdom.Element; import org.openmrs.Concept; import org.openmrs.ConceptDatatype; import org.openmrs.ConceptName; import org.openmrs.Encounter; import org.openmrs.Location; import org.openmrs.Obs; import org.openmrs.Person; import org.openmrs.User; import org.openmrs.api.context.Context; import org.openmrs.module.xforms.util.DOMUtil; import org.openmrs.module.xforms.util.XformsUtil; import org.openmrs.propertyeditor.ConceptEditor; import org.openmrs.propertyeditor.LocationEditor; import org.openmrs.propertyeditor.UserEditor; import org.openmrs.util.FormConstants; import org.openmrs.util.FormUtil; import org.openmrs.util.OpenmrsUtil; import org.springframework.util.FileCopyUtils; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; /** * Utility functions and variables for editing for obs using xforms. * * @author daniel * */ public class XformObsEdit { private static final Log log = LogFactory.getLog(XformObsEdit.class); /** A mapping of xpath expressions to their complex data. */ private static HashMap<String,byte[]> complexData; /** A mapping of xpath expressions and their corresponding node names. */ private static HashMap<String,String> complexDataNodeNames; /** A list of xpath expressions for complex data which has beed edited. */ private static List<String> dirtyComplexData; public static String getMultSelObsNodeName(Element parent, Obs obs, List<String> nonCopyAttributes){ return XformBuilder.getElementByAttributePrefix(parent, "openmrs_concept",obs.getValueCoded().getConceptId()+"^", false, "obsId", true, nonCopyAttributes).getName(); } public static void fillObs(HttpServletRequest request,Document doc, Integer encounterId, String xml)throws Exception{ Element formNode = XformBuilder.getElement(doc.getRootElement(),"form"); if(formNode == null) return; Encounter encounter = Context.getEncounterService().getEncounter(encounterId); if(encounter == null) return; retrieveSessionValues(request); clearSessionData(request,encounter.getForm().getFormId()); formNode.setAttribute(null, "encounterId", encounter.getEncounterId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_LOCATION_ID, encounter.getLocation().getLocationId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_ENCOUNTER_DATETIME, XformsUtil.encounterDateIncludesTime() ? XformsUtil.fromDateTime2SubmitString(encounter.getEncounterDatetime()) : XformsUtil.fromDate2SubmitString(encounter.getEncounterDatetime())); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_PROVIDER_ID, XformsUtil.getProviderId(encounter).toString()); List<String> complexObs = DOMUtil.getXformComplexObsNodeNames(xml); HashMap<String,Element> obsGroupNodes = new HashMap<String,Element>(); List<String> nonCopyAttributes = new ArrayList<String>(); nonCopyAttributes.add("obsId"); nonCopyAttributes.add("obsGroupId"); Set<Obs> observations = encounter.getObs(); for(Obs obs : observations){ Concept concept = obs.getConcept(); //Obs obsGroup = obs.getObsGroup(); String obsGroupId = obs.getObsGroup() == null ? null : obs.getObsGroup().getObsId().toString(); //TODO This needs to do a better job by searching for an attribute that starts with //a concept id of the concept and hence remove the name dependency as the concept name //could change or may be different in a different locale. Element node = XformBuilder.getElementByAttributePrefix(formNode,"openmrs_concept", (obsGroupId == null ? concept.getConceptId() : obs.getObsGroup().getConcept()) +"^", (obsGroupId == null ? false : true), (obsGroupId == null ? "obsId" : "obsGroupId"), true, nonCopyAttributes); if(node == null) continue; //check if this is a repeating obs. if(obsGroupId != null){ String nodeGroupId = node.getAttributeValue(null, "obsGroupId"); //if this is first time to get a node of this parent. if(nodeGroupId == null || nodeGroupId.trim().length() == 0){ node.setAttribute(null, "obsGroupId", obsGroupId); //new group processing obsGroupNodes.put(obsGroupId, node); } else{ if(!nodeGroupId.equals(obsGroupId)){ Element groupNode = obsGroupNodes.get(obsGroupId); if(groupNode == null){//new group node = XformBuilder.createCopy(node, nonCopyAttributes); node.setAttribute(null, "obsGroupId", obsGroupId); obsGroupNodes.put(obsGroupId, node); }//else a kid of some other group which we processed but not necessarily being the first one. else node = groupNode; }//else another kid of an already processed group. } node = XformBuilder.getElementByAttributePrefix(node,"openmrs_concept",concept.getConceptId()+"^", false, "obsId", false, nonCopyAttributes); if(node == null) continue; } String value = obs.getValueAsString(Context.getLocale()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) value = FormUtil.conceptToString(obs.getValueCoded(), Context.getLocale()); + else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATE) && obs.getValueDatetime() != null) + value = XformsUtil.fromDate2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATETIME) && obs.getValueDatetime() != null) value = XformsUtil.fromDateTime2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.TIME) && obs.getValueDatetime() != null) value = XformsUtil.fromTime2SubmitString(obs.getValueDatetime()); if("1".equals(node.getAttributeValue(null,"multiple"))){ Element multNode = XformBuilder.getElement(node, "xforms_value"); if(multNode != null){ value = XformBuilder.getTextValue(multNode); if(value != null && value.trim().length() > 0) value += " "; else value = ""; //TODO This may fail when locale changes from the one in which the form was designed. //String xmlToken = FormUtil.getXmlToken(obs.getValueAsString(Context.getLocale())); try{ String xmlToken = getMultSelObsNodeName((Element)multNode.getParent(), obs, nonCopyAttributes); XformBuilder.setNodeValue(node, "xforms_value", value + xmlToken); //TODO May need to use getElementWithAttributePrefix() Element valueNode = XformBuilder.getElement(node, xmlToken); if(valueNode != null){ XformBuilder.setNodeValue(valueNode,"true"); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); } }catch(Exception ex){ ex.printStackTrace(); } } } else{ Element valueNode = XformBuilder.getElement(node, "value"); if(valueNode != null){ if(complexObs.contains(node.getName())){ String key = getComplexDataKey(formNode.getAttributeValue(null, "id"),"/form/obs/" + node.getName() + "/value"); value = getComplexObsValue(node.getName(),valueNode,value,key); } XformBuilder.setNodeValue(valueNode,value); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) valueNode.setAttribute(null, "displayValue", obs.getValueCoded().getName().getName()); if(obsGroupId != null) valueNode.setAttribute(null, "default", "false()"); } node.setAttribute(null, "obsId", obs.getObsId().toString()); //XformBuilder.setNodeValue(node, "value", value); } } //System.out.println(XformBuilder.fromDoc2String(doc)); } private static String getComplexObsValue(String nodeName, Element valueNode, String value, String key){ complexDataNodeNames.put(key, nodeName); if(value == null || value.trim().length() == 0) return value; try{ byte[] bytes = FileCopyUtils.copyToByteArray(new FileInputStream(value)); complexData.put(key, bytes); return Base64.encode(bytes); } catch(Exception ex){ log.error(ex); //File may be deleted, but that should not prevent loading of the form. } return value; } public static Encounter getEditedEncounter(HttpServletRequest request,Document doc,Set<Obs> obs2Void, String xml) throws Exception{ return getEditedEncounter(request,XformBuilder.getElement(doc.getRootElement(),"form"),obs2Void); } public static Encounter getEditedEncounter(HttpServletRequest request,Element formNode,Set<Obs> obs2Void) throws Exception{ if(formNode == null || !"form".equals(formNode.getName())) return null; String formId = formNode.getAttributeValue(null, "id"); retrieveSessionValues(request); clearSessionData(request,Integer.parseInt(formId)); List<String> complexObs = DOMUtil.getModelComplexObsNodeNames(formId); List<String> dirtyComplexObs = getEditedComplexObsNames(); Date datetime = new Date(); Integer encounterId = Integer.parseInt(formNode.getAttributeValue(null, "encounterId")); Encounter encounter = Context.getEncounterService().getEncounter(encounterId); setEncounterHeader(encounter,formNode); Hashtable<String,String[]> multipleSelValues = new Hashtable<String,String[]>(); Set<Obs> observations = encounter.getObs(); for(Obs obs : observations){ Concept concept = obs.getConcept(); String nodeName = FormUtil.getXmlToken(concept.getDisplayString()); Element node = XformBuilder.getElementByAttributeValue(formNode,"obsId",obs.getObsId().toString()); if(node == null){ if(obs.getObsGroup() != null) voidObs(obs.getObsGroup(),datetime,obs2Void); voidObs(obs,datetime,obs2Void); continue; } if(isMultipleSelNode((Element)node.getParent())) node = (Element)node.getParent(); if(isMultipleSelNode(node)){ String xmlToken = FormUtil.getXmlToken(obs.getValueAsString(Context.getLocale())); if(multipleSelValueContains(nodeName,xmlToken,node,multipleSelValues)) continue; voidObs(obs,datetime,obs2Void); } else{ Element valueNode = XformBuilder.getElement(node, "value"); if(valueNode != null){ String newValue = XformBuilder.getTextValue(valueNode);; String oldValue = obs.getValueAsString(Context.getLocale()); if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATETIME) && obs.getValueDatetime() != null) oldValue = XformsUtil.fromDateTime2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.TIME) && obs.getValueDatetime() != null) oldValue = XformsUtil.fromTime2SubmitString(obs.getValueDatetime()); //Deal with complex obs first if(complexObs.contains(nodeName)){ //Continue if complex obs has neither been replaced //with a another one nor cleared. if(!dirtyComplexObs.contains(nodeName) && !( (newValue == null || newValue.trim().length() == 0) && (oldValue != null && oldValue.trim().length() > 0 ) )) continue; //complex obs not modified. voidObs(obs,datetime,obs2Void); if(newValue == null || newValue.trim().length() == 0) continue; //complex obs just cleared without a replacement. newValue = saveComplexObs(nodeName,newValue,formNode); } else{ if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) oldValue = conceptToString(obs.getValueCoded(), Context.getLocale()); if(oldValue.equals(newValue)) continue; //obs has not changed voidObs(obs,datetime,obs2Void); if(newValue == null || newValue.trim().length() == 0) continue; } //setObsValue(obs,newValue); //obs.setDateChanged(datetime); //obs.setChangedBy(Context.getAuthenticatedUser()); encounter.addObs(createObs(concept,obs.getObsGroup(),newValue,datetime)); } else throw new IllegalArgumentException("cannot locate node for concept: " + concept.getDisplayString()); } } //addNewObs(formNode,complexObs,encounter,XformBuilder.getElement(formNode,"obs"),datetime,null); //addNewObs(formNode,complexObs,encounter,XformBuilder.getElement(formNode,"problem_list"),datetime,null); //Add new obs for all form sections for(int i=0; i<formNode.getChildCount(); i++){ if(formNode.getType(i) != Element.ELEMENT) continue; Element child = (Element)formNode.getChild(i); String conceptStr = child.getAttributeValue(null, "openmrs_concept"); if(conceptStr == null || conceptStr.trim().length() == 0) continue; //TODO Can't we have sections which are not concepts? addNewObs(formNode, complexObs, encounter, child, datetime, null); } return encounter; } private static void voidObs(Obs obs, Date datetime, Set<Obs> obs2Void){ obs.setVoided(true); obs.setVoidedBy(Context.getAuthenticatedUser()); obs.setDateVoided(datetime); obs.setVoidReason("xformsmodule"); //TODO Need to set this from user. obs2Void.add(obs); } private static void setEncounterHeader(Encounter encounter, Element formNode) throws Exception{ encounter.setLocation(Context.getLocationService().getLocation(Integer.valueOf(XformBuilder.getNodeValue(formNode, XformBuilder.NODE_ENCOUNTER_LOCATION_ID)))); Integer id = Integer.valueOf(XformBuilder.getNodeValue(formNode, XformBuilder.NODE_ENCOUNTER_PROVIDER_ID)); Person person = Context.getPersonService().getPerson(id); try{ Method method = encounter.getClass().getMethod("setProvider", new Class[]{Person.class}); method.invoke(encounter, new Object[]{person}); } catch(NoSuchMethodError ex){ encounter.setProvider(Context.getUserService().getUser(id)); } String submitString = XformBuilder.getNodeValue(formNode, XformBuilder.NODE_ENCOUNTER_ENCOUNTER_DATETIME); Date date = XformsUtil.fromSubmitString2Date(submitString); if(XformsUtil.encounterDateIncludesTime()) date = XformsUtil.fromSubmitString2DateTime(submitString); encounter.setEncounterDatetime(date); } private static void addNewObs(Element formNode, List<String> complexObs,Encounter encounter, Element obsNode, Date datetime, Obs obsGroup) throws Exception{ if(obsNode == null) return; for(int i=0; i<obsNode.getChildCount(); i++){ if(obsNode.getType(i) != Element.ELEMENT) continue; Element node = (Element)obsNode.getChild(i); String conceptStr = node.getAttributeValue(null, "openmrs_concept"); if(conceptStr == null || conceptStr.trim().length() == 0) continue; Concept concept = Context.getConceptService().getConcept(Integer.parseInt(getConceptId(conceptStr))); if(isMultipleSelNode(node)) addMultipleSelObs(encounter,concept,node,datetime); else{ Element valueNode = XformBuilder.getElement(node, "value"); String value = XformBuilder.getTextValue(valueNode); String obsId = node.getAttributeValue(null, "obsId"); String obsGroupId = node.getAttributeValue(null, "obsGroupId"); if((obsId != null && obsId.trim().length() > 0) || obsGroupId != null && obsGroupId.trim().length() > 0){ if(!"true()".equals(valueNode.getAttributeValue(null, "new"))) continue; //new obs cant have an obs id } if(obsGroupId != null && obsGroupId.trim().length() > 0){ Obs group = createObs(concept,obsGroup,value,datetime); encounter.addObs(group); addNewObs(formNode,complexObs,encounter,node,datetime,group); continue; //new obs cant have an obsGroupId } if(valueNode == null) continue; if(value == null || value.trim().length() == 0) continue; String nodeName = node.getName(); if(complexObs.contains(nodeName)) value = saveComplexObs(nodeName,value,formNode); Obs obs = createObs(concept,obsGroup,value,datetime); encounter.addObs(obs); if(concept.isSet()) addNewObs(node,complexObs,encounter,node,datetime,obs); } } } private static void addMultipleSelObs(Encounter encounter, Concept concept,Element node, Date datetime) throws Exception{ Element multValueNode = XformBuilder.getElement(node, "xforms_value"); if(multValueNode == null) return; String value = XformBuilder.getTextValue(multValueNode); if(value == null || value.trim().length() == 0) return; String[] valueArray = value.split(XformBuilder.MULTIPLE_SELECT_VALUE_SEPARATOR); for(int i=0; i<node.getChildCount(); i++){ if(node.getType(i) != Element.ELEMENT) continue; Element valueNode = (Element)node.getChild(i); String obsId = valueNode.getAttributeValue(null, "obsId"); if(obsId != null && obsId.trim().length() > 0){ if(!"true()".equals(valueNode.getAttributeValue(null, "new"))) continue; //new obs cant have an obs id } String obsGroupId = valueNode.getAttributeValue(null, "obsGroupId"); if(obsGroupId != null && obsGroupId.trim().length() > 0) continue; //new obs cant have an obsGroupId String conceptStr = valueNode.getAttributeValue(null, "openmrs_concept"); if(conceptStr == null || conceptStr.trim().length() == 0) continue; //must have an openmrs_concept attribute hence nothing like date or value nodes if(!contains(valueNode.getName(),valueArray)) continue; //name must be in the xforms_value Obs obs = createObs(concept,null,conceptStr,datetime); encounter.addObs(obs); } } private static boolean multipleSelValueContains(String nodeName, String valueName,Element node,Hashtable<String,String[]> multipleSelValues){ String[] values = multipleSelValues.get(nodeName); if(values == null){ Element multNode = XformBuilder.getElement(node, "xforms_value"); if(multNode != null){ String value = XformBuilder.getTextValue(multNode); if(value == null) value = ""; values = value.split(XformBuilder.MULTIPLE_SELECT_VALUE_SEPARATOR); multipleSelValues.put(nodeName, values); } } return contains(valueName,values); } /*private static void setObsValue(Obs obs,Element valueNode, boolean isNew) throws Exception{ setObsValue(obs,XformBuilder.getTextValue(valueNode),isNew); }*/ private static boolean setObsValue(Obs obs,String value) throws Exception{ ConceptDatatype dt = obs.getConcept().getDatatype(); if (dt.isNumeric()) obs.setValueNumeric(Double.parseDouble(value.toString())); else if (dt.isText()) obs.setValueText(value); else if (dt.isCoded()) obs.setValueCoded((Concept) convertToType(getConceptId(value), Concept.class)); else if (dt.isBoolean()){ boolean booleanValue = value != null && !Boolean.FALSE.equals(value) && !"false".equals(value); obs.setValueNumeric(booleanValue ? 1.0 : 0.0); } else if(dt.TIME.equals(dt.getHl7Abbreviation())) obs.setValueDatetime(XformsUtil.fromSubmitString2Time(value)); else if(dt.DATETIME.equals(dt.getHl7Abbreviation())) obs.setValueDatetime(XformsUtil.fromSubmitString2DateTime(value)); else if (dt.isDate()) obs.setValueDatetime(XformsUtil.fromSubmitString2Date(value)); else if ("ZZ".equals(dt.getHl7Abbreviation())) { // don't set a value. eg could be a set }else throw new IllegalArgumentException("concept datatype not yet implemented: " + dt.getName() + " with Hl7 Abbreviation: " + dt.getHl7Abbreviation()); return false; } private static String getConceptId(String conceptStr){ int pos = conceptStr.indexOf('^'); if(pos < 1) return conceptStr; //must be a number already. return conceptStr.substring(0, pos); } private static Object convertToType(String val, Class<?> clazz) { if (val == null) return null; if ("".equals(val) && !String.class.equals(clazz)) return null; if (Location.class.isAssignableFrom(clazz)) { LocationEditor ed = new LocationEditor(); ed.setAsText(val); return ed.getValue(); } else if (User.class.isAssignableFrom(clazz)) { UserEditor ed = new UserEditor(); ed.setAsText(val); return ed.getValue(); } else if (Date.class.isAssignableFrom(clazz)) { try { DateFormat df = Context.getDateFormat(); df.setLenient(false); return df.parse(val); } catch (ParseException e) { throw new IllegalArgumentException(e); } } else if (Double.class.isAssignableFrom(clazz)) { return Double.valueOf(val); } else if (Concept.class.isAssignableFrom(clazz)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(val); return ed.getValue(); } else { return val; } } private static Obs createObs(Concept concept,Obs obsGroup, String value, Date datetime) throws Exception{ Obs obs = new Obs(); obs.setConcept(concept); obs.setObsGroup(obsGroup); setObsValue(obs,value); if (datetime != null) obs.setObsDatetime(datetime); obs.setCreator(Context.getAuthenticatedUser()); return obs; } private static boolean isMultipleSelNode(Element node){ return "1".equals(node.getAttributeValue(null,"multiple")); } private static boolean contains(String name,String[] valueArray){ for(String value : valueArray){ if(!value.equalsIgnoreCase(name)) continue; return true; } return false; } public static String conceptToString(Concept concept, Locale locale) { ConceptName localizedName = concept.getName(locale); return conceptToString(concept, localizedName); } /** * Turn the given concept/concept-name pair into a string acceptable for hl7 and forms * * @param concept Concept to convert to a string * @param localizedName specific localized concept-name * @return String representation of the given concept */ public static String conceptToString(Concept concept, ConceptName localizedName) { return concept.getConceptId() + "^" + localizedName.getName() + "^" + FormConstants.HL7_LOCAL_CONCEPT; // + "^" // + localizedName.getConceptNameId() + "^" + localizedName.getName() + "^" + FormConstants.HL7_LOCAL_CONCEPT_NAME; } public static String getComplexDataKey(String formid, String xpath){ return formid + xpath; } public static List<String> getEditedComplexObsNames(){ List<String> names = new ArrayList<String>(); for(String xpath : dirtyComplexData){ String name = complexDataNodeNames.get(xpath); if(name != null) names.add(name); } return names; } public static String saveComplexObs(String nodeName, String value, Element formNode) throws Exception { byte[] bytes = Base64.decode(value); String path = formNode.getAttributeValue(null,"name"); path += File.separatorChar + nodeName; File file = OpenmrsUtil.getOutFile(XformsUtil.getXformsComplexObsDir(path), new Date(), Context.getAuthenticatedUser()); FileOutputStream writter = new FileOutputStream(file); writter.write(bytes); writter.close(); return file.getAbsolutePath(); } private static void retrieveSessionValues(HttpServletRequest request){ HttpSession session = request.getSession(); complexData = (HashMap<String,byte[]>)session.getAttribute("XformObsEdit.complexData"); complexDataNodeNames = (HashMap<String,String>)session.getAttribute("XformObsEdit.complexDataNodeNames"); dirtyComplexData = (List<String>)session.getAttribute("XformObsEdit.dirtyComplexData"); if(complexData == null){ complexData = new HashMap<String,byte[]>(); session.setAttribute("XformObsEdit.complexData", complexData); } if(complexDataNodeNames == null){ complexDataNodeNames = new HashMap<String,String>(); session.setAttribute("XformObsEdit.complexDataNodeNames", complexDataNodeNames); } if(dirtyComplexData == null){ dirtyComplexData = new ArrayList<String>(); session.setAttribute("XformObsEdit.dirtyComplexData", dirtyComplexData); } } private static void clearSessionData(HttpServletRequest request,Integer formId){ complexData.clear(); complexDataNodeNames.clear(); dirtyComplexData.clear(); clearFormSessionData(request, formId.toString()); } public static byte[] getComplexData(HttpServletRequest request,String formId, String xpath){ retrieveSessionValues(request); return complexData.get(getComplexDataKey(formId, xpath)); } public static void setComplexDataDirty(HttpServletRequest request,String formId, String xpath){ retrieveSessionValues(request); String key = getComplexDataKey(formId, xpath); if(!dirtyComplexData.contains(key)) dirtyComplexData.add(key); } public static void loadAndClearSessionData(HttpServletRequest request,Integer formId){ HttpSession session = request.getSession(); complexData = (HashMap<String,byte[]>)session.getAttribute("XformObsEdit.complexData"); complexDataNodeNames = (HashMap<String,String>)session.getAttribute("XformObsEdit.complexDataNodeNames"); dirtyComplexData = (List<String>)session.getAttribute("XformObsEdit.dirtyComplexData"); if(complexData != null) complexData.clear(); if(complexDataNodeNames != null) complexDataNodeNames.clear(); if(dirtyComplexData != null) dirtyComplexData.clear(); clearFormSessionData(request, formId.toString()); } public static void clearFormSessionData(HttpServletRequest request,String formId){ HttpSession session = request.getSession(); session.setAttribute(getFormKey(formId), null); } public static String getFormKey(String formId){ return "MultidemiaData"+formId; } public static void fillPatientComplexObs(HttpServletRequest request,Document doc, String xml) throws Exception{ retrieveSessionValues(request); clearSessionData(request,0); Element patientNode = XformBuilder.getElement(doc.getRootElement(), "patient"); if(patientNode== null) return; List<String> complexObs = DOMUtil.getXformComplexObsNodeNames(xml); for(int index = 0; index < patientNode.getChildCount(); index++){ if(patientNode.getType(index) != Element.ELEMENT) continue; //Syste Element node = (Element)patientNode.getChild(index); if(complexObs.contains(node.getName())){ String value = XformBuilder.getTextValue(node); if(value != null && value.trim().length() > 0){ String key = getComplexDataKey(patientNode.getAttributeValue(null, "id"),"/patient/" + node.getName()); value = getComplexObsValue(node.getName(),node,value,key); XformBuilder.setNodeValue(node,value); } } } } } //String s = ""; //if(formNode != null) // s = "NOT NULL"; //else // s = "NULL"; //for(Obs obs : observations){ // Concept concept = obs.getConcept(); // s+=":" + FormUtil.conceptToString(concept, Context.getLocale()); // s+="+++" + FormUtil.getXmlToken(concept.getDisplayString()); // s+="=" + obs.getValueAsString(Context.getLocale()); // // ConceptDatatype dataType = concept.getDatatype(); // s += " & " + FormUtil.getXmlToken(obs.getValueAsString(Context.getLocale())); // if(dataType.isCoded()) // s += " !! " + FormUtil.conceptToString(obs.getValueCoded(), Context.getLocale()); //
true
true
public static void fillObs(HttpServletRequest request,Document doc, Integer encounterId, String xml)throws Exception{ Element formNode = XformBuilder.getElement(doc.getRootElement(),"form"); if(formNode == null) return; Encounter encounter = Context.getEncounterService().getEncounter(encounterId); if(encounter == null) return; retrieveSessionValues(request); clearSessionData(request,encounter.getForm().getFormId()); formNode.setAttribute(null, "encounterId", encounter.getEncounterId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_LOCATION_ID, encounter.getLocation().getLocationId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_ENCOUNTER_DATETIME, XformsUtil.encounterDateIncludesTime() ? XformsUtil.fromDateTime2SubmitString(encounter.getEncounterDatetime()) : XformsUtil.fromDate2SubmitString(encounter.getEncounterDatetime())); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_PROVIDER_ID, XformsUtil.getProviderId(encounter).toString()); List<String> complexObs = DOMUtil.getXformComplexObsNodeNames(xml); HashMap<String,Element> obsGroupNodes = new HashMap<String,Element>(); List<String> nonCopyAttributes = new ArrayList<String>(); nonCopyAttributes.add("obsId"); nonCopyAttributes.add("obsGroupId"); Set<Obs> observations = encounter.getObs(); for(Obs obs : observations){ Concept concept = obs.getConcept(); //Obs obsGroup = obs.getObsGroup(); String obsGroupId = obs.getObsGroup() == null ? null : obs.getObsGroup().getObsId().toString(); //TODO This needs to do a better job by searching for an attribute that starts with //a concept id of the concept and hence remove the name dependency as the concept name //could change or may be different in a different locale. Element node = XformBuilder.getElementByAttributePrefix(formNode,"openmrs_concept", (obsGroupId == null ? concept.getConceptId() : obs.getObsGroup().getConcept()) +"^", (obsGroupId == null ? false : true), (obsGroupId == null ? "obsId" : "obsGroupId"), true, nonCopyAttributes); if(node == null) continue; //check if this is a repeating obs. if(obsGroupId != null){ String nodeGroupId = node.getAttributeValue(null, "obsGroupId"); //if this is first time to get a node of this parent. if(nodeGroupId == null || nodeGroupId.trim().length() == 0){ node.setAttribute(null, "obsGroupId", obsGroupId); //new group processing obsGroupNodes.put(obsGroupId, node); } else{ if(!nodeGroupId.equals(obsGroupId)){ Element groupNode = obsGroupNodes.get(obsGroupId); if(groupNode == null){//new group node = XformBuilder.createCopy(node, nonCopyAttributes); node.setAttribute(null, "obsGroupId", obsGroupId); obsGroupNodes.put(obsGroupId, node); }//else a kid of some other group which we processed but not necessarily being the first one. else node = groupNode; }//else another kid of an already processed group. } node = XformBuilder.getElementByAttributePrefix(node,"openmrs_concept",concept.getConceptId()+"^", false, "obsId", false, nonCopyAttributes); if(node == null) continue; } String value = obs.getValueAsString(Context.getLocale()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) value = FormUtil.conceptToString(obs.getValueCoded(), Context.getLocale()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATETIME) && obs.getValueDatetime() != null) value = XformsUtil.fromDateTime2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.TIME) && obs.getValueDatetime() != null) value = XformsUtil.fromTime2SubmitString(obs.getValueDatetime()); if("1".equals(node.getAttributeValue(null,"multiple"))){ Element multNode = XformBuilder.getElement(node, "xforms_value"); if(multNode != null){ value = XformBuilder.getTextValue(multNode); if(value != null && value.trim().length() > 0) value += " "; else value = ""; //TODO This may fail when locale changes from the one in which the form was designed. //String xmlToken = FormUtil.getXmlToken(obs.getValueAsString(Context.getLocale())); try{ String xmlToken = getMultSelObsNodeName((Element)multNode.getParent(), obs, nonCopyAttributes); XformBuilder.setNodeValue(node, "xforms_value", value + xmlToken); //TODO May need to use getElementWithAttributePrefix() Element valueNode = XformBuilder.getElement(node, xmlToken); if(valueNode != null){ XformBuilder.setNodeValue(valueNode,"true"); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); } }catch(Exception ex){ ex.printStackTrace(); } } } else{ Element valueNode = XformBuilder.getElement(node, "value"); if(valueNode != null){ if(complexObs.contains(node.getName())){ String key = getComplexDataKey(formNode.getAttributeValue(null, "id"),"/form/obs/" + node.getName() + "/value"); value = getComplexObsValue(node.getName(),valueNode,value,key); } XformBuilder.setNodeValue(valueNode,value); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) valueNode.setAttribute(null, "displayValue", obs.getValueCoded().getName().getName()); if(obsGroupId != null) valueNode.setAttribute(null, "default", "false()"); } node.setAttribute(null, "obsId", obs.getObsId().toString()); //XformBuilder.setNodeValue(node, "value", value); } } //System.out.println(XformBuilder.fromDoc2String(doc)); }
public static void fillObs(HttpServletRequest request,Document doc, Integer encounterId, String xml)throws Exception{ Element formNode = XformBuilder.getElement(doc.getRootElement(),"form"); if(formNode == null) return; Encounter encounter = Context.getEncounterService().getEncounter(encounterId); if(encounter == null) return; retrieveSessionValues(request); clearSessionData(request,encounter.getForm().getFormId()); formNode.setAttribute(null, "encounterId", encounter.getEncounterId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_LOCATION_ID, encounter.getLocation().getLocationId().toString()); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_ENCOUNTER_DATETIME, XformsUtil.encounterDateIncludesTime() ? XformsUtil.fromDateTime2SubmitString(encounter.getEncounterDatetime()) : XformsUtil.fromDate2SubmitString(encounter.getEncounterDatetime())); XformBuilder.setNodeValue(doc, XformBuilder.NODE_ENCOUNTER_PROVIDER_ID, XformsUtil.getProviderId(encounter).toString()); List<String> complexObs = DOMUtil.getXformComplexObsNodeNames(xml); HashMap<String,Element> obsGroupNodes = new HashMap<String,Element>(); List<String> nonCopyAttributes = new ArrayList<String>(); nonCopyAttributes.add("obsId"); nonCopyAttributes.add("obsGroupId"); Set<Obs> observations = encounter.getObs(); for(Obs obs : observations){ Concept concept = obs.getConcept(); //Obs obsGroup = obs.getObsGroup(); String obsGroupId = obs.getObsGroup() == null ? null : obs.getObsGroup().getObsId().toString(); //TODO This needs to do a better job by searching for an attribute that starts with //a concept id of the concept and hence remove the name dependency as the concept name //could change or may be different in a different locale. Element node = XformBuilder.getElementByAttributePrefix(formNode,"openmrs_concept", (obsGroupId == null ? concept.getConceptId() : obs.getObsGroup().getConcept()) +"^", (obsGroupId == null ? false : true), (obsGroupId == null ? "obsId" : "obsGroupId"), true, nonCopyAttributes); if(node == null) continue; //check if this is a repeating obs. if(obsGroupId != null){ String nodeGroupId = node.getAttributeValue(null, "obsGroupId"); //if this is first time to get a node of this parent. if(nodeGroupId == null || nodeGroupId.trim().length() == 0){ node.setAttribute(null, "obsGroupId", obsGroupId); //new group processing obsGroupNodes.put(obsGroupId, node); } else{ if(!nodeGroupId.equals(obsGroupId)){ Element groupNode = obsGroupNodes.get(obsGroupId); if(groupNode == null){//new group node = XformBuilder.createCopy(node, nonCopyAttributes); node.setAttribute(null, "obsGroupId", obsGroupId); obsGroupNodes.put(obsGroupId, node); }//else a kid of some other group which we processed but not necessarily being the first one. else node = groupNode; }//else another kid of an already processed group. } node = XformBuilder.getElementByAttributePrefix(node,"openmrs_concept",concept.getConceptId()+"^", false, "obsId", false, nonCopyAttributes); if(node == null) continue; } String value = obs.getValueAsString(Context.getLocale()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) value = FormUtil.conceptToString(obs.getValueCoded(), Context.getLocale()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATE) && obs.getValueDatetime() != null) value = XformsUtil.fromDate2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.DATETIME) && obs.getValueDatetime() != null) value = XformsUtil.fromDateTime2SubmitString(obs.getValueDatetime()); else if(concept.getDatatype().getHl7Abbreviation().equals(ConceptDatatype.TIME) && obs.getValueDatetime() != null) value = XformsUtil.fromTime2SubmitString(obs.getValueDatetime()); if("1".equals(node.getAttributeValue(null,"multiple"))){ Element multNode = XformBuilder.getElement(node, "xforms_value"); if(multNode != null){ value = XformBuilder.getTextValue(multNode); if(value != null && value.trim().length() > 0) value += " "; else value = ""; //TODO This may fail when locale changes from the one in which the form was designed. //String xmlToken = FormUtil.getXmlToken(obs.getValueAsString(Context.getLocale())); try{ String xmlToken = getMultSelObsNodeName((Element)multNode.getParent(), obs, nonCopyAttributes); XformBuilder.setNodeValue(node, "xforms_value", value + xmlToken); //TODO May need to use getElementWithAttributePrefix() Element valueNode = XformBuilder.getElement(node, xmlToken); if(valueNode != null){ XformBuilder.setNodeValue(valueNode,"true"); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); } }catch(Exception ex){ ex.printStackTrace(); } } } else{ Element valueNode = XformBuilder.getElement(node, "value"); if(valueNode != null){ if(complexObs.contains(node.getName())){ String key = getComplexDataKey(formNode.getAttributeValue(null, "id"),"/form/obs/" + node.getName() + "/value"); value = getComplexObsValue(node.getName(),valueNode,value,key); } XformBuilder.setNodeValue(valueNode,value); valueNode.setAttribute(null, "obsId", obs.getObsId().toString()); if(concept.getDatatype().isCoded() && obs.getValueCoded() != null) valueNode.setAttribute(null, "displayValue", obs.getValueCoded().getName().getName()); if(obsGroupId != null) valueNode.setAttribute(null, "default", "false()"); } node.setAttribute(null, "obsId", obs.getObsId().toString()); //XformBuilder.setNodeValue(node, "value", value); } } //System.out.println(XformBuilder.fromDoc2String(doc)); }
diff --git a/common/plugins/org.jboss.tools.common/src/org/jboss/tools/common/util/SwtUtil.java b/common/plugins/org.jboss.tools.common/src/org/jboss/tools/common/util/SwtUtil.java index 6638b413f..d8d6c6d68 100644 --- a/common/plugins/org.jboss.tools.common/src/org/jboss/tools/common/util/SwtUtil.java +++ b/common/plugins/org.jboss.tools.common/src/org/jboss/tools/common/util/SwtUtil.java @@ -1,38 +1,37 @@ /******************************************************************************* * Copyright (c) 2007-2011 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributor: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.common.util; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Resource; import org.eclipse.swt.widgets.Widget; /** * @author Yahor Radtsevich (yradtsevich) */ public class SwtUtil { /** * Adds a dispose listener to {@code widget} * which when invoked disposes given {@code resource} * * @param resource resource to be disposed * @param widget widget to which disposal bind disposal of {@code resource} */ public static void bindDisposal(final Resource resource, Widget widget) { widget.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { resource.dispose(); - System.out.println("Resource Disposed: " + resource); } }); } }
true
true
public static void bindDisposal(final Resource resource, Widget widget) { widget.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { resource.dispose(); System.out.println("Resource Disposed: " + resource); } }); }
public static void bindDisposal(final Resource resource, Widget widget) { widget.addDisposeListener(new DisposeListener() { public void widgetDisposed(DisposeEvent e) { resource.dispose(); } }); }
diff --git a/samples/jaxp/SourceValidator.java b/samples/jaxp/SourceValidator.java index ede7fd02f..8f72857f8 100644 --- a/samples/jaxp/SourceValidator.java +++ b/samples/jaxp/SourceValidator.java @@ -1,548 +1,549 @@ /* * Copyright 2005 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jaxp; import java.io.PrintWriter; import java.util.Vector; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import javax.xml.validation.Validator; import org.w3c.dom.Document; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; /** * <p>A sample demonstrating how to use the JAXP 1.3 Validation API * to create a validator and use the validator to validate input * from SAX, DOM or a stream. The output of this program shows the * time spent executing the Validator.validate(Source) method.</p> * * <p>This class is useful as a "poor-man's" performance tester to * compare the speed of various JAXP 1.3 validators with different * input sources. However, it is important to note that the first * validation time of a validator will include both VM class load time * and validator initialization that would not be present in subsequent * validations with the same document. Also note that when the source for * validation is SAX or a stream, the validation time will also include * the time to parse the document, whereas the DOM validation is * completely in memory.</p> * * <p><strong>Note:</strong> The results produced by this program * should never be accepted as true performance measurements.</p> * * @author Michael Glavassevich, IBM * * @version $Id$ */ public class SourceValidator implements ErrorHandler { // // Constants // // feature ids /** Schema full checking feature id (http://apache.org/xml/features/validation/schema-full-checking). */ protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID = "http://apache.org/xml/features/validation/schema-full-checking"; /** Honour all schema locations feature id (http://apache.org/xml/features/honour-all-schemaLocations). */ protected static final String HONOUR_ALL_SCHEMA_LOCATIONS_ID = "http://apache.org/xml/features/honour-all-schemaLocations"; /** Validate schema annotations feature id (http://apache.org/xml/features/validate-annotations) */ protected static final String VALIDATE_ANNOTATIONS_ID = "http://apache.org/xml/features/validate-annotations"; /** Generate synthetic schema annotations feature id (http://apache.org/xml/features/generate-synthetic-annotations). */ protected static final String GENERATE_SYNTHETIC_ANNOTATIONS_ID = "http://apache.org/xml/features/generate-synthetic-annotations"; // default settings /** Default repetition (1). */ protected static final int DEFAULT_REPETITION = 1; /** Default validation source. */ protected static final String DEFAULT_VALIDATION_SOURCE = "sax"; /** Default schema full checking support (false). */ protected static final boolean DEFAULT_SCHEMA_FULL_CHECKING = false; /** Default honour all schema locations (false). */ protected static final boolean DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS = false; /** Default validate schema annotations (false). */ protected static final boolean DEFAULT_VALIDATE_ANNOTATIONS = false; /** Default generate synthetic schema annotations (false). */ protected static final boolean DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS = false; /** Default memory usage report (false). */ protected static final boolean DEFAULT_MEMORY_USAGE = false; // // Data // protected PrintWriter fOut = new PrintWriter(System.out); // // Constructors // /** Default constructor. */ public SourceValidator() { } // <init>() // // Public methods // public void validate(Validator validator, Source source, String systemId, int repetitions, boolean memoryUsage) { try { long timeBefore = System.currentTimeMillis(); long memoryBefore = Runtime.getRuntime().freeMemory(); for (int j = 0; j < repetitions; ++j) { validator.validate(source); } long memoryAfter = Runtime.getRuntime().freeMemory(); long timeAfter = System.currentTimeMillis(); long time = timeAfter - timeBefore; long memory = memoryUsage ? memoryBefore - memoryAfter : Long.MIN_VALUE; printResults(fOut, systemId, time, memory, repetitions); } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); Exception se = e; if (e instanceof SAXException) { se = ((SAXException)e).getException(); } if (se != null) se.printStackTrace(System.err); else e.printStackTrace(System.err); } } // validate(Validator,Source,String,int,boolean) /** Prints the results. */ public void printResults(PrintWriter out, String uri, long time, long memory, int repetition) { // filename.xml: 631 ms out.print(uri); out.print(": "); if (repetition == 1) { out.print(time); } else { out.print(time); out.print('/'); out.print(repetition); out.print('='); out.print(((float)time)/repetition); } out.print(" ms"); if (memory != Long.MIN_VALUE) { out.print(", "); out.print(memory); out.print(" bytes"); } out.println(); out.flush(); } // printResults(PrintWriter,String,long,long,int) // // ErrorHandler methods // /** Warning. */ public void warning(SAXParseException ex) throws SAXException { printError("Warning", ex); } // warning(SAXParseException) /** Error. */ public void error(SAXParseException ex) throws SAXException { printError("Error", ex); } // error(SAXParseException) /** Fatal error. */ public void fatalError(SAXParseException ex) throws SAXException { printError("Fatal Error", ex); throw ex; } // fatalError(SAXParseException) // // Protected methods // /** Prints the error message. */ protected void printError(String type, SAXParseException ex) { System.err.print("["); System.err.print(type); System.err.print("] "); String systemId = ex.getSystemId(); if (systemId != null) { int index = systemId.lastIndexOf('/'); if (index != -1) systemId = systemId.substring(index + 1); System.err.print(systemId); } System.err.print(':'); System.err.print(ex.getLineNumber()); System.err.print(':'); System.err.print(ex.getColumnNumber()); System.err.print(": "); System.err.print(ex.getMessage()); System.err.println(); System.err.flush(); } // printError(String,SAXParseException) // // MAIN // /** Main program entry point. */ public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables Vector schemas = null; Vector instances = null; int repetition = DEFAULT_REPETITION; String validationSource = DEFAULT_VALIDATION_SOURCE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number ("+number+")."); } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-vs")) { if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) { validationSource = arg; } else { System.err.println("error: unknown source type ("+arg+")."); } } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } try { // Create new instance of SourceValidator. SourceValidator sourceValidator = new SourceValidator(); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(sourceValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(sourceValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents if (instances != null && instances.size() > 0) { final int length = instances.size(); if (validationSource.equals("sax")) { // SAXSource XMLReader reader = XMLReaderFactory.createXMLReader(); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); SAXSource source = new SAXSource(reader, new InputSource(systemId)); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else if (validationSource.equals("dom")) { // DOMSource DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); + db.setErrorHandler(sourceValidator); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); Document doc = db.parse(systemId); DOMSource source = new DOMSource(doc); source.setSystemId(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else { // StreamSource for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); StreamSource source = new StreamSource(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[]) // // Private static methods // /** Prints the usage. */ private static void printUsage() { System.err.println("usage: java jaxp.SourceValidator (options) ..."); System.err.println(); System.err.println("options:"); System.err.println(" -x number Select number of repetitions."); System.err.println(" -a uri ... Provide a list of schema documents"); System.err.println(" -i uri ... Provide a list of instance documents to validate"); System.err.println(" -vs source Select validation source (sax|dom|stream)"); System.err.println(" -f | -F Turn on/off Schema full checking."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -hs | -HS Turn on/off honouring of all schema locations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -va | -VA Turn on/off validation of schema annotations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -ga | -GA Turn on/off generation of synthetic schema annotations."); System.err.println(" NOTE: Not supported by all schema factories and validators."); System.err.println(" -m | -M Turn on/off memory usage report"); System.err.println(" -h This help screen."); System.err.println(); System.err.println("defaults:"); System.err.println(" Repetition: " + DEFAULT_REPETITION); System.err.println(" Validation source: " + DEFAULT_VALIDATION_SOURCE); System.err.print(" Schema full checking: "); System.err.println(DEFAULT_SCHEMA_FULL_CHECKING ? "on" : "off"); System.err.print(" Honour all schema locations: "); System.err.println(DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS ? "on" : "off"); System.err.print(" Validate annotations: "); System.err.println(DEFAULT_VALIDATE_ANNOTATIONS ? "on" : "off"); System.err.print(" Generate synthetic annotations: "); System.err.println(DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS ? "on" : "off"); System.err.print(" Memory: "); System.err.println(DEFAULT_MEMORY_USAGE ? "on" : "off"); System.err.println(); System.err.println("notes:"); System.err.println(" The speed and memory results from this program should NOT be used as the"); System.err.println(" basis of parser performance comparison! Real analytical methods should be"); System.err.println(" used. For better results, perform multiple document validations within the"); System.err.println(" same virtual machine to remove class loading from parse time and memory usage."); } // printUsage() } // class SourceValidator
true
true
public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables Vector schemas = null; Vector instances = null; int repetition = DEFAULT_REPETITION; String validationSource = DEFAULT_VALIDATION_SOURCE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number ("+number+")."); } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-vs")) { if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) { validationSource = arg; } else { System.err.println("error: unknown source type ("+arg+")."); } } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } try { // Create new instance of SourceValidator. SourceValidator sourceValidator = new SourceValidator(); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(sourceValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(sourceValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents if (instances != null && instances.size() > 0) { final int length = instances.size(); if (validationSource.equals("sax")) { // SAXSource XMLReader reader = XMLReaderFactory.createXMLReader(); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); SAXSource source = new SAXSource(reader, new InputSource(systemId)); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else if (validationSource.equals("dom")) { // DOMSource DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); Document doc = db.parse(systemId); DOMSource source = new DOMSource(doc); source.setSystemId(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else { // StreamSource for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); StreamSource source = new StreamSource(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[])
public static void main (String [] argv) { // is there anything to do? if (argv.length == 0) { printUsage(); System.exit(1); } // variables Vector schemas = null; Vector instances = null; int repetition = DEFAULT_REPETITION; String validationSource = DEFAULT_VALIDATION_SOURCE; boolean schemaFullChecking = DEFAULT_SCHEMA_FULL_CHECKING; boolean honourAllSchemaLocations = DEFAULT_HONOUR_ALL_SCHEMA_LOCATIONS; boolean validateAnnotations = DEFAULT_VALIDATE_ANNOTATIONS; boolean generateSyntheticAnnotations = DEFAULT_GENERATE_SYNTHETIC_ANNOTATIONS; boolean memoryUsage = DEFAULT_MEMORY_USAGE; // process arguments for (int i = 0; i < argv.length; ++i) { String arg = argv[i]; if (arg.startsWith("-")) { String option = arg.substring(1); if (option.equals("x")) { if (++i == argv.length) { System.err.println("error: Missing argument to -x option."); continue; } String number = argv[i]; try { int value = Integer.parseInt(number); if (value < 1) { System.err.println("error: Repetition must be at least 1."); continue; } repetition = value; } catch (NumberFormatException e) { System.err.println("error: invalid number ("+number+")."); } continue; } if (arg.equals("-a")) { // process -a: schema documents if (schemas == null) { schemas = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { schemas.add(arg); ++i; } continue; } if (arg.equals("-i")) { // process -i: instance documents if (instances == null) { instances = new Vector(); } while (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { instances.add(arg); ++i; } continue; } if (arg.equals("-vs")) { if (i + 1 < argv.length && !(arg = argv[i + 1]).startsWith("-")) { if (arg.equals("sax") || arg.equals("dom") || arg.equals("stream")) { validationSource = arg; } else { System.err.println("error: unknown source type ("+arg+")."); } } continue; } if (option.equalsIgnoreCase("f")) { schemaFullChecking = option.equals("f"); continue; } if (option.equalsIgnoreCase("hs")) { honourAllSchemaLocations = option.equals("hs"); continue; } if (option.equalsIgnoreCase("va")) { validateAnnotations = option.equals("va"); continue; } if (option.equalsIgnoreCase("ga")) { generateSyntheticAnnotations = option.equals("ga"); continue; } if (option.equalsIgnoreCase("m")) { memoryUsage = option.equals("m"); continue; } if (option.equals("h")) { printUsage(); continue; } System.err.println("error: unknown option ("+option+")."); continue; } } try { // Create new instance of SourceValidator. SourceValidator sourceValidator = new SourceValidator(); // Create SchemaFactory and configure SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); factory.setErrorHandler(sourceValidator); try { factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { factory.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { factory.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { factory.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: SchemaFactory does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: SchemaFactory does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Build Schema from sources Schema schema; if (schemas != null && schemas.size() > 0) { final int length = schemas.size(); StreamSource[] sources = new StreamSource[length]; for (int j = 0; j < length; ++j) { sources[j] = new StreamSource((String) schemas.elementAt(j)); } schema = factory.newSchema(sources); } else { schema = factory.newSchema(); } // Setup validator and input source. Validator validator = schema.newValidator(); validator.setErrorHandler(sourceValidator); try { validator.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, schemaFullChecking); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+SCHEMA_FULL_CHECKING_FEATURE_ID+")"); } try { validator.setFeature(HONOUR_ALL_SCHEMA_LOCATIONS_ID, honourAllSchemaLocations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+HONOUR_ALL_SCHEMA_LOCATIONS_ID+")"); } try { validator.setFeature(VALIDATE_ANNOTATIONS_ID, validateAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+VALIDATE_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+VALIDATE_ANNOTATIONS_ID+")"); } try { validator.setFeature(GENERATE_SYNTHETIC_ANNOTATIONS_ID, generateSyntheticAnnotations); } catch (SAXNotRecognizedException e) { System.err.println("warning: Validator does not recognize feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } catch (SAXNotSupportedException e) { System.err.println("warning: Validator does not support feature ("+GENERATE_SYNTHETIC_ANNOTATIONS_ID+")"); } // Validate instance documents if (instances != null && instances.size() > 0) { final int length = instances.size(); if (validationSource.equals("sax")) { // SAXSource XMLReader reader = XMLReaderFactory.createXMLReader(); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); SAXSource source = new SAXSource(reader, new InputSource(systemId)); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else if (validationSource.equals("dom")) { // DOMSource DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); db.setErrorHandler(sourceValidator); for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); Document doc = db.parse(systemId); DOMSource source = new DOMSource(doc); source.setSystemId(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } else { // StreamSource for (int j = 0; j < length; ++j) { String systemId = (String) instances.elementAt(j); StreamSource source = new StreamSource(systemId); sourceValidator.validate(validator, source, systemId, repetition, memoryUsage); } } } } catch (SAXParseException e) { // ignore } catch (Exception e) { System.err.println("error: Parse error occurred - "+e.getMessage()); if (e instanceof SAXException) { Exception nested = ((SAXException)e).getException(); if (nested != null) { e = nested; } } e.printStackTrace(System.err); } } // main(String[])
diff --git a/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java b/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java index c2a343244..d7149e4e3 100644 --- a/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java +++ b/onebusaway-nyc-transit-data-federation/src/test/java/org/onebusaway/nyc/transit_data_federation/bundle/tasks/stif/TestStifTripLoaderTest.java @@ -1,56 +1,57 @@ /** * Copyright (c) 2011 Metropolitan Transportation Authority * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.onebusaway.nyc.transit_data_federation.bundle.tasks.stif; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import org.junit.Test; import org.onebusaway.gtfs.impl.GtfsRelationalDaoImpl; import org.onebusaway.gtfs.model.AgencyAndId; import org.onebusaway.gtfs.model.Trip; import org.onebusaway.gtfs.serialization.GtfsReader; public class TestStifTripLoaderTest { @Test public void testLoader() throws IOException { InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun"); String gtfs = getClass().getResource("m14.zip").getFile(); GtfsReader reader = new GtfsReader(); GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl(); reader.setEntityStore(dao); reader.setInputLocation(new File(gtfs)); reader.run(); StifTripLoader loader = new StifTripLoader(); + loader.setLogger(new MultiCSVLogger(null)); loader.setGtfsDao(dao); loader.run(in, new File("stif.m_0014__.210186.sun")); Map<String, List<AgencyAndId>> mapping = loader.getTripMapping(); assertTrue(mapping.containsKey("1140")); List<AgencyAndId> trips = mapping.get("1140"); AgencyAndId tripId = trips.get(0); Trip trip = dao.getTripForId(tripId); assertEquals(new AgencyAndId("MTA NYCT", "20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId()); } }
true
true
public void testLoader() throws IOException { InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun"); String gtfs = getClass().getResource("m14.zip").getFile(); GtfsReader reader = new GtfsReader(); GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl(); reader.setEntityStore(dao); reader.setInputLocation(new File(gtfs)); reader.run(); StifTripLoader loader = new StifTripLoader(); loader.setGtfsDao(dao); loader.run(in, new File("stif.m_0014__.210186.sun")); Map<String, List<AgencyAndId>> mapping = loader.getTripMapping(); assertTrue(mapping.containsKey("1140")); List<AgencyAndId> trips = mapping.get("1140"); AgencyAndId tripId = trips.get(0); Trip trip = dao.getTripForId(tripId); assertEquals(new AgencyAndId("MTA NYCT", "20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId()); }
public void testLoader() throws IOException { InputStream in = getClass().getResourceAsStream("stif.m_0014__.210186.sun"); String gtfs = getClass().getResource("m14.zip").getFile(); GtfsReader reader = new GtfsReader(); GtfsRelationalDaoImpl dao = new GtfsRelationalDaoImpl(); reader.setEntityStore(dao); reader.setInputLocation(new File(gtfs)); reader.run(); StifTripLoader loader = new StifTripLoader(); loader.setLogger(new MultiCSVLogger(null)); loader.setGtfsDao(dao); loader.run(in, new File("stif.m_0014__.210186.sun")); Map<String, List<AgencyAndId>> mapping = loader.getTripMapping(); assertTrue(mapping.containsKey("1140")); List<AgencyAndId> trips = mapping.get("1140"); AgencyAndId tripId = trips.get(0); Trip trip = dao.getTripForId(tripId); assertEquals(new AgencyAndId("MTA NYCT", "20100627DA_003000_M14AD_0001_M14AD_1"), trip.getId()); }
diff --git a/src/main/java/tachyon/DataServerMessage.java b/src/main/java/tachyon/DataServerMessage.java index 00ed875b0c..7473f4b9fa 100644 --- a/src/main/java/tachyon/DataServerMessage.java +++ b/src/main/java/tachyon/DataServerMessage.java @@ -1,183 +1,184 @@ package tachyon; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DataServerMessage { public static final short DATA_SERVER_REQUEST_MESSAGE = 1; public static final short DATA_SERVER_RESPONSE_MESSAGE = 2; private final Logger LOG = LoggerFactory.getLogger(DataServerMessage.class); private final boolean IS_TO_SEND_DATA; private final short mMsgType; private boolean mIsMessageReady; private ByteBuffer mHeader; private static final int HEADER_LENGTH = 12; private int mFileId; private long mDataLength; RandomAccessFile mFile; private ByteBuffer mData; FileChannel mInChannel; private DataServerMessage(boolean isToSendData, short msgType) { IS_TO_SEND_DATA = isToSendData; mMsgType = msgType; mIsMessageReady = false; } public static DataServerMessage createPartitionRequestMessage() { DataServerMessage ret = new DataServerMessage(false, DATA_SERVER_REQUEST_MESSAGE); ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); return ret; } public static DataServerMessage createPartitionRequestMessage(int fileId) { DataServerMessage ret = new DataServerMessage(true, DATA_SERVER_REQUEST_MESSAGE); ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mFileId = fileId; ret.mDataLength = 0; ret.generateHeader(); ret.mData = ByteBuffer.allocate(0); ret.mIsMessageReady = true; return ret; } public static DataServerMessage createPartitionResponseMessage(boolean toSend, int fileId) { DataServerMessage ret = new DataServerMessage(toSend, DATA_SERVER_RESPONSE_MESSAGE); if (toSend) { ret.mFileId = fileId; try { String filePath = Config.WORKER_DATA_FOLDER + fileId; ret.LOG.info("Try to response remote requst by reading from " + filePath); ret.mFile = new RandomAccessFile(filePath, "r"); ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mDataLength = ret.mFile.length(); ret.mInChannel = ret.mFile.getChannel(); ret.mData = ret.mInChannel.map(FileChannel.MapMode.READ_ONLY, 0, ret.mDataLength); ret.mIsMessageReady = true; ret.generateHeader(); WorkerServiceHandler.sDataAccessQueue.add(ret.mFileId); } catch (IOException e) { // TODO This is a trick for now. The data may have been removed before remote retrieving. ret.mFileId = - ret.mFileId; ret.mDataLength = 0; + ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mData = ByteBuffer.allocate(0); ret.generateHeader(); ret.LOG.error(e.getMessage(), e); } } else { ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mData = null; } return ret; } public void close() { if (mMsgType == DATA_SERVER_RESPONSE_MESSAGE) { try { mFile.close(); } catch (IOException e) { LOG.error(mFile + " " + e.getMessage()); } } } private void generateHeader() { mHeader.clear(); mHeader.putInt(mFileId); mHeader.putLong(mDataLength); mHeader.flip(); } public int recv(SocketChannel socketChannel) throws IOException { isSend(false); int numRead = 0; if (mHeader.remaining() > 0) { numRead = socketChannel.read(mHeader); if (mHeader.remaining() == 0) { mHeader.flip(); mFileId = mHeader.getInt(); mDataLength = mHeader.getLong(); // TODO make this better to truncate the file. assert mDataLength < Integer.MAX_VALUE; mData = ByteBuffer.allocate((int) mDataLength); LOG.info("recv(): mData: " + mData + " mFileId " + mFileId); if (mDataLength == 0) { mIsMessageReady = true; } } } else { numRead = socketChannel.read(mData); if (mData.remaining() == 0) { mIsMessageReady = true; } } return numRead; } public void send(SocketChannel socketChannel) throws IOException { isSend(true); socketChannel.write(mHeader); if (mHeader.remaining() == 0) { socketChannel.write(mData); } } public boolean finishSending() { isSend(true); return mHeader.remaining() == 0 && mData.remaining() == 0; } private void isSend(boolean isSend) { if (IS_TO_SEND_DATA != isSend) { if (IS_TO_SEND_DATA) { CommonUtils.runtimeException("Try to recv on send message"); } else { CommonUtils.runtimeException("Try to send on recv message"); } } } public boolean isMessageReady() { return mIsMessageReady; } public int getFileId() { if (!mIsMessageReady) { CommonUtils.runtimeException("Message is not ready."); } return mFileId; } public ByteBuffer getReadOnlyData() { if (!mIsMessageReady) { CommonUtils.runtimeException("Message is not ready."); } ByteBuffer ret = ByteBuffer.wrap(mData.array()); ret.asReadOnlyBuffer(); return ret; } }
true
true
public static DataServerMessage createPartitionResponseMessage(boolean toSend, int fileId) { DataServerMessage ret = new DataServerMessage(toSend, DATA_SERVER_RESPONSE_MESSAGE); if (toSend) { ret.mFileId = fileId; try { String filePath = Config.WORKER_DATA_FOLDER + fileId; ret.LOG.info("Try to response remote requst by reading from " + filePath); ret.mFile = new RandomAccessFile(filePath, "r"); ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mDataLength = ret.mFile.length(); ret.mInChannel = ret.mFile.getChannel(); ret.mData = ret.mInChannel.map(FileChannel.MapMode.READ_ONLY, 0, ret.mDataLength); ret.mIsMessageReady = true; ret.generateHeader(); WorkerServiceHandler.sDataAccessQueue.add(ret.mFileId); } catch (IOException e) { // TODO This is a trick for now. The data may have been removed before remote retrieving. ret.mFileId = - ret.mFileId; ret.mDataLength = 0; ret.mData = ByteBuffer.allocate(0); ret.generateHeader(); ret.LOG.error(e.getMessage(), e); } } else { ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mData = null; } return ret; }
public static DataServerMessage createPartitionResponseMessage(boolean toSend, int fileId) { DataServerMessage ret = new DataServerMessage(toSend, DATA_SERVER_RESPONSE_MESSAGE); if (toSend) { ret.mFileId = fileId; try { String filePath = Config.WORKER_DATA_FOLDER + fileId; ret.LOG.info("Try to response remote requst by reading from " + filePath); ret.mFile = new RandomAccessFile(filePath, "r"); ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mDataLength = ret.mFile.length(); ret.mInChannel = ret.mFile.getChannel(); ret.mData = ret.mInChannel.map(FileChannel.MapMode.READ_ONLY, 0, ret.mDataLength); ret.mIsMessageReady = true; ret.generateHeader(); WorkerServiceHandler.sDataAccessQueue.add(ret.mFileId); } catch (IOException e) { // TODO This is a trick for now. The data may have been removed before remote retrieving. ret.mFileId = - ret.mFileId; ret.mDataLength = 0; ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mData = ByteBuffer.allocate(0); ret.generateHeader(); ret.LOG.error(e.getMessage(), e); } } else { ret.mHeader = ByteBuffer.allocate(HEADER_LENGTH); ret.mData = null; } return ret; }
diff --git a/src/test/java/org/mule/transport/sftp/dataintegrity/SftpWrongPassPhraseOnOutboundDirectoryTestCase.java b/src/test/java/org/mule/transport/sftp/dataintegrity/SftpWrongPassPhraseOnOutboundDirectoryTestCase.java index a80a8d3..ab487d2 100644 --- a/src/test/java/org/mule/transport/sftp/dataintegrity/SftpWrongPassPhraseOnOutboundDirectoryTestCase.java +++ b/src/test/java/org/mule/transport/sftp/dataintegrity/SftpWrongPassPhraseOnOutboundDirectoryTestCase.java @@ -1,55 +1,54 @@ package org.mule.transport.sftp.dataintegrity; import java.io.IOException; import org.mule.api.endpoint.ImmutableEndpoint; import org.mule.module.client.MuleClient; import org.mule.transport.sftp.SftpClient; /** * Verify that the original file is not lost if the password for the outbound endpoint is wrong */ public class SftpWrongPassPhraseOnOutboundDirectoryTestCase extends AbstractSftpDataIntegrityTestCase { private static String INBOUND_ENDPOINT_NAME = "inboundEndpoint"; protected String getConfigResources() { return "dataintegrity/sftp-wrong-passphrase-config.xml"; } @Override protected void doSetUp() throws Exception { super.doSetUp(); // Delete the in & outbound directories initEndpointDirectory(INBOUND_ENDPOINT_NAME); } /** * The outbound directory doesn't exist. * The source file should still exist * @throws Exception */ public void testWrongPassPhraseOnOutboundDirectory() throws Exception { MuleClient muleClient = new MuleClient(); // Send an file to the SFTP server, which the inbound-outboundEndpoint then can pick up Exception exception = dispatchAndWaitForException(new DispatchParameters(INBOUND_ENDPOINT_NAME, null), "sftp"); assertNotNull(exception); assertTrue(exception instanceof IOException); assertTrue(exception.getMessage().startsWith("Error during login to")); - assertTrue(exception.getMessage().endsWith("Auth fail")); SftpClient sftpClient = getSftpClient(muleClient, INBOUND_ENDPOINT_NAME); try { ImmutableEndpoint endpoint = (ImmutableEndpoint) muleClient.getProperty(INBOUND_ENDPOINT_NAME); assertTrue("The inbound file should still exist", super.verifyFileExists(sftpClient, endpoint.getEndpointURI(), FILE_NAME)); } finally { sftpClient.disconnect(); } } }
true
true
public void testWrongPassPhraseOnOutboundDirectory() throws Exception { MuleClient muleClient = new MuleClient(); // Send an file to the SFTP server, which the inbound-outboundEndpoint then can pick up Exception exception = dispatchAndWaitForException(new DispatchParameters(INBOUND_ENDPOINT_NAME, null), "sftp"); assertNotNull(exception); assertTrue(exception instanceof IOException); assertTrue(exception.getMessage().startsWith("Error during login to")); assertTrue(exception.getMessage().endsWith("Auth fail")); SftpClient sftpClient = getSftpClient(muleClient, INBOUND_ENDPOINT_NAME); try { ImmutableEndpoint endpoint = (ImmutableEndpoint) muleClient.getProperty(INBOUND_ENDPOINT_NAME); assertTrue("The inbound file should still exist", super.verifyFileExists(sftpClient, endpoint.getEndpointURI(), FILE_NAME)); } finally { sftpClient.disconnect(); } }
public void testWrongPassPhraseOnOutboundDirectory() throws Exception { MuleClient muleClient = new MuleClient(); // Send an file to the SFTP server, which the inbound-outboundEndpoint then can pick up Exception exception = dispatchAndWaitForException(new DispatchParameters(INBOUND_ENDPOINT_NAME, null), "sftp"); assertNotNull(exception); assertTrue(exception instanceof IOException); assertTrue(exception.getMessage().startsWith("Error during login to")); SftpClient sftpClient = getSftpClient(muleClient, INBOUND_ENDPOINT_NAME); try { ImmutableEndpoint endpoint = (ImmutableEndpoint) muleClient.getProperty(INBOUND_ENDPOINT_NAME); assertTrue("The inbound file should still exist", super.verifyFileExists(sftpClient, endpoint.getEndpointURI(), FILE_NAME)); } finally { sftpClient.disconnect(); } }
diff --git a/src/com/axiastudio/pypapi/ui/PickerDialog.java b/src/com/axiastudio/pypapi/ui/PickerDialog.java index f2d9bc1..25167a2 100644 --- a/src/com/axiastudio/pypapi/ui/PickerDialog.java +++ b/src/com/axiastudio/pypapi/ui/PickerDialog.java @@ -1,221 +1,222 @@ /* * Copyright (C) 2012 AXIA Studio (http://www.axiastudio.com) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.axiastudio.pypapi.ui; import com.axiastudio.pypapi.Register; import com.axiastudio.pypapi.db.Controller; import com.axiastudio.pypapi.db.Store; import com.trolltech.qt.core.QEvent; import com.trolltech.qt.core.QModelIndex; import com.trolltech.qt.core.QObject; import com.trolltech.qt.core.Qt; import com.trolltech.qt.gui.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * * @author Tiziano Lattisi <tiziano at axiastudio.it> */ public class PickerDialog extends QDialog { private final String STYLE="QLineEdit {" + "image: none;" + "}"; private List selection; private QTableView tableView; private QItemSelectionModel selectionModel; private QLineEdit filterLineEdit; private QLabel searchLogLabel; private Store store; private Controller controller; private QVBoxLayout layout; private QToolButton buttonSearch; private QToolButton buttonCancel; private QToolButton buttonAccept; private Boolean isCriteria; private HashMap criteriaWidgets; public PickerDialog(Controller controller) { this(null, controller); } public PickerDialog(QWidget parent, Controller controller) { super(parent); this.controller = controller; this.selection = new ArrayList(); this.criteriaWidgets = new HashMap(); this.init(); EntityBehavior behavior = (EntityBehavior) Register.queryUtility(IEntityBehavior.class, this.controller.getClassName()); List<Column> criteria = behavior.getCriteria(); this.isCriteria = false; if (criteria != null){ if (criteria.size()>0){ this.addCriteria(criteria); this.buttonAccept.setEnabled(false); this.isCriteria = true; } } else { this.executeSearch(); this.buttonSearch.setEnabled(false); } this.tableView.horizontalHeader().setResizeMode(QHeaderView.ResizeMode.ResizeToContents); this.tableView.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows); this.tableView.setSortingEnabled(true); for( int i=0; i<behavior.getSearchColumns().size(); i++ ){ Column c = behavior.getSearchColumns().get(i); this.tableView.horizontalHeader().setResizeMode(i, QHeaderView.ResizeMode.resolve(c.getResizeModeValue())); } this.setStyleSheet(this.STYLE); } private void init(){ this.setWindowTitle("Research and selection"); this.layout = new QVBoxLayout(this); this.layout.setSpacing(4); this.tableView = new QTableView(); this.tableView.setSizePolicy(new QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)); this.tableView.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows); this.tableView.setMinimumHeight(150); this.tableView.setSortingEnabled(true); this.tableView.installEventFilter(this); this.layout.addWidget(this.tableView, 1); this.filterLineEdit = new QLineEdit(); QLabel filterLabel = new QLabel(); filterLabel.setPixmap(new QPixmap("classpath:com/axiastudio/pypapi/ui/resources/toolbar/find.png")); this.searchLogLabel = new QLabel(); this.buttonSearch = new QToolButton(this); this.buttonSearch.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/key.png")); this.buttonSearch.clicked.connect(this, "executeSearch()"); this.buttonSearch.setShortcut(QKeySequence.StandardKey.Find); this.buttonCancel = new QToolButton(this); this.buttonCancel.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/cancel.png")); this.buttonCancel.clicked.connect(this, "reject()"); this.buttonAccept = new QToolButton(this); this.buttonAccept.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/accept.png")); this.buttonAccept.clicked.connect(this, "accept()"); + this.tableView.doubleClicked.connect(this, "accept()"); QHBoxLayout buttonLayout = new QHBoxLayout(); buttonLayout.setSpacing(4); buttonLayout.addWidget(this.filterLineEdit); buttonLayout.addWidget(filterLabel); QSpacerItem spacer = new QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer); buttonLayout.addWidget(this.buttonSearch); QSpacerItem spacer2 = new QSpacerItem(40, 20, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer2); buttonLayout.addWidget(this.buttonCancel); buttonLayout.addWidget(this.buttonAccept); this.layout.addLayout(buttonLayout); this.resize(500, 300); } private void addCriteria(List<Column> criteria){ QGridLayout grid = new QGridLayout(); for (int i=0; i<criteria.size(); i++){ Column c = criteria.get(i); QLabel criteriaLabel = new QLabel(c.getLabel()); grid.addWidget(criteriaLabel, i, 0); QHBoxLayout criteriaLayout = new QHBoxLayout(); // TODO: different types of search widget depending on the data type QLineEdit line = new QLineEdit(); this.criteriaWidgets.put(c, line); criteriaLayout.addWidget(line); grid.addLayout(criteriaLayout, i, 1); } this.layout.addLayout(grid); } public final void executeSearch(){ Store supersetStore=null; EntityBehavior behavior = (EntityBehavior) Register.queryUtility(IEntityBehavior.class, this.controller.getClassName()); List<Column> columns = behavior.getSearchColumns(); if (!this.isCriteria){ supersetStore = this.controller.createFullStore(); } else { List<Column> criteria = behavior.getCriteria(); HashMap criteriaMap = new HashMap(); for (Column criteriaColumn: criteria){ QWidget widget = (QWidget) this.criteriaWidgets.get(criteriaColumn); // TODO: criteria with widgets other than QLIneEdit if (widget.getClass() == QLineEdit.class){ String value = ((QLineEdit) widget).text(); if (!"".equals(value)){ criteriaMap.put(criteriaColumn, value); } } } supersetStore = this.controller.createCriteriaStore(criteriaMap); } TableModel model = new TableModel(supersetStore, columns); model.setEditable(false); this.tableView.setModel(model); this.selectionModel = new QItemSelectionModel(model); this.tableView.setSelectionModel(this.selectionModel); this.selectionModel.selectionChanged.connect(this, "selectRows(QItemSelection, QItemSelection)"); } private void selectRows(QItemSelection selected, QItemSelection deselected){ TableModel model = (TableModel) this.tableView.model(); List<Integer> selectedIndexes = new ArrayList(); List<Integer> deselectedIndexes = new ArrayList(); for (QModelIndex i: selected.indexes()){ if(!selectedIndexes.contains(i.row())){ selectedIndexes.add(i.row()); } } for (QModelIndex i: deselected.indexes()){ if(!deselectedIndexes.contains(i.row())){ deselectedIndexes.add(i.row()); } } for (Integer idx: selectedIndexes){ boolean res = this.selection.add(model.getEntityByRow(idx)); } for (Integer idx: deselectedIndexes){ boolean res = this.selection.remove(model.getEntityByRow(idx)); } this.buttonAccept.setEnabled(this.selection.size()>0); } public List getSelection() { return selection; } @Override public boolean eventFilter(QObject qo, QEvent qevent) { if( qevent.type() == QEvent.Type.KeyPress ){ QKeyEvent qke = (QKeyEvent) qevent; if( qke.key() == Qt.Key.Key_Return.value() ){ if( this.getSelection().size() > 0 ){ this.accept(); } } } return false; } }
true
true
private void init(){ this.setWindowTitle("Research and selection"); this.layout = new QVBoxLayout(this); this.layout.setSpacing(4); this.tableView = new QTableView(); this.tableView.setSizePolicy(new QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)); this.tableView.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows); this.tableView.setMinimumHeight(150); this.tableView.setSortingEnabled(true); this.tableView.installEventFilter(this); this.layout.addWidget(this.tableView, 1); this.filterLineEdit = new QLineEdit(); QLabel filterLabel = new QLabel(); filterLabel.setPixmap(new QPixmap("classpath:com/axiastudio/pypapi/ui/resources/toolbar/find.png")); this.searchLogLabel = new QLabel(); this.buttonSearch = new QToolButton(this); this.buttonSearch.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/key.png")); this.buttonSearch.clicked.connect(this, "executeSearch()"); this.buttonSearch.setShortcut(QKeySequence.StandardKey.Find); this.buttonCancel = new QToolButton(this); this.buttonCancel.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/cancel.png")); this.buttonCancel.clicked.connect(this, "reject()"); this.buttonAccept = new QToolButton(this); this.buttonAccept.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/accept.png")); this.buttonAccept.clicked.connect(this, "accept()"); QHBoxLayout buttonLayout = new QHBoxLayout(); buttonLayout.setSpacing(4); buttonLayout.addWidget(this.filterLineEdit); buttonLayout.addWidget(filterLabel); QSpacerItem spacer = new QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer); buttonLayout.addWidget(this.buttonSearch); QSpacerItem spacer2 = new QSpacerItem(40, 20, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer2); buttonLayout.addWidget(this.buttonCancel); buttonLayout.addWidget(this.buttonAccept); this.layout.addLayout(buttonLayout); this.resize(500, 300); }
private void init(){ this.setWindowTitle("Research and selection"); this.layout = new QVBoxLayout(this); this.layout.setSpacing(4); this.tableView = new QTableView(); this.tableView.setSizePolicy(new QSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)); this.tableView.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows); this.tableView.setMinimumHeight(150); this.tableView.setSortingEnabled(true); this.tableView.installEventFilter(this); this.layout.addWidget(this.tableView, 1); this.filterLineEdit = new QLineEdit(); QLabel filterLabel = new QLabel(); filterLabel.setPixmap(new QPixmap("classpath:com/axiastudio/pypapi/ui/resources/toolbar/find.png")); this.searchLogLabel = new QLabel(); this.buttonSearch = new QToolButton(this); this.buttonSearch.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/key.png")); this.buttonSearch.clicked.connect(this, "executeSearch()"); this.buttonSearch.setShortcut(QKeySequence.StandardKey.Find); this.buttonCancel = new QToolButton(this); this.buttonCancel.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/cancel.png")); this.buttonCancel.clicked.connect(this, "reject()"); this.buttonAccept = new QToolButton(this); this.buttonAccept.setIcon(new QIcon("classpath:com/axiastudio/pypapi/ui/resources/toolbar/accept.png")); this.buttonAccept.clicked.connect(this, "accept()"); this.tableView.doubleClicked.connect(this, "accept()"); QHBoxLayout buttonLayout = new QHBoxLayout(); buttonLayout.setSpacing(4); buttonLayout.addWidget(this.filterLineEdit); buttonLayout.addWidget(filterLabel); QSpacerItem spacer = new QSpacerItem(40, 20, QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer); buttonLayout.addWidget(this.buttonSearch); QSpacerItem spacer2 = new QSpacerItem(40, 20, QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Minimum); buttonLayout.addItem(spacer2); buttonLayout.addWidget(this.buttonCancel); buttonLayout.addWidget(this.buttonAccept); this.layout.addLayout(buttonLayout); this.resize(500, 300); }
diff --git a/src/me/sd5/mcbetaterraingenerator/MCBetaTerrainGenerator.java b/src/me/sd5/mcbetaterraingenerator/MCBetaTerrainGenerator.java index a5acea2..30cd9fe 100644 --- a/src/me/sd5/mcbetaterraingenerator/MCBetaTerrainGenerator.java +++ b/src/me/sd5/mcbetaterraingenerator/MCBetaTerrainGenerator.java @@ -1,99 +1,100 @@ package me.sd5.mcbetaterraingenerator; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; import me.sd5.mcbetaterraingenerator.exceptions.InvalidInputException; /** * @author sd5 * Main class. Takes user input and tells the generator which areas it has to generate. */ public class MCBetaTerrainGenerator { //The constant names of the files in the jar. public static final String jar_levelDat_b173 = "level_beta_1.7.3.dat"; public static final String jar_mcserver_b173 = "minecraft_server_beta_1.7.3.jar"; public static final String jar_mcserver_f152 = "minecraft_server_final_1.5.2.jar"; public static final String jar_serverproperties_b173 = "server_beta_1.7.3.properties"; //The constant names of the files on the hard disk. public static final String levelDat_b173 = "level.dat"; public static final String mcserver_b173 = "minecraft_server.jar"; public static final String mcserver_f152 = "minecraft_server.jar"; public static final String serverproperties_b173 = "server.properties"; //The constant paths. public static final String mainDir = "mcBetaTerrainGenerator"; public static final String genDir = mainDir + File.separator + "generation"; public static final String conDir = mainDir + File.separator + "conversion"; public static final String endDir = mainDir + File.separator + "finished"; public static final String genDirWorld = genDir + File.separator + "world"; public static final String genDirRegion = genDirWorld + File.separator + "region"; public static final String conDirWorld = conDir + File.separator + "world"; public static final String conDirRegion = conDirWorld + File.separator + "region"; public static void main(String[] args) { //A scanner to read the user's input. Scanner in = new Scanner(System.in); String areasInput; String seedInput; //Ask the user for the areas to generate. System.out.println("Areas to generate: "); System.out.println("Example: -4,-4,3,3;0,4,6,4"); System.out.print("Input: "); areasInput = in.nextLine(); //Ask the user for a seed to generate with. System.out.println(""); System.out.println("Seed for terrain generation:"); System.out.println("Leave blank for random seed."); System.out.print("Input: "); seedInput = in.nextLine(); //Close the scanner, it is no longer needed. in.close(); //Try to parse the user input into the regions which will be generated. AreaInputParser aip = new AreaInputParser(";", ","); ArrayList<Area> areas = null; try { areas = aip.parseInput(areasInput); } catch (InvalidInputException e) { e.printStackTrace(); } //Remove old files. Util.deleteFile(mainDir); //Create the needed files. try { Util.copyFileFromJar(jar_mcserver_b173, genDir + File.separator + mcserver_b173); Util.copyFileFromJar(jar_mcserver_f152, conDir + File.separator + mcserver_f152); Util.copyFileFromJar(jar_serverproperties_b173, genDir + File.separator + serverproperties_b173); Util.copyFileFromJar(jar_levelDat_b173, genDirWorld + File.separator + levelDat_b173); + Util.copyFileFromJar(jar_levelDat_b173, conDirWorld + File.separator + levelDat_b173); } catch(FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Set up a new generator with the user's seed. Generator generator = new Generator(seedInput); for(Area area : areas) { generator.generate(area); } //Automatically converts the .mcr files to .mca Converter converter = new Converter(); converter.convert(areas); } }
true
true
public static void main(String[] args) { //A scanner to read the user's input. Scanner in = new Scanner(System.in); String areasInput; String seedInput; //Ask the user for the areas to generate. System.out.println("Areas to generate: "); System.out.println("Example: -4,-4,3,3;0,4,6,4"); System.out.print("Input: "); areasInput = in.nextLine(); //Ask the user for a seed to generate with. System.out.println(""); System.out.println("Seed for terrain generation:"); System.out.println("Leave blank for random seed."); System.out.print("Input: "); seedInput = in.nextLine(); //Close the scanner, it is no longer needed. in.close(); //Try to parse the user input into the regions which will be generated. AreaInputParser aip = new AreaInputParser(";", ","); ArrayList<Area> areas = null; try { areas = aip.parseInput(areasInput); } catch (InvalidInputException e) { e.printStackTrace(); } //Remove old files. Util.deleteFile(mainDir); //Create the needed files. try { Util.copyFileFromJar(jar_mcserver_b173, genDir + File.separator + mcserver_b173); Util.copyFileFromJar(jar_mcserver_f152, conDir + File.separator + mcserver_f152); Util.copyFileFromJar(jar_serverproperties_b173, genDir + File.separator + serverproperties_b173); Util.copyFileFromJar(jar_levelDat_b173, genDirWorld + File.separator + levelDat_b173); } catch(FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Set up a new generator with the user's seed. Generator generator = new Generator(seedInput); for(Area area : areas) { generator.generate(area); } //Automatically converts the .mcr files to .mca Converter converter = new Converter(); converter.convert(areas); }
public static void main(String[] args) { //A scanner to read the user's input. Scanner in = new Scanner(System.in); String areasInput; String seedInput; //Ask the user for the areas to generate. System.out.println("Areas to generate: "); System.out.println("Example: -4,-4,3,3;0,4,6,4"); System.out.print("Input: "); areasInput = in.nextLine(); //Ask the user for a seed to generate with. System.out.println(""); System.out.println("Seed for terrain generation:"); System.out.println("Leave blank for random seed."); System.out.print("Input: "); seedInput = in.nextLine(); //Close the scanner, it is no longer needed. in.close(); //Try to parse the user input into the regions which will be generated. AreaInputParser aip = new AreaInputParser(";", ","); ArrayList<Area> areas = null; try { areas = aip.parseInput(areasInput); } catch (InvalidInputException e) { e.printStackTrace(); } //Remove old files. Util.deleteFile(mainDir); //Create the needed files. try { Util.copyFileFromJar(jar_mcserver_b173, genDir + File.separator + mcserver_b173); Util.copyFileFromJar(jar_mcserver_f152, conDir + File.separator + mcserver_f152); Util.copyFileFromJar(jar_serverproperties_b173, genDir + File.separator + serverproperties_b173); Util.copyFileFromJar(jar_levelDat_b173, genDirWorld + File.separator + levelDat_b173); Util.copyFileFromJar(jar_levelDat_b173, conDirWorld + File.separator + levelDat_b173); } catch(FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Set up a new generator with the user's seed. Generator generator = new Generator(seedInput); for(Area area : areas) { generator.generate(area); } //Automatically converts the .mcr files to .mca Converter converter = new Converter(); converter.convert(areas); }
diff --git a/src/com/android/exchange/adapter/ProvisionParser.java b/src/com/android/exchange/adapter/ProvisionParser.java index 1aff046..057ffaf 100644 --- a/src/com/android/exchange/adapter/ProvisionParser.java +++ b/src/com/android/exchange/adapter/ProvisionParser.java @@ -1,450 +1,450 @@ /* Copyright (C) 2010 The Android Open Source Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.exchange.adapter; import com.android.email.SecurityPolicy; import com.android.email.SecurityPolicy.PolicySet; import com.android.exchange.EasSyncService; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; /** * Parse the result of the Provision command * * Assuming a successful parse, we store the PolicySet and the policy key */ public class ProvisionParser extends Parser { private EasSyncService mService; PolicySet mPolicySet = null; String mPolicyKey = null; boolean mRemoteWipe = false; boolean mIsSupportable = true; public ProvisionParser(InputStream in, EasSyncService service) throws IOException { super(in); mService = service; } public PolicySet getPolicySet() { return mPolicySet; } public String getPolicyKey() { return mPolicyKey; } public boolean getRemoteWipe() { return mRemoteWipe; } public boolean hasSupportablePolicySet() { return (mPolicySet != null) && mIsSupportable; } private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; - boolean supported = true; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { + boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { - supported = false; + tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { - supported = false; + tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { - supported = false; + tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { - supported = false; + tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { - supported = false; + tagIsSupported = false; } break; // Complex character setting is only used if we're in "strong" (alphanumeric) mode case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); - if ((passwordMode == PolicySet.PASSWORD_MODE_STRONG) && + if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && (passwordComplexChars > 0)) { - supported = false; + tagIsSupported = false; } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { - supported = false; + tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { - supported = false; + tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { - supported = false; + tagIsSupported = false; } break; default: skipTag(); } - if (!supported) { + if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); } /** * Return whether or not either of the application list tags specifies any applications * @param endTag the tag whose children we're walking through * @return whether any applications were specified (by name or by hash) * @throws IOException */ private boolean specifiesApplications(int endTag) throws IOException { boolean specifiesApplications = false; while (nextTag(endTag) != END) { switch (tag) { case Tags.PROVISION_APPLICATION_NAME: case Tags.PROVISION_HASH: specifiesApplications = true; break; default: skipTag(); } } return specifiesApplications; } class ShadowPolicySet { int mMinPasswordLength = 0; int mPasswordMode = PolicySet.PASSWORD_MODE_NONE; int mMaxPasswordFails = 0; int mMaxScreenLockTime = 0; int mPasswordExpiration = 0; int mPasswordHistory = 0; int mPasswordComplexChars = 0; } /*package*/ void parseProvisionDocXml(String doc) throws IOException { ShadowPolicySet sps = new ShadowPolicySet(); try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); XmlPullParser parser = factory.newPullParser(); parser.setInput(new ByteArrayInputStream(doc.getBytes()), "UTF-8"); int type = parser.getEventType(); if (type == XmlPullParser.START_DOCUMENT) { type = parser.next(); if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("wap-provisioningdoc")) { parseWapProvisioningDoc(parser, sps); } } } } catch (XmlPullParserException e) { throw new IOException(); } mPolicySet = new PolicySet(sps.mMinPasswordLength, sps.mPasswordMode, sps.mMaxPasswordFails, sps.mMaxScreenLockTime, true, sps.mPasswordExpiration, sps.mPasswordHistory, sps.mPasswordComplexChars); } /** * Return true if password is required; otherwise false. */ private boolean parseSecurityPolicy(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean passwordRequired = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String tagName = parser.getName(); if (tagName.equals("parm")) { String name = parser.getAttributeValue(null, "name"); if (name.equals("4131")) { String value = parser.getAttributeValue(null, "value"); if (value.equals("1")) { passwordRequired = false; } } } } } return passwordRequired; } private void parseCharacteristic(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { boolean enforceInactivityTimer = true; while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { if (parser.getName().equals("parm")) { String name = parser.getAttributeValue(null, "name"); String value = parser.getAttributeValue(null, "value"); if (name.equals("AEFrequencyValue")) { if (enforceInactivityTimer) { if (value.equals("0")) { sps.mMaxScreenLockTime = 1; } else { sps.mMaxScreenLockTime = 60*Integer.parseInt(value); } } } else if (name.equals("AEFrequencyType")) { // "0" here means we don't enforce an inactivity timeout if (value.equals("0")) { enforceInactivityTimer = false; } } else if (name.equals("DeviceWipeThreshold")) { sps.mMaxPasswordFails = Integer.parseInt(value); } else if (name.equals("CodewordFrequency")) { // Ignore; has no meaning for us } else if (name.equals("MinimumPasswordLength")) { sps.mMinPasswordLength = Integer.parseInt(value); } else if (name.equals("PasswordComplexity")) { if (value.equals("0")) { sps.mPasswordMode = PolicySet.PASSWORD_MODE_STRONG; } else { sps.mPasswordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } } } } } private void parseRegistry(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("characteristic")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { parseCharacteristic(parser, sps); } } } } private void parseWapProvisioningDoc(XmlPullParser parser, ShadowPolicySet sps) throws XmlPullParserException, IOException { while (true) { int type = parser.nextTag(); if (type == XmlPullParser.END_TAG && parser.getName().equals("wap-provisioningdoc")) { break; } else if (type == XmlPullParser.START_TAG) { String name = parser.getName(); if (name.equals("characteristic")) { String atype = parser.getAttributeValue(null, "type"); if (atype.equals("SecurityPolicy")) { // If a password isn't required, stop here if (!parseSecurityPolicy(parser, sps)) { return; } } else if (atype.equals("Registry")) { parseRegistry(parser, sps); return; } } } } } private void parseProvisionData() throws IOException { while (nextTag(Tags.PROVISION_DATA) != END) { if (tag == Tags.PROVISION_EAS_PROVISION_DOC) { parseProvisionDocWbxml(); } else { skipTag(); } } } private void parsePolicy() throws IOException { String policyType = null; while (nextTag(Tags.PROVISION_POLICY) != END) { switch (tag) { case Tags.PROVISION_POLICY_TYPE: policyType = getValue(); mService.userLog("Policy type: ", policyType); break; case Tags.PROVISION_POLICY_KEY: mPolicyKey = getValue(); break; case Tags.PROVISION_STATUS: mService.userLog("Policy status: ", getValue()); break; case Tags.PROVISION_DATA: if (policyType.equalsIgnoreCase(EasSyncService.EAS_2_POLICY_TYPE)) { // Parse the old style XML document parseProvisionDocXml(getValue()); } else { // Parse the newer WBXML data parseProvisionData(); } break; default: skipTag(); } } } private void parsePolicies() throws IOException { while (nextTag(Tags.PROVISION_POLICIES) != END) { if (tag == Tags.PROVISION_POLICY) { parsePolicy(); } else { skipTag(); } } } @Override public boolean parse() throws IOException { boolean res = false; if (nextTag(START_DOCUMENT) != Tags.PROVISION_PROVISION) { throw new IOException(); } while (nextTag(START_DOCUMENT) != END_DOCUMENT) { switch (tag) { case Tags.PROVISION_STATUS: int status = getValueInt(); mService.userLog("Provision status: ", status); res = (status == 1); break; case Tags.PROVISION_POLICIES: parsePolicies(); break; case Tags.PROVISION_REMOTE_WIPE: // Indicate remote wipe command received mRemoteWipe = true; break; default: skipTag(); } } return res; } }
false
true
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; boolean supported = true; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { supported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { supported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { supported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { supported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { supported = false; } break; // Complex character setting is only used if we're in "strong" (alphanumeric) mode case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); if ((passwordMode == PolicySet.PASSWORD_MODE_STRONG) && (passwordComplexChars > 0)) { supported = false; } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { supported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { supported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { supported = false; } break; default: skipTag(); } if (!supported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
private void parseProvisionDocWbxml() throws IOException { int minPasswordLength = 0; int passwordMode = PolicySet.PASSWORD_MODE_NONE; int maxPasswordFails = 0; int maxScreenLockTime = 0; int passwordExpiration = 0; int passwordHistory = 0; int passwordComplexChars = 0; while (nextTag(Tags.PROVISION_EAS_PROVISION_DOC) != END) { boolean tagIsSupported = true; switch (tag) { case Tags.PROVISION_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { if (passwordMode == PolicySet.PASSWORD_MODE_NONE) { passwordMode = PolicySet.PASSWORD_MODE_SIMPLE; } } break; case Tags.PROVISION_MIN_DEVICE_PASSWORD_LENGTH: minPasswordLength = getValueInt(); break; case Tags.PROVISION_ALPHA_DEVICE_PASSWORD_ENABLED: if (getValueInt() == 1) { passwordMode = PolicySet.PASSWORD_MODE_STRONG; } break; case Tags.PROVISION_MAX_INACTIVITY_TIME_DEVICE_LOCK: // EAS gives us seconds, which is, happily, what the PolicySet requires maxScreenLockTime = getValueInt(); break; case Tags.PROVISION_MAX_DEVICE_PASSWORD_FAILED_ATTEMPTS: maxPasswordFails = getValueInt(); break; case Tags.PROVISION_DEVICE_PASSWORD_EXPIRATION: passwordExpiration = getValueInt(); // We don't yet support this if (passwordExpiration > 0) { tagIsSupported = false; } break; case Tags.PROVISION_DEVICE_PASSWORD_HISTORY: passwordHistory = getValueInt(); break; case Tags.PROVISION_ALLOW_SIMPLE_DEVICE_PASSWORD: // Ignore this unless there's any MSFT documentation for what this means // Hint: I haven't seen any that's more specific than "simple" getValue(); break; // The following policies, if false, can't be supported at the moment case Tags.PROVISION_ATTACHMENTS_ENABLED: case Tags.PROVISION_ALLOW_STORAGE_CARD: case Tags.PROVISION_ALLOW_CAMERA: case Tags.PROVISION_ALLOW_UNSIGNED_APPLICATIONS: case Tags.PROVISION_ALLOW_UNSIGNED_INSTALLATION_PACKAGES: case Tags.PROVISION_ALLOW_WIFI: case Tags.PROVISION_ALLOW_TEXT_MESSAGING: case Tags.PROVISION_ALLOW_POP_IMAP_EMAIL: case Tags.PROVISION_ALLOW_IRDA: case Tags.PROVISION_ALLOW_HTML_EMAIL: case Tags.PROVISION_ALLOW_BROWSER: case Tags.PROVISION_ALLOW_CONSUMER_EMAIL: case Tags.PROVISION_ALLOW_INTERNET_SHARING: if (getValueInt() == 0) { tagIsSupported = false; } break; // Bluetooth: 0 = no bluetooth; 1 = only hands-free; 2 = allowed case Tags.PROVISION_ALLOW_BLUETOOTH: if (getValueInt() != 2) { tagIsSupported = false; } break; // The following policies, if true, can't be supported at the moment case Tags.PROVISION_DEVICE_ENCRYPTION_ENABLED: case Tags.PROVISION_PASSWORD_RECOVERY_ENABLED: case Tags.PROVISION_REQUIRE_DEVICE_ENCRYPTION: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_ENCRYPTED_SMIME_MESSAGES: case Tags.PROVISION_REQUIRE_SIGNED_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_ENCRYPTION_SMIME_ALGORITHM: case Tags.PROVISION_REQUIRE_MANUAL_SYNC_WHEN_ROAMING: if (getValueInt() == 1) { tagIsSupported = false; } break; // The following, if greater than zero, can't be supported at the moment case Tags.PROVISION_MAX_ATTACHMENT_SIZE: if (getValueInt() > 0) { tagIsSupported = false; } break; // Complex character setting is only used if we're in "strong" (alphanumeric) mode case Tags.PROVISION_MIN_DEVICE_PASSWORD_COMPLEX_CHARS: passwordComplexChars = getValueInt(); if ((passwordMode != PolicySet.PASSWORD_MODE_STRONG) && (passwordComplexChars > 0)) { tagIsSupported = false; } break; // The following policies are moot; they allow functionality that we don't support case Tags.PROVISION_ALLOW_DESKTOP_SYNC: case Tags.PROVISION_ALLOW_SMIME_ENCRYPTION_NEGOTIATION: case Tags.PROVISION_ALLOW_SMIME_SOFT_CERTS: case Tags.PROVISION_ALLOW_REMOTE_DESKTOP: skipTag(); break; // We don't handle approved/unapproved application lists case Tags.PROVISION_UNAPPROVED_IN_ROM_APPLICATION_LIST: case Tags.PROVISION_APPROVED_APPLICATION_LIST: // Parse and throw away the content if (specifiesApplications(tag)) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_CALENDAR_AGE_FILTER: case Tags.PROVISION_MAX_EMAIL_AGE_FILTER: // 0 indicates no specified filter if (getValueInt() != 0) { tagIsSupported = false; } break; // NOTE: We can support these entirely within the email application if we choose case Tags.PROVISION_MAX_EMAIL_BODY_TRUNCATION_SIZE: case Tags.PROVISION_MAX_EMAIL_HTML_BODY_TRUNCATION_SIZE: String value = getValue(); // -1 indicates no required truncation if (!value.equals("-1")) { tagIsSupported = false; } break; default: skipTag(); } if (!tagIsSupported) { log("Policy not supported: " + tag); mIsSupportable = false; } } mPolicySet = new SecurityPolicy.PolicySet(minPasswordLength, passwordMode, maxPasswordFails, maxScreenLockTime, true, passwordExpiration, passwordHistory, passwordComplexChars); }
diff --git a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/internal/renderers/IEditorRendererExtensionRegistry.java b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/internal/renderers/IEditorRendererExtensionRegistry.java index 14e5fb7f..d4b12b2a 100644 --- a/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/internal/renderers/IEditorRendererExtensionRegistry.java +++ b/plugins/org.eclipse.mylyn.docs.intent.client.ui/src/org/eclipse/mylyn/docs/intent/client/ui/internal/renderers/IEditorRendererExtensionRegistry.java @@ -1,146 +1,146 @@ /******************************************************************************* * Copyright (c) 2010, 2011 Obeo. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Obeo - initial API and implementation *******************************************************************************/ package org.eclipse.mylyn.docs.intent.client.ui.internal.renderers; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.eclipse.mylyn.docs.intent.client.ui.editor.renderers.IEditorRendererExtension; import org.eclipse.mylyn.docs.intent.core.modelingunit.ExternalContentReference; /** * Registry containing all Lock Strategy extensions that have been parsed from the * {@link IEditorRendererExtensionRegistryListener#RENDERER_EXTENSION_POINT} extension point. * * @author <a href="mailto:[email protected]">Alex Lagarde</a> */ public final class IEditorRendererExtensionRegistry { /** * The registered {@link ISaveDialogExtension}s. */ private static final Map<IEditorRendererExtension, Collection<IEditorRendererExtensionDescriptor>> EXTENSIONS = Maps .newHashMap(); /** * Utility classes don't need a default constructor. */ private IEditorRendererExtensionRegistry() { } /** * Adds an extension to the registry, with the given behavior. * * @param extensionDescriptor * The extension that is to be added to the registry */ public static void addExtension(IEditorRendererExtensionDescriptor extensionDescriptor) { IEditorRendererExtension extension = extensionDescriptor.getEditorRendererExtension(); if (EXTENSIONS.get(extension) == null) { EXTENSIONS.put(extension, new HashSet<IEditorRendererExtensionDescriptor>()); } EXTENSIONS.get(extension).add(extensionDescriptor); } /** * Removes all extensions from the registry. This will be called at plugin stopping. */ public static void clearRegistry() { EXTENSIONS.clear(); } /** * Returns a copy of the registered extensions list. * * @return A copy of the registered extensions list. */ public static Collection<IEditorRendererExtensionDescriptor> getRegisteredExtensions() { Set<IEditorRendererExtensionDescriptor> registeredExtensions = Sets.newHashSet(); for (Collection<IEditorRendererExtensionDescriptor> extensions : EXTENSIONS.values()) { registeredExtensions.addAll(extensions); } return registeredExtensions; } /** * Returns all the registered {@link IEditorRendererExtension}s defined for the given * {@link ExternalContentReference}, sorted by priority. * * @param externalContentReference * the {@link ExternalContentReference} to render * @return all the registered {@link IEditorRendererExtension}s defined for the given * {@link ExternalContentReference} */ public static Collection<IEditorRendererExtension> getEditorRendererExtensions( ExternalContentReference externalContentReference) { List<IEditorRendererExtensionDescriptor> registeredExtensions = Lists.newArrayList(); // Step 1: get all valid extension for (Collection<IEditorRendererExtensionDescriptor> extensions : EXTENSIONS.values()) { for (IEditorRendererExtensionDescriptor descriptor : extensions) { if (descriptor.getEditorRendererExtension().isRendererFor(externalContentReference)) { registeredExtensions.add(descriptor); } } } // Step 2: sort by priority Collections.sort(registeredExtensions, new Comparator<IEditorRendererExtensionDescriptor>() { public int compare(IEditorRendererExtensionDescriptor o1, IEditorRendererExtensionDescriptor o2) { - return o1.getPriority() - o2.getPriority(); + return o2.getPriority() - o1.getPriority(); } }); // Step 3: return corresponding editor render Collection<IEditorRendererExtension> editorRenders = Sets.newLinkedHashSet(); for (IEditorRendererExtensionDescriptor descriptor : registeredExtensions) { editorRenders.add(descriptor.getEditorRendererExtension()); } return editorRenders; } /** * Returns all the registered {@link IEditorRendererExtension}s. * * @return all the registered {@link IEditorRendererExtension}s */ public static Collection<IEditorRendererExtension> getEditorRendererExtensions() { return EXTENSIONS.keySet(); } /** * Removes a phantom from the registry. * * @param extensionClassName * Qualified class name of the sync element which corresponding phantom is to be removed from * the registry. */ public static void removeExtension(String extensionClassName) { for (IEditorRendererExtensionDescriptor extension : getRegisteredExtensions()) { if (extension.getExtensionClassName().equals(extensionClassName)) { EXTENSIONS.get(extension).clear(); } } } }
true
true
public static Collection<IEditorRendererExtension> getEditorRendererExtensions( ExternalContentReference externalContentReference) { List<IEditorRendererExtensionDescriptor> registeredExtensions = Lists.newArrayList(); // Step 1: get all valid extension for (Collection<IEditorRendererExtensionDescriptor> extensions : EXTENSIONS.values()) { for (IEditorRendererExtensionDescriptor descriptor : extensions) { if (descriptor.getEditorRendererExtension().isRendererFor(externalContentReference)) { registeredExtensions.add(descriptor); } } } // Step 2: sort by priority Collections.sort(registeredExtensions, new Comparator<IEditorRendererExtensionDescriptor>() { public int compare(IEditorRendererExtensionDescriptor o1, IEditorRendererExtensionDescriptor o2) { return o1.getPriority() - o2.getPriority(); } }); // Step 3: return corresponding editor render Collection<IEditorRendererExtension> editorRenders = Sets.newLinkedHashSet(); for (IEditorRendererExtensionDescriptor descriptor : registeredExtensions) { editorRenders.add(descriptor.getEditorRendererExtension()); } return editorRenders; }
public static Collection<IEditorRendererExtension> getEditorRendererExtensions( ExternalContentReference externalContentReference) { List<IEditorRendererExtensionDescriptor> registeredExtensions = Lists.newArrayList(); // Step 1: get all valid extension for (Collection<IEditorRendererExtensionDescriptor> extensions : EXTENSIONS.values()) { for (IEditorRendererExtensionDescriptor descriptor : extensions) { if (descriptor.getEditorRendererExtension().isRendererFor(externalContentReference)) { registeredExtensions.add(descriptor); } } } // Step 2: sort by priority Collections.sort(registeredExtensions, new Comparator<IEditorRendererExtensionDescriptor>() { public int compare(IEditorRendererExtensionDescriptor o1, IEditorRendererExtensionDescriptor o2) { return o2.getPriority() - o1.getPriority(); } }); // Step 3: return corresponding editor render Collection<IEditorRendererExtension> editorRenders = Sets.newLinkedHashSet(); for (IEditorRendererExtensionDescriptor descriptor : registeredExtensions) { editorRenders.add(descriptor.getEditorRendererExtension()); } return editorRenders; }
diff --git a/src/org/python/util/jython.java b/src/org/python/util/jython.java index daf46c6d..e619e9b3 100644 --- a/src/org/python/util/jython.java +++ b/src/org/python/util/jython.java @@ -1,547 +1,547 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.List; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.python.Version; import org.python.core.CodeFlag; import org.python.core.CompileMode; import org.python.core.Options; import org.python.core.Py; import org.python.core.PyCode; import org.python.core.PyException; import org.python.core.PyFile; import org.python.core.PyList; import org.python.core.PyString; import org.python.core.PyStringMap; import org.python.core.PySystemState; import org.python.core.imp; import org.python.core.util.RelativeFile; import org.python.modules._systemrestart; import org.python.modules.posix.PosixModule; import org.python.modules.thread.thread; public class jython { private static final String COPYRIGHT = "Type \"help\", \"copyright\", \"credits\" or \"license\" for more information."; static final String usageHeader = "usage: jython [option] ... [-c cmd | -m mod | file | -] [arg] ...\n"; private static final String usage = usageHeader + "Options and arguments:\n" + //(and corresponding environment variables):\n" + "-c cmd : program passed in as string (terminates option list)\n" + //"-d : debug output from parser (also PYTHONDEBUG=x)\n" + "-Dprop=v : Set the property `prop' to value `v'\n"+ //"-E : ignore environment variables (such as PYTHONPATH)\n" + "-C codec : Use a different codec when reading from the console.\n"+ "-h : print this help message and exit (also --help)\n" + "-i : inspect interactively after running script\n" + //, (also PYTHONINSPECT=x)\n" + " and force prompts, even if stdin does not appear to be a terminal\n" + "-jar jar : program read from __run__.py in jar file\n"+ "-m mod : run library module as a script (terminates option list)\n" + //"-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)\n" + //"-OO : remove doc-strings in addition to the -O optimizations\n" + "-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n" + "-S : don't imply 'import site' on initialization\n" + //"-t : issue warnings about inconsistent tab usage (-tt: issue errors)\n" + "-u : unbuffered binary stdout and stderr\n" + // (also PYTHONUNBUFFERED=x)\n" + //" see man page for details on internal buffering relating to '-u'\n" + "-v : verbose (trace import statements)\n" + // (also PYTHONVERBOSE=x)\n" + "-V : print the Python version number and exit (also --version)\n" + "-W arg : warning control (arg is action:message:category:module:lineno)\n" + //"-x : skip first line of source, allowing use of non-Unix forms of #!cmd\n" + "file : program read from script file\n" + "- : program read from stdin (default; interactive mode if a tty)\n" + "arg ... : arguments passed to program in sys.argv[1:]\n" + "Other environment variables:\n" + "JYTHONPATH: '" + File.pathSeparator + "'-separated list of directories prefixed to the default module\n" + " search path. The result is sys.path."; public static boolean shouldRestart; /** * Runs a JAR file, by executing the code found in the file __run__.py, * which should be in the root of the JAR archive. * * Note that the __name__ is set to the base name of the JAR file and not * to "__main__" (for historic reasons). * * This method do NOT handle exceptions. the caller SHOULD handle any * (Py)Exceptions thrown by the code. * * @param filename The path to the filename to run. */ public static void runJar(String filename) { // TBD: this is kind of gross because a local called `zipfile' just magically // shows up in the module's globals. Either `zipfile' should be called // `__zipfile__' or (preferrably, IMO), __run__.py should be imported and a main() // function extracted. This function should be called passing zipfile in as an // argument. // // Probably have to keep this code around for backwards compatibility (?) try { ZipFile zip = new ZipFile(filename); ZipEntry runit = zip.getEntry("__run__.py"); if (runit == null) { throw Py.ValueError("jar file missing '__run__.py'"); } PyStringMap locals = new PyStringMap(); // Stripping the stuff before the last File.separator fixes Bug #931129 by // keeping illegal characters out of the generated proxy class name int beginIndex; if ((beginIndex = filename.lastIndexOf(File.separator)) != -1) { filename = filename.substring(beginIndex + 1); } locals.__setitem__("__name__", new PyString(filename)); locals.__setitem__("zipfile", Py.java2py(zip)); InputStream file = zip.getInputStream(runit); PyCode code; try { code = Py.compile(file, "__run__", CompileMode.exec); } finally { file.close(); } Py.runCode(code, locals, locals); } catch (IOException e) { throw Py.IOError(e); } } public static void main(String[] args) { do { shouldRestart = false; run(args); } while (shouldRestart); } public static void run(String[] args) { // Parse the command line options CommandLineOptions opts = new CommandLineOptions(); if (!opts.parse(args)) { if (opts.version) { System.err.println("Jython " + Version.PY_VERSION); System.exit(0); } if (!opts.runCommand && !opts.runModule) { System.err.println(usage); } int exitcode = opts.help ? 0 : -1; System.exit(exitcode); } // Setup the basic python system state from these options PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv); PyList warnoptions = new PyList(); for (String wopt : opts.warnoptions) { warnoptions.append(new PyString(wopt)); } Py.getSystemState().setWarnoptions(warnoptions); PySystemState systemState = Py.getSystemState(); // Decide if stdin is interactive - if (!opts.fixInteractive && opts.interactive) { + if (!opts.fixInteractive || opts.interactive) { opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty(); if (!opts.interactive) { systemState.ps1 = systemState.ps2 = Py.EmptyString; } } // Now create an interpreter InteractiveConsole interp = newInterpreter(opts.interactive); systemState.__setattr__("_jy_interpreter", Py.java2py(interp)); // Print banner and copyright information (or not) if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(InteractiveConsole.getDefaultBanner()); } if (Options.importSite) { try { imp.load("site"); if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(COPYRIGHT); } } catch (PyException pye) { if (!pye.match(Py.ImportError)) { System.err.println("error importing site"); Py.printException(pye); System.exit(-1); } } } if (opts.division != null) { if ("old".equals(opts.division)) { Options.divisionWarning = 0; } else if ("warn".equals(opts.division)) { Options.divisionWarning = 1; } else if ("warnall".equals(opts.division)) { Options.divisionWarning = 2; } else if ("new".equals(opts.division)) { Options.Qnew = true; interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION); } } // was there a filename on the command line? if (opts.filename != null) { String path; try { path = new File(opts.filename).getCanonicalFile().getParent(); } catch (IOException ioe) { path = new File(opts.filename).getAbsoluteFile().getParent(); } if (path == null) { path = ""; } Py.getSystemState().path.insert(0, new PyString(path)); if (opts.jar) { try { runJar(opts.filename); } catch (Throwable t) { Py.printException(t); System.exit(-1); } } else if (opts.filename.equals("-")) { try { interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>")); interp.execfile(System.in, "<stdin>"); } catch (Throwable t) { Py.printException(t); } } else { try { interp.globals.__setitem__(new PyString("__file__"), new PyString(opts.filename)); FileInputStream file; try { file = new FileInputStream(new RelativeFile(opts.filename)); } catch (FileNotFoundException e) { throw Py.IOError(e); } try { if (PosixModule.getPOSIX().isatty(file.getFD())) { opts.interactive = true; interp.interact(null, new PyFile(file)); System.exit(0); } else { interp.execfile(file, opts.filename); } } finally { file.close(); } } catch (Throwable t) { if (t instanceof PyException && ((PyException)t).match(_systemrestart.SystemRestart)) { // Shutdown this instance... shouldRestart = true; shutdownInterpreter(); interp.cleanup(); // ..reset the state... Py.setSystemState(new PySystemState()); // ...and start again return; } else { Py.printException(t); if (!opts.interactive) { interp.cleanup(); System.exit(-1); } } } } } else { // if there was no file name on the command line, then "" is the first element // on sys.path. This is here because if there /was/ a filename on the c.l., // and say the -i option was given, sys.path[0] will have gotten filled in // with the dir of the argument filename. Py.getSystemState().path.insert(0, Py.EmptyString); if (opts.command != null) { try { interp.exec(opts.command); } catch (Throwable t) { Py.printException(t); System.exit(1); } } if (opts.moduleName != null) { // PEP 338 - Execute module as a script try { interp.exec("import runpy"); interp.set("name", Py.newString(opts.moduleName)); interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)"); interp.cleanup(); System.exit(0); } catch (Throwable t) { Py.printException(t); interp.cleanup(); System.exit(-1); } } } if (opts.fixInteractive || (opts.filename == null && opts.command == null)) { if (opts.encoding == null) { opts.encoding = PySystemState.registry.getProperty("python.console.encoding"); } if (opts.encoding != null) { if (!Charset.isSupported(opts.encoding)) { System.err.println(opts.encoding + " is not a supported encoding on this JVM, so it can't " + "be used in python.console.encoding."); System.exit(1); } interp.cflags.encoding = opts.encoding; } try { interp.interact(null, null); } catch (Throwable t) { Py.printException(t); } } interp.cleanup(); if (opts.fixInteractive || opts.interactive) { System.exit(0); } } /** * Returns a new python interpreter using the InteractiveConsole subclass from the * <tt>python.console</tt> registry key. * <p> * When stdin is interactive the default is {@link JLineConsole}. Otherwise the * featureless {@link InteractiveConsole} is always used as alternative consoles cause * unexpected behavior with the std file streams. */ private static InteractiveConsole newInterpreter(boolean interactiveStdin) { if (!interactiveStdin) { return new InteractiveConsole(); } String interpClass = PySystemState.registry.getProperty("python.console", ""); if (interpClass.length() > 0) { try { return (InteractiveConsole)Class.forName(interpClass).newInstance(); } catch (Throwable t) { // fall through } } return new JLineConsole(); } /** * Run any finalizations on the current interpreter in preparation for a SytemRestart. */ public static void shutdownInterpreter() { // Stop all the active threads and signal the SystemRestart thread.interruptAllThreads(); Py.getSystemState()._systemRestart = true; // Close all sockets -- not all of their operations are stopped by // Thread.interrupt (in particular pre-nio sockets) try { imp.load("socket").__findattr__("_closeActiveSockets").__call__(); } catch (PyException pye) { // continue } } } class CommandLineOptions { public String filename; public boolean jar, interactive, notice; public boolean runCommand, runModule; public boolean fixInteractive; public boolean help, version; public String[] argv; public Properties properties; public String command; public List<String> warnoptions = Generic.list(); public String encoding; public String division; public String moduleName; public CommandLineOptions() { filename = null; jar = fixInteractive = false; interactive = notice = true; runModule = false; properties = new Properties(); help = version = false; } public void setProperty(String key, String value) { properties.put(key, value); try { System.setProperty(key, value); } catch (SecurityException e) { // continue } } public boolean parse(String[] args) { int index = 0; while (index < args.length && args[index].startsWith("-")) { String arg = args[index]; if (arg.equals("-h") || arg.equals("-?") || arg.equals("--help")) { help = true; return false; } else if (arg.equals("-V") || arg.equals("--version")) { version = true; return false; } else if (arg.equals("-")) { if (!fixInteractive) { interactive = false; } filename = "-"; } else if (arg.equals("-i")) { fixInteractive = true; interactive = true; } else if (arg.equals("-jar")) { jar = true; if (!fixInteractive) { interactive = false; } } else if (arg.equals("-u")) { Options.unbuffered = true; } else if (arg.equals("-v")) { Options.verbose++; } else if (arg.equals("-vv")) { Options.verbose += 2; } else if (arg.equals("-vvv")) { Options.verbose +=3 ; } else if (arg.equals("-S")) { Options.importSite = false; } else if (arg.equals("-c")) { runCommand = true; if (arg.length() > 2) { command = arg.substring(2); } else if ((index + 1) < args.length) { command = args[++index]; } else { System.err.println("Argument expected for the -c option"); System.err.print(jython.usageHeader); System.err.println("Try `jython -h' for more information."); return false; } if (!fixInteractive) { interactive = false; } index++; break; } else if (arg.equals("-W")) { warnoptions.add(args[++index]); } else if (arg.equals("-C")) { encoding = args[++index]; setProperty("python.console.encoding", encoding); } else if (arg.equals("-E")) { // XXX: accept -E (ignore environment variables) to be compatiable with // CPython. do nothing for now (we could ignore the registry) } else if (arg.startsWith("-D")) { String key = null; String value = null; int equals = arg.indexOf("="); if (equals == -1) { String arg2 = args[++index]; key = arg.substring(2, arg.length()); value = arg2; } else { key = arg.substring(2, equals); value = arg.substring(equals + 1, arg.length()); } setProperty(key, value); } else if (arg.startsWith("-Q")) { if (arg.length() > 2) { division = arg.substring(2); } else { division = args[++index]; } } else if (arg.startsWith("-m")) { runModule = true; if (arg.length() > 2) { moduleName = arg.substring(2); } else if ((index + 1) < args.length) { moduleName = args[++index]; } else { System.err.println("Argument expected for the -m option"); System.err.print(jython.usageHeader); System.err.println("Try `jython -h' for more information."); return false; } if (!fixInteractive) { interactive = false; } index++; int n = args.length - index + 1; argv = new String[n]; argv[0] = moduleName; for (int i = 1; index < args.length; i++, index++) { argv[i] = args[index]; } return true; } else { String opt = args[index]; if (opt.startsWith("--")) { opt = opt.substring(2); } else if (opt.startsWith("-")) { opt = opt.substring(1); } System.err.println("Unknown option: " + opt); return false; } index += 1; } notice = interactive; if (filename == null && index < args.length && command == null) { filename = args[index++]; if (!fixInteractive) { interactive = false; } notice = false; } if (command != null) { notice = false; } int n = args.length - index + 1; argv = new String[n]; if (filename != null) { argv[0] = filename; } else if (command != null) { argv[0] = "-c"; } else { argv[0] = ""; } for (int i = 1; i < n; i++, index++) { argv[i] = args[index]; } return true; } }
true
true
public static void run(String[] args) { // Parse the command line options CommandLineOptions opts = new CommandLineOptions(); if (!opts.parse(args)) { if (opts.version) { System.err.println("Jython " + Version.PY_VERSION); System.exit(0); } if (!opts.runCommand && !opts.runModule) { System.err.println(usage); } int exitcode = opts.help ? 0 : -1; System.exit(exitcode); } // Setup the basic python system state from these options PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv); PyList warnoptions = new PyList(); for (String wopt : opts.warnoptions) { warnoptions.append(new PyString(wopt)); } Py.getSystemState().setWarnoptions(warnoptions); PySystemState systemState = Py.getSystemState(); // Decide if stdin is interactive if (!opts.fixInteractive && opts.interactive) { opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty(); if (!opts.interactive) { systemState.ps1 = systemState.ps2 = Py.EmptyString; } } // Now create an interpreter InteractiveConsole interp = newInterpreter(opts.interactive); systemState.__setattr__("_jy_interpreter", Py.java2py(interp)); // Print banner and copyright information (or not) if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(InteractiveConsole.getDefaultBanner()); } if (Options.importSite) { try { imp.load("site"); if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(COPYRIGHT); } } catch (PyException pye) { if (!pye.match(Py.ImportError)) { System.err.println("error importing site"); Py.printException(pye); System.exit(-1); } } } if (opts.division != null) { if ("old".equals(opts.division)) { Options.divisionWarning = 0; } else if ("warn".equals(opts.division)) { Options.divisionWarning = 1; } else if ("warnall".equals(opts.division)) { Options.divisionWarning = 2; } else if ("new".equals(opts.division)) { Options.Qnew = true; interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION); } } // was there a filename on the command line? if (opts.filename != null) { String path; try { path = new File(opts.filename).getCanonicalFile().getParent(); } catch (IOException ioe) { path = new File(opts.filename).getAbsoluteFile().getParent(); } if (path == null) { path = ""; } Py.getSystemState().path.insert(0, new PyString(path)); if (opts.jar) { try { runJar(opts.filename); } catch (Throwable t) { Py.printException(t); System.exit(-1); } } else if (opts.filename.equals("-")) { try { interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>")); interp.execfile(System.in, "<stdin>"); } catch (Throwable t) { Py.printException(t); } } else { try { interp.globals.__setitem__(new PyString("__file__"), new PyString(opts.filename)); FileInputStream file; try { file = new FileInputStream(new RelativeFile(opts.filename)); } catch (FileNotFoundException e) { throw Py.IOError(e); } try { if (PosixModule.getPOSIX().isatty(file.getFD())) { opts.interactive = true; interp.interact(null, new PyFile(file)); System.exit(0); } else { interp.execfile(file, opts.filename); } } finally { file.close(); } } catch (Throwable t) { if (t instanceof PyException && ((PyException)t).match(_systemrestart.SystemRestart)) { // Shutdown this instance... shouldRestart = true; shutdownInterpreter(); interp.cleanup(); // ..reset the state... Py.setSystemState(new PySystemState()); // ...and start again return; } else { Py.printException(t); if (!opts.interactive) { interp.cleanup(); System.exit(-1); } } } } } else { // if there was no file name on the command line, then "" is the first element // on sys.path. This is here because if there /was/ a filename on the c.l., // and say the -i option was given, sys.path[0] will have gotten filled in // with the dir of the argument filename. Py.getSystemState().path.insert(0, Py.EmptyString); if (opts.command != null) { try { interp.exec(opts.command); } catch (Throwable t) { Py.printException(t); System.exit(1); } } if (opts.moduleName != null) { // PEP 338 - Execute module as a script try { interp.exec("import runpy"); interp.set("name", Py.newString(opts.moduleName)); interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)"); interp.cleanup(); System.exit(0); } catch (Throwable t) { Py.printException(t); interp.cleanup(); System.exit(-1); } } } if (opts.fixInteractive || (opts.filename == null && opts.command == null)) { if (opts.encoding == null) { opts.encoding = PySystemState.registry.getProperty("python.console.encoding"); } if (opts.encoding != null) { if (!Charset.isSupported(opts.encoding)) { System.err.println(opts.encoding + " is not a supported encoding on this JVM, so it can't " + "be used in python.console.encoding."); System.exit(1); } interp.cflags.encoding = opts.encoding; } try { interp.interact(null, null); } catch (Throwable t) { Py.printException(t); } } interp.cleanup(); if (opts.fixInteractive || opts.interactive) { System.exit(0); } }
public static void run(String[] args) { // Parse the command line options CommandLineOptions opts = new CommandLineOptions(); if (!opts.parse(args)) { if (opts.version) { System.err.println("Jython " + Version.PY_VERSION); System.exit(0); } if (!opts.runCommand && !opts.runModule) { System.err.println(usage); } int exitcode = opts.help ? 0 : -1; System.exit(exitcode); } // Setup the basic python system state from these options PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv); PyList warnoptions = new PyList(); for (String wopt : opts.warnoptions) { warnoptions.append(new PyString(wopt)); } Py.getSystemState().setWarnoptions(warnoptions); PySystemState systemState = Py.getSystemState(); // Decide if stdin is interactive if (!opts.fixInteractive || opts.interactive) { opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty(); if (!opts.interactive) { systemState.ps1 = systemState.ps2 = Py.EmptyString; } } // Now create an interpreter InteractiveConsole interp = newInterpreter(opts.interactive); systemState.__setattr__("_jy_interpreter", Py.java2py(interp)); // Print banner and copyright information (or not) if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(InteractiveConsole.getDefaultBanner()); } if (Options.importSite) { try { imp.load("site"); if (opts.interactive && opts.notice && !opts.runModule) { System.err.println(COPYRIGHT); } } catch (PyException pye) { if (!pye.match(Py.ImportError)) { System.err.println("error importing site"); Py.printException(pye); System.exit(-1); } } } if (opts.division != null) { if ("old".equals(opts.division)) { Options.divisionWarning = 0; } else if ("warn".equals(opts.division)) { Options.divisionWarning = 1; } else if ("warnall".equals(opts.division)) { Options.divisionWarning = 2; } else if ("new".equals(opts.division)) { Options.Qnew = true; interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION); } } // was there a filename on the command line? if (opts.filename != null) { String path; try { path = new File(opts.filename).getCanonicalFile().getParent(); } catch (IOException ioe) { path = new File(opts.filename).getAbsoluteFile().getParent(); } if (path == null) { path = ""; } Py.getSystemState().path.insert(0, new PyString(path)); if (opts.jar) { try { runJar(opts.filename); } catch (Throwable t) { Py.printException(t); System.exit(-1); } } else if (opts.filename.equals("-")) { try { interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>")); interp.execfile(System.in, "<stdin>"); } catch (Throwable t) { Py.printException(t); } } else { try { interp.globals.__setitem__(new PyString("__file__"), new PyString(opts.filename)); FileInputStream file; try { file = new FileInputStream(new RelativeFile(opts.filename)); } catch (FileNotFoundException e) { throw Py.IOError(e); } try { if (PosixModule.getPOSIX().isatty(file.getFD())) { opts.interactive = true; interp.interact(null, new PyFile(file)); System.exit(0); } else { interp.execfile(file, opts.filename); } } finally { file.close(); } } catch (Throwable t) { if (t instanceof PyException && ((PyException)t).match(_systemrestart.SystemRestart)) { // Shutdown this instance... shouldRestart = true; shutdownInterpreter(); interp.cleanup(); // ..reset the state... Py.setSystemState(new PySystemState()); // ...and start again return; } else { Py.printException(t); if (!opts.interactive) { interp.cleanup(); System.exit(-1); } } } } } else { // if there was no file name on the command line, then "" is the first element // on sys.path. This is here because if there /was/ a filename on the c.l., // and say the -i option was given, sys.path[0] will have gotten filled in // with the dir of the argument filename. Py.getSystemState().path.insert(0, Py.EmptyString); if (opts.command != null) { try { interp.exec(opts.command); } catch (Throwable t) { Py.printException(t); System.exit(1); } } if (opts.moduleName != null) { // PEP 338 - Execute module as a script try { interp.exec("import runpy"); interp.set("name", Py.newString(opts.moduleName)); interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)"); interp.cleanup(); System.exit(0); } catch (Throwable t) { Py.printException(t); interp.cleanup(); System.exit(-1); } } } if (opts.fixInteractive || (opts.filename == null && opts.command == null)) { if (opts.encoding == null) { opts.encoding = PySystemState.registry.getProperty("python.console.encoding"); } if (opts.encoding != null) { if (!Charset.isSupported(opts.encoding)) { System.err.println(opts.encoding + " is not a supported encoding on this JVM, so it can't " + "be used in python.console.encoding."); System.exit(1); } interp.cflags.encoding = opts.encoding; } try { interp.interact(null, null); } catch (Throwable t) { Py.printException(t); } } interp.cleanup(); if (opts.fixInteractive || opts.interactive) { System.exit(0); } }
diff --git a/src/org/python/core/__builtin__.java b/src/org/python/core/__builtin__.java index bee31527..f058add3 100644 --- a/src/org/python/core/__builtin__.java +++ b/src/org/python/core/__builtin__.java @@ -1,1176 +1,1176 @@ // Copyright (c) Corporation for National Research Initiatives package org.python.core; import java.util.Hashtable; class BuiltinFunctions extends PyBuiltinFunctionSet { public BuiltinFunctions(String name, int index, int argcount) { this(name, index, argcount, argcount); } public BuiltinFunctions(String name, int index, int minargs, int maxargs) { super(name, index, minargs, maxargs); } public PyObject __call__() { switch (this.index) { case 4: return __builtin__.globals(); case 16: return __builtin__.dir(); case 24: return __builtin__.input(); case 28: return __builtin__.locals(); case 34: return Py.newString(__builtin__.raw_input()); case 41: return __builtin__.vars(); default: throw info.unexpectedCall(0, false); } } public PyObject __call__(PyObject arg1) { switch (this.index) { case 0: return Py.newString(__builtin__.chr(Py.py2int(arg1, "chr(): 1st arg can't be coerced to int"))); case 1: return Py.newInteger(__builtin__.len(arg1)); case 2: return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int")); case 3: if (!(arg1 instanceof PyString)) throw Py.TypeError("ord() expected string of length 1, but " + arg1.getType().getFullName() + " found"); if (arg1.__len__() > 1) throw Py.TypeError("ord() expected a character, but string of length " + arg1.__len__() + " found"); return Py.newInteger(__builtin__.ord(Py.py2char(arg1, "ord(): 1st arg can't be coerced to char"))); case 5: return __builtin__.hash(arg1); case 6: return Py.newUnicode(__builtin__.chr(Py.py2int(arg1, "unichr(): 1st arg can't be coerced to int"))); case 7: return __builtin__.abs(arg1); case 11: return Py.newInteger(__builtin__.id(arg1)); case 12: return __builtin__.sum(arg1); case 14: return Py.newBoolean(__builtin__.callable(arg1)); case 16: return __builtin__.dir(arg1); case 18: return __builtin__.eval(arg1); case 19: try { __builtin__.execfile(arg1.asString(0)); } catch (ConversionException e) { throw Py.TypeError("execfile's first argument must be str"); } return null; case 23: return __builtin__.hex(arg1); case 24: return __builtin__.input(arg1); case 25: return __builtin__.intern(arg1.__str__()); case 27: return __builtin__.iter(arg1); case 32: return __builtin__.oct(arg1); case 34: return Py.newString(__builtin__.raw_input(arg1)); case 36: Object o = arg1.__tojava__(PyModule.class); if (o == Py.NoConversion) { o = arg1.__tojava__(PyJavaClass.class); if (o == Py.NoConversion) { Py.TypeError("reload() argument must be a module"); } return __builtin__.reload((PyJavaClass) o); } return __builtin__.reload((PyModule) o); case 37: return __builtin__.repr(arg1); case 38: return __builtin__.round(Py.py2double(arg1)); case 40: return __builtin__.slice(arg1); case 41: return __builtin__.vars(arg1); case 42: return __builtin__.xrange(Py.py2int(arg1)); case 30: return fancyCall(new PyObject[] { arg1 }); case 31: return fancyCall(new PyObject[] { arg1 }); case 43: return fancyCall(new PyObject[] { arg1 }); default: throw info.unexpectedCall(1, false); } } public PyObject __call__(PyObject arg1, PyObject arg2) { switch (this.index) { case 2: return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, "range(): 2nd arg can't be coerced to int")); case 6: return Py.newInteger(__builtin__.cmp(arg1, arg2)); case 9: return __builtin__.apply(arg1, arg2); case 10: return Py.newBoolean(__builtin__.isinstance(arg1, arg2)); case 12: return __builtin__.sum(arg1, arg2); case 13: return __builtin__.coerce(arg1, arg2); case 15: __builtin__.delattr(arg1, asString(arg2, "delattr(): attribute name must be string")); return null; case 17: return __builtin__.divmod(arg1, arg2); case 18: return __builtin__.eval(arg1, arg2); case 19: try { __builtin__.execfile(arg1.asString(0), arg2); } catch (ConversionException e) { throw Py.TypeError("execfile's first argument must be str"); } return null; case 20: return __builtin__.filter(arg1, arg2); case 21: return __builtin__.getattr(arg1, asString(arg2, "getattr(): attribute name must be string")); case 22: return Py.newBoolean(__builtin__.hasattr(arg1, asString(arg2, "hasattr(): attribute name must be string"))); case 26: return Py.newBoolean(__builtin__.issubclass(arg1, arg2)); case 27: return __builtin__.iter(arg1, arg2); case 33: return __builtin__.pow(arg1, arg2); case 35: return __builtin__.reduce(arg1, arg2); case 38: return __builtin__.round(Py.py2double(arg1), Py.py2int(arg2)); case 40: return __builtin__.slice(arg1, arg2); case 42: return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2)); case 29: return fancyCall(new PyObject[] { arg1, arg2 }); case 30: return fancyCall(new PyObject[] { arg1, arg2 }); case 31: return fancyCall(new PyObject[] { arg1, arg2 }); case 43: return fancyCall(new PyObject[] { arg1, arg2 }); default: throw info.unexpectedCall(2, false); } } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3) { switch (this.index) { case 2: return __builtin__.range(Py.py2int(arg1, "range(): 1st arg can't be coerced to int"), Py.py2int(arg2, "range(): 2nd arg can't be coerced to int"), Py.py2int(arg3, "range(): 3rd arg can't be coerced to int")); case 9: try { if (arg3 instanceof PyStringMap) { PyDictionary d = new PyDictionary(); d.update(arg3); arg3 = d; } // this catches both casts of arg3 to a PyDictionary, and // all casts of keys in the dictionary to PyStrings inside // apply(PyObject, PyObject, PyDictionary) PyDictionary d = (PyDictionary) arg3; return __builtin__.apply(arg1, arg2, d); } catch (ClassCastException e) { throw Py.TypeError("apply() 3rd argument must be a " + "dictionary with string keys"); } case 18: return __builtin__.eval(arg1, arg2, arg3); case 19: __builtin__.execfile(asString(arg1, "execfile's first argument must be str", false), arg2, arg3); return null; case 21: return __builtin__.getattr(arg1, asString(arg2, "getattr(): attribute name must be string"), arg3); case 33: return __builtin__.pow(arg1, arg2, arg3); case 35: return __builtin__.reduce(arg1, arg2, arg3); case 39: __builtin__.setattr(arg1, asString(arg2, "setattr(): attribute name must be string"), arg3); return null; case 40: return __builtin__.slice(arg1, arg2, arg3); case 42: return __builtin__.xrange(Py.py2int(arg1), Py.py2int(arg2), Py.py2int(arg3)); case 44: return fancyCall(new PyObject[] { arg1, arg2, arg3 }); case 29: return fancyCall(new PyObject[] { arg1, arg2, arg3 }); case 30: return fancyCall(new PyObject[] { arg1, arg2, arg3 }); case 31: return fancyCall(new PyObject[] { arg1, arg2, arg3 }); case 43: return fancyCall(new PyObject[] { arg1, arg2, arg3 }); default: throw info.unexpectedCall(3, false); } } /** * @return arg as an interned String, or throws TypeError with mesage if asString throws a ConversionException */ private String asString(PyObject arg, String message) { return asString(arg, message, true); } /** * @param intern - should the resulting string be interned * @return arg as a String, or throws TypeError with message if asString throws a ConversionException. */ private String asString(PyObject arg, String message, boolean intern) { try { return intern ? arg.asString(0).intern() : arg.asString(0); } catch (ConversionException e) { throw Py.TypeError(message); } } public PyObject __call__(PyObject arg1, PyObject arg2, PyObject arg3, PyObject arg4) { switch (this.index) { case 44: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); case 29: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); case 30: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); case 31: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); case 43: return fancyCall(new PyObject[] { arg1, arg2, arg3, arg4 }); default: throw info.unexpectedCall(4, false); } } public PyObject fancyCall(PyObject[] args) { switch (this.index) { case 44: if (args.length > 5) { throw info.unexpectedCall(args.length, false); } int flags = 0; if (args.length > 3) { flags = Py.py2int(args[3]); } boolean dont_inherit = false; if (args.length > 4) { dont_inherit = Py.py2boolean(args[4]); } return __builtin__.compile(args[0].toString(), args[1].toString(), args[2].toString(), flags, dont_inherit); case 29: return __builtin__.map(args); case 30: return __builtin__.max(args); case 31: return __builtin__.min(args); case 43: return __builtin__.zip(args); default: throw info.unexpectedCall(args.length, false); } } } /** * The builtin module. All builtin functions are defined here */ public class __builtin__ { public static void fillWithBuiltins(PyObject dict) { /* newstyle */ dict.__setitem__("object", PyType.fromClass(PyObject.class)); dict.__setitem__("type", PyType.fromClass(PyType.class)); + dict.__setitem__("bool", PyType.fromClass(PyBoolean.class)); dict.__setitem__("int", PyType.fromClass(PyInteger.class)); dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class)); dict.__setitem__("float", PyType.fromClass(PyFloat.class)); dict.__setitem__("long", PyType.fromClass(PyLong.class)); dict.__setitem__("complex", PyType.fromClass(PyComplex.class)); dict.__setitem__("dict", PyType.fromClass(PyDictionary.class)); dict.__setitem__("list", PyType.fromClass(PyList.class)); dict.__setitem__("tuple", PyType.fromClass(PyTuple.class)); dict.__setitem__("property", PyType.fromClass(PyProperty.class)); dict.__setitem__("staticmethod", PyType.fromClass(PyStaticMethod.class)); dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class)); dict.__setitem__("super", PyType.fromClass(PySuper.class)); dict.__setitem__("str", PyType.fromClass(PyString.class)); dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class)); dict.__setitem__("basestring", PyType.fromClass(PyBaseString.class)); dict.__setitem__("file", PyType.fromClass(PyFile.class)); dict.__setitem__("open", PyType.fromClass(PyFile.class)); /* - */ dict.__setitem__("None", Py.None); dict.__setitem__("NotImplemented", Py.NotImplemented); dict.__setitem__("Ellipsis", Py.Ellipsis); dict.__setitem__("True", Py.True); dict.__setitem__("False", Py.False); // Work in debug mode by default // Hopefully add -O option in the future to change this dict.__setitem__("__debug__", Py.One); dict.__setitem__("abs", new BuiltinFunctions("abs", 7, 1)); dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); - dict.__setitem__("bool", new BuiltinFunctions("bool", 8, 1)); dict.__setitem__("callable", new BuiltinFunctions("callable", 14, 1)); dict.__setitem__("coerce", new BuiltinFunctions("coerce", 13, 2)); dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); dict.__setitem__("isinstance", new BuiltinFunctions("isinstance", 10, 2)); dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2)); dict.__setitem__("unichr", new BuiltinFunctions("unichr", 6, 1)); dict.__setitem__("compile", new BuiltinFunctions("compile", 44, 3, -1)); dict.__setitem__("delattr", new BuiltinFunctions("delattr", 15, 2)); dict.__setitem__("dir", new BuiltinFunctions("dir", 16, 0, 1)); dict.__setitem__("divmod", new BuiltinFunctions("divmod", 17, 2)); dict.__setitem__("eval", new BuiltinFunctions("eval", 18, 1, 3)); dict.__setitem__("execfile", new BuiltinFunctions("execfile", 19, 1, 3)); dict.__setitem__("filter", new BuiltinFunctions("filter", 20, 2)); dict.__setitem__("getattr", new BuiltinFunctions("getattr", 21, 2, 3)); dict.__setitem__("hasattr", new BuiltinFunctions("hasattr", 22, 2)); dict.__setitem__("hex", new BuiltinFunctions("hex", 23, 1)); dict.__setitem__("input", new BuiltinFunctions("input", 24, 0, 1)); dict.__setitem__("intern", new BuiltinFunctions("intern", 25, 1)); dict.__setitem__("issubclass", new BuiltinFunctions("issubclass", 26, 2)); dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); dict.__setitem__("max", new BuiltinFunctions("max", 30, 1, -1)); dict.__setitem__("min", new BuiltinFunctions("min", 31, 1, -1)); dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); dict.__setitem__("round", new BuiltinFunctions("round", 38, 1, 2)); dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); dict.__setitem__("slice", new BuiltinFunctions("slice", 40, 1, 3)); dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("xrange", new BuiltinFunctions("xrange", 42, 1, 3)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 1, -1)); dict.__setitem__("__import__", new ImportFunction()); } public static PyObject abs(PyObject o) { if (o.isNumberType()) { return o.__abs__(); } throw Py.TypeError("bad operand type for abs()"); } public static PyObject apply(PyObject o, PyObject args) { return o.__call__(Py.make_array(args)); } public static PyObject apply(PyObject o, PyObject args, PyDictionary kws) { PyObject[] a; String[] kw; Hashtable table = kws.table; if (table.size() > 0) { java.util.Enumeration ek = table.keys(); java.util.Enumeration ev = table.elements(); int n = table.size(); kw = new String[n]; PyObject[] aargs = Py.make_array(args); a = new PyObject[n + aargs.length]; System.arraycopy(aargs, 0, a, 0, aargs.length); int offset = aargs.length; for (int i = 0; i < n; i++) { kw[i] = ((PyString) ek.nextElement()).internedString(); a[i + offset] = (PyObject) ev.nextElement(); } return o.__call__(a, kw); } else { return apply(o, args); } } public static boolean callable(PyObject o) { return o.__findattr__("__call__") != null; } public static char unichr(int i) { return chr(i); } public static char chr(int i) { if (i < 0 || i > 65535) { throw Py.ValueError("chr() arg not in range(65535)"); } return (char) i; } public static int cmp(PyObject x, PyObject y) { return x._cmp(y); } public static PyTuple coerce(PyObject o1, PyObject o2) { PyObject[] result = o1._coerce(o2); if (result != null) { return new PyTuple(result); } throw Py.TypeError("number coercion failed"); } public static PyCode compile(String data, String filename, String type) { return Py.compile_flags(data, filename, type, Py.getCompilerFlags()); } public static PyCode compile(String data, String filename, String type, int flags, boolean dont_inherit) { if ((flags & ~PyTableCode.CO_ALL_FEATURES) != 0) { throw Py.ValueError("compile(): unrecognised flags"); } return Py.compile_flags(data, filename, type, Py.getCompilerFlags(flags, dont_inherit)); } public static void delattr(PyObject o, String n) { o.__delattr__(n); } public static PyObject dir(PyObject o) { PyList ret = (PyList) o.__dir__(); ret.sort(); return ret; } public static PyObject dir() { PyObject l = locals(); PyList ret; if (l instanceof PyStringMap) { ret = ((PyStringMap) l).keys(); } else if (l instanceof PyDictionary) { ret = ((PyDictionary) l).keys(); } ret = (PyList) l.invoke("keys"); ret.sort(); return ret; } public static PyObject divmod(PyObject x, PyObject y) { return x._divmod(y); } public static PyEnumerate enumerate(PyObject seq) { return new PyEnumerate(seq); } public static PyObject eval(PyObject o, PyObject globals, PyObject locals) { PyCode code; if (o instanceof PyCode) { code = (PyCode) o; } else { if (o instanceof PyString) { code = compile(o.toString(), "<string>", "eval"); } else { throw Py.TypeError("eval: argument 1 must be string or code object"); } } return Py.runCode(code, locals, globals); } public static PyObject eval(PyObject o, PyObject globals) { return eval(o, globals, globals); } public static PyObject eval(PyObject o) { if (o instanceof PyTableCode && ((PyTableCode) o).hasFreevars()) { throw Py.TypeError("code object passed to eval() may not contain free variables"); } return eval(o, null, null); } public static void execfile(String name, PyObject globals, PyObject locals) { execfile_flags(name, globals, locals, Py.getCompilerFlags()); } public static void execfile_flags(String name, PyObject globals, PyObject locals, CompilerFlags cflags) { java.io.FileInputStream file; try { file = new java.io.FileInputStream(name); } catch (java.io.FileNotFoundException e) { throw Py.IOError(e); } PyCode code; try { code = Py.compile_flags(file, name, "exec", cflags); } finally { try { file.close(); } catch (java.io.IOException e) { throw Py.IOError(e); } } Py.runCode(code, locals, globals); } public static void execfile(String name, PyObject globals) { execfile(name, globals, globals); } public static void execfile(String name) { execfile(name, null, null); } public static PyObject filter(PyObject f, PyString s) { if (f == Py.None) { return s; } PyObject[] args = new PyObject[1]; char[] chars = s.toString().toCharArray(); int i; int j; int n = chars.length; for (i = 0, j = 0; i < n; i++) { args[0] = Py.makeCharacter(chars[i]); if (!f.__call__(args).__nonzero__()) { continue; } chars[j++] = chars[i]; } return new PyString(new String(chars, 0, j)); } public static PyObject filter(PyObject f, PyObject l) { if (l instanceof PyString) { return filter(f, (PyString) l); } PyList list = new PyList(); PyObject iter = l.__iter__(); for (PyObject item = null; (item = iter.__iternext__()) != null;) { if (f == Py.None) { if (!item.__nonzero__()) { continue; } } else if (!f.__call__(item).__nonzero__()) { continue; } list.append(item); } if (l instanceof PyTuple) { return tuple(list); } return list; } public static PyObject getattr(PyObject o, String n) { return o.__getattr__(n); } public static PyObject getattr(PyObject o, String n, PyObject def) { PyObject val = o.__findattr__(n); if (val != null) { return val; } return def; } public static PyObject globals() { return Py.getFrame().f_globals; } public static boolean hasattr(PyObject o, String n) { try { return o.__findattr__(n) != null; } catch (PyException exc) { if (Py.matchException(exc, Py.AttributeError)) { return false; } throw exc; } } public static PyInteger hash(PyObject o) { return o.__hash__(); } public static PyString hex(PyObject o) { try { return o.__hex__(); } catch (PyException e) { if (Py.matchException(e, Py.AttributeError)) throw Py.TypeError("hex() argument can't be converted to hex"); throw e; } } public static long id(PyObject o) { return Py.id(o); } public static PyObject input(PyObject prompt) { String line = raw_input(prompt); return eval(new PyString(line)); } public static PyObject input() { return input(new PyString("")); } private static PyStringMap internedStrings; public static PyString intern(PyString s) { if (internedStrings == null) { internedStrings = new PyStringMap(); } String istring = s.internedString(); PyObject ret = internedStrings.__finditem__(istring); if (ret != null) { return (PyString) ret; } if (s instanceof PyStringDerived) { s = s.__str__(); } internedStrings.__setitem__(istring, s); return s; } // xxx find where used, modify with more appropriate if necessary public static boolean isinstance(PyObject obj, PyObject cls) { return Py.isInstance(obj, cls); } // xxx find where used, modify with more appropriate if necessary public static boolean issubclass(PyObject derived, PyObject cls) { return Py.isSubClass(derived, cls); } public static PyObject iter(PyObject obj) { return obj.__iter__(); } public static PyObject iter(PyObject callable, PyObject sentinel) { return new PyCallIter(callable, sentinel); } public static int len(PyObject o) { try { return o.__len__(); } catch (PyException e) { // Make this work like CPython where // // a = 7; len(a) raises a TypeError, // a.__len__() raises an AttributeError // and // class F: pass // f = F(); len(f) also raises an AttributeError // // Testing the type of o feels unclean though if (e.type == Py.AttributeError && !(o instanceof PyInstance)) { throw Py.TypeError("len() of unsized object"); } throw e; } } public static PyObject locals() { return Py.getFrame().getf_locals(); } public static PyObject map(PyObject[] argstar) { int n = argstar.length - 1; if (n < 1) { throw Py.TypeError("map requires at least two arguments"); } PyObject element; PyObject f = argstar[0]; PyList list = new PyList(); PyObject[] args = new PyObject[n]; PyObject[] iters = new PyObject[n]; for (int j = 0; j < n; j++) { iters[j] = Py.iter(argstar[j + 1], "argument " + (j + 1) + " to map() must support iteration"); } while (true) { boolean any_items = false; for (int j = 0; j < n; j++) { if ((element = iters[j].__iternext__()) != null) { args[j] = element; any_items = true; } else { args[j] = Py.None; } } if (!any_items) { break; } if (f == Py.None) { if (n == 1) { list.append(args[0]); } else { list.append(new PyTuple((PyObject[]) args.clone())); } } else { list.append(f.__call__(args)); } } return list; } public static PyObject max(PyObject[] l) { if (l.length == 1) { return max(l[0]); } return max(new PyTuple(l)); } private static PyObject max(PyObject o) { PyObject max = null; PyObject iter = o.__iter__(); for (PyObject item; (item = iter.__iternext__()) != null;) { if (max == null || item._gt(max).__nonzero__()) { max = item; } } if (max == null) { throw Py.ValueError("max of empty sequence"); } return max; } public static PyObject min(PyObject[] l) { if (l.length == 0) { throw Py.TypeError("min expected 1 arguments, got 0"); } if (l.length == 1) { return min(l[0]); } return min(new PyTuple(l)); } private static PyObject min(PyObject o) { PyObject min = null; PyObject iter = o.__iter__(); for (PyObject item; (item = iter.__iternext__()) != null;) { if (min == null || item._lt(min).__nonzero__()) { min = item; } } if (min == null) { throw Py.ValueError("min of empty sequence"); } return min; } public static PyString oct(PyObject o) { return o.__oct__(); } public static final int ord(char c) { return c; } public static PyObject pow(PyObject x, PyObject y) { return x._pow(y); } private static boolean coerce(PyObject[] objs) { PyObject x = objs[0]; PyObject y = objs[1]; PyObject[] result; result = x._coerce(y); if (result != null) { objs[0] = result[0]; objs[1] = result[1]; return true; } result = y._coerce(x); if (result != null) { objs[0] = result[1]; objs[1] = result[0]; return true; } return false; } public static PyObject pow(PyObject xi, PyObject yi, PyObject zi) { PyObject x = xi; PyObject y = yi; PyObject z = zi; PyObject[] tmp = new PyObject[2]; tmp[0] = x; tmp[1] = y; if (coerce(tmp)) { x = tmp[0]; y = tmp[1]; tmp[1] = z; if (coerce(tmp)) { x = tmp[0]; z = tmp[1]; tmp[0] = y; if (coerce(tmp)) { z = tmp[1]; y = tmp[0]; } } } else { tmp[1] = z; if (coerce(tmp)) { x = tmp[0]; z = tmp[1]; tmp[0] = y; if (coerce(tmp)) { y = tmp[0]; z = tmp[1]; tmp[1] = x; if (coerce(tmp)) { x = tmp[1]; y = tmp[0]; } } } } if (x.getType() == y.getType() && x.getType() == z.getType()) { x = x.__pow__(y, z); if (x != null) { return x; } } throw Py.TypeError("__pow__ not defined for these operands"); } public static PyObject range(int start, int stop, int step) { if (step == 0) { throw Py.ValueError("zero step for range()"); } int n; if (step > 0) { n = (stop - start + step - 1) / step; } else { n = (stop - start + step + 1) / step; } if (n <= 0) { return new PyList(); } PyObject[] l = new PyObject[n]; int j = start; for (int i = 0; i < n; i++) { l[i] = Py.newInteger(j); j += step; } return new PyList(l); } public static PyObject range(int n) { return range(0, n, 1); } public static PyObject range(int start, int stop) { return range(start, stop, 1); } private static PyString readline(PyObject file) { if (file instanceof PyFile) { return new PyString(((PyFile) file).readline()); } else { PyObject ret = file.invoke("readline"); if (!(ret instanceof PyString)) { throw Py.TypeError("object.readline() returned non-string"); } return (PyString) ret; } } public static String raw_input(PyObject prompt) { Py.print(prompt); PyObject stdin = Py.getSystemState().stdin; String data = readline(stdin).toString(); if (data.endsWith("\n")) { return data.substring(0, data.length() - 1); } else { if (data.length() == 0) { throw Py.EOFError("raw_input()"); } } return data; } public static String raw_input() { return raw_input(new PyString("")); } public static PyObject reduce(PyObject f, PyObject l, PyObject z) { PyObject result = z; PyObject iter = Py.iter(l, "reduce() arg 2 must support iteration"); for (PyObject item; (item = iter.__iternext__()) != null;) { if (result == null) { result = item; } else { result = f.__call__(result, item); } } if (result == null) { throw Py.TypeError("reduce of empty sequence with no initial value"); } return result; } public static PyObject reduce(PyObject f, PyObject l) { return reduce(f, l, null); } public static PyObject reload(PyModule o) { return imp.reload(o); } public static PyObject reload(PyJavaClass o) { return imp.reload(o); } public static PyString repr(PyObject o) { return o.__repr__(); } // This seems awfully special purpose... public static PyFloat round(double f, int digits) { boolean neg = f < 0; double multiple = Math.pow(10., digits); if (neg) { f = -f; } double tmp = Math.floor(f * multiple + 0.5); if (neg) { tmp = -tmp; } return new PyFloat(tmp / multiple); } public static PyFloat round(double f) { return round(f, 0); } public static void setattr(PyObject o, String n, PyObject v) { o.__setattr__(n, v); } public static PySlice slice(PyObject start, PyObject stop, PyObject step) { return new PySlice(start, stop, step); } public static PySlice slice(PyObject start, PyObject stop) { return slice(start, stop, Py.None); } public static PySlice slice(PyObject stop) { return slice(Py.None, stop, Py.None); } public static PyObject sum(PyObject seq, PyObject result) { if (result instanceof PyString) { throw Py.TypeError("sum() can't sum strings [use ''.join(seq) instead]"); } PyObject item; PyObject iter = seq.__iter__(); while ((item = iter.__iternext__()) != null) { result = result._add(item); } return result; } public static PyObject sum(PyObject seq) { return sum(seq, Py.Zero); } public static PyTuple tuple(PyObject o) { if (o instanceof PyTuple) { return (PyTuple) o; } if (o instanceof PyList) { // always make a copy, otherwise the tuple will share the // underlying data structure with the list object, which // renders the tuple mutable! PyList l = (PyList) o; PyObject[] a = new PyObject[l.size()]; System.arraycopy(l.getArray(), 0, a, 0, a.length); return new PyTuple(a); } return new PyTuple(Py.make_array(o)); } public static PyType type(PyObject o) { return o.getType(); } public static PyObject vars() { return locals(); } public static PyObject vars(PyObject o) { try { return o.__getattr__("__dict__"); } catch (PyException e) { if (Py.matchException(e, Py.AttributeError)) throw Py.TypeError("vars() argument must have __dict__ attribute"); throw e; } } public static PyObject xrange(int start, int stop, int step) { return new PyXRange(start, stop, step); } public static PyObject xrange(int n) { return xrange(0, n, 1); } public static PyObject xrange(int start, int stop) { return xrange(start, stop, 1); } public static PyString __doc__zip = new PyString("zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n" + "\n" + "Return a list of tuples, where each tuple contains the i-th element\n" + "from each of the argument sequences. The returned list is\n" + "truncated in length to the length of the shortest argument sequence."); public static PyObject zip(PyObject[] argstar) { int itemsize = argstar.length; if (itemsize < 1) { throw Py.TypeError("zip requires at least one sequence"); } // Type check the arguments; they must be sequences. Might as well // cache the __iter__() methods. PyObject[] iters = new PyObject[itemsize]; for (int j = 0; j < itemsize; j++) { PyObject iter = argstar[j].__iter__(); if (iter == null) { throw Py.TypeError("zip argument #" + (j + 1) + " must support iteration"); } iters[j] = iter; } PyList ret = new PyList(); for (int i = 0;; i++) { PyObject[] next = new PyObject[itemsize]; PyObject item; for (int j = 0; j < itemsize; j++) { try { item = iters[j].__iternext__(); } catch (PyException e) { if (Py.matchException(e, Py.StopIteration)) { return ret; } throw e; } if (item == null) { return ret; } next[j] = item; } ret.append(new PyTuple(next)); } } public static PyObject __import__(String name) { return __import__(name, null, null, null); } public static PyObject __import__(String name, PyObject globals) { return __import__(name, globals, null, null); } public static PyObject __import__(String name, PyObject globals, PyObject locals) { return __import__(name, globals, locals, null); } public static PyObject __import__(String name, PyObject globals, PyObject locals, PyObject fromlist) { PyFrame frame = Py.getFrame(); if (frame == null) { return null; } PyObject builtins = frame.f_builtins; if (builtins == null) { builtins = Py.getSystemState().builtins; } PyObject __import__ = builtins.__finditem__("__import__"); if (__import__ == null) { return null; } PyObject module = __import__.__call__(new PyObject[] { Py.newString(name), globals, locals, fromlist }); return module; } } class ImportFunction extends PyObject { public ImportFunction() { } public PyObject __call__(PyObject args[], String keywords[]) { if (!(args.length < 1 || args[0] instanceof PyString)) { throw Py.TypeError("first argument must be a string"); } if (keywords.length > 0) { throw Py.TypeError("__import__() takes no keyword arguments"); } int argc = args.length; String module = args[0].__str__().toString(); PyObject globals = (argc > 1 && args[1] != null) ? args[1] : null; PyObject fromlist = (argc > 3 && args[3] != null) ? args[3] : Py.EmptyTuple; return load(module, globals, fromlist); } private PyObject load(String module, PyObject globals, PyObject fromlist) { PyObject mod = imp.importName(module.intern(), fromlist.__len__() == 0, globals, fromlist); return mod; } public String toString() { return "<built-in function __import__>"; } }
false
true
public static void fillWithBuiltins(PyObject dict) { /* newstyle */ dict.__setitem__("object", PyType.fromClass(PyObject.class)); dict.__setitem__("type", PyType.fromClass(PyType.class)); dict.__setitem__("int", PyType.fromClass(PyInteger.class)); dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class)); dict.__setitem__("float", PyType.fromClass(PyFloat.class)); dict.__setitem__("long", PyType.fromClass(PyLong.class)); dict.__setitem__("complex", PyType.fromClass(PyComplex.class)); dict.__setitem__("dict", PyType.fromClass(PyDictionary.class)); dict.__setitem__("list", PyType.fromClass(PyList.class)); dict.__setitem__("tuple", PyType.fromClass(PyTuple.class)); dict.__setitem__("property", PyType.fromClass(PyProperty.class)); dict.__setitem__("staticmethod", PyType.fromClass(PyStaticMethod.class)); dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class)); dict.__setitem__("super", PyType.fromClass(PySuper.class)); dict.__setitem__("str", PyType.fromClass(PyString.class)); dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class)); dict.__setitem__("basestring", PyType.fromClass(PyBaseString.class)); dict.__setitem__("file", PyType.fromClass(PyFile.class)); dict.__setitem__("open", PyType.fromClass(PyFile.class)); /* - */ dict.__setitem__("None", Py.None); dict.__setitem__("NotImplemented", Py.NotImplemented); dict.__setitem__("Ellipsis", Py.Ellipsis); dict.__setitem__("True", Py.True); dict.__setitem__("False", Py.False); // Work in debug mode by default // Hopefully add -O option in the future to change this dict.__setitem__("__debug__", Py.One); dict.__setitem__("abs", new BuiltinFunctions("abs", 7, 1)); dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); dict.__setitem__("bool", new BuiltinFunctions("bool", 8, 1)); dict.__setitem__("callable", new BuiltinFunctions("callable", 14, 1)); dict.__setitem__("coerce", new BuiltinFunctions("coerce", 13, 2)); dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); dict.__setitem__("isinstance", new BuiltinFunctions("isinstance", 10, 2)); dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2)); dict.__setitem__("unichr", new BuiltinFunctions("unichr", 6, 1)); dict.__setitem__("compile", new BuiltinFunctions("compile", 44, 3, -1)); dict.__setitem__("delattr", new BuiltinFunctions("delattr", 15, 2)); dict.__setitem__("dir", new BuiltinFunctions("dir", 16, 0, 1)); dict.__setitem__("divmod", new BuiltinFunctions("divmod", 17, 2)); dict.__setitem__("eval", new BuiltinFunctions("eval", 18, 1, 3)); dict.__setitem__("execfile", new BuiltinFunctions("execfile", 19, 1, 3)); dict.__setitem__("filter", new BuiltinFunctions("filter", 20, 2)); dict.__setitem__("getattr", new BuiltinFunctions("getattr", 21, 2, 3)); dict.__setitem__("hasattr", new BuiltinFunctions("hasattr", 22, 2)); dict.__setitem__("hex", new BuiltinFunctions("hex", 23, 1)); dict.__setitem__("input", new BuiltinFunctions("input", 24, 0, 1)); dict.__setitem__("intern", new BuiltinFunctions("intern", 25, 1)); dict.__setitem__("issubclass", new BuiltinFunctions("issubclass", 26, 2)); dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); dict.__setitem__("max", new BuiltinFunctions("max", 30, 1, -1)); dict.__setitem__("min", new BuiltinFunctions("min", 31, 1, -1)); dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); dict.__setitem__("round", new BuiltinFunctions("round", 38, 1, 2)); dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); dict.__setitem__("slice", new BuiltinFunctions("slice", 40, 1, 3)); dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("xrange", new BuiltinFunctions("xrange", 42, 1, 3)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 1, -1)); dict.__setitem__("__import__", new ImportFunction()); }
public static void fillWithBuiltins(PyObject dict) { /* newstyle */ dict.__setitem__("object", PyType.fromClass(PyObject.class)); dict.__setitem__("type", PyType.fromClass(PyType.class)); dict.__setitem__("bool", PyType.fromClass(PyBoolean.class)); dict.__setitem__("int", PyType.fromClass(PyInteger.class)); dict.__setitem__("enumerate", PyType.fromClass(PyEnumerate.class)); dict.__setitem__("float", PyType.fromClass(PyFloat.class)); dict.__setitem__("long", PyType.fromClass(PyLong.class)); dict.__setitem__("complex", PyType.fromClass(PyComplex.class)); dict.__setitem__("dict", PyType.fromClass(PyDictionary.class)); dict.__setitem__("list", PyType.fromClass(PyList.class)); dict.__setitem__("tuple", PyType.fromClass(PyTuple.class)); dict.__setitem__("property", PyType.fromClass(PyProperty.class)); dict.__setitem__("staticmethod", PyType.fromClass(PyStaticMethod.class)); dict.__setitem__("classmethod", PyType.fromClass(PyClassMethod.class)); dict.__setitem__("super", PyType.fromClass(PySuper.class)); dict.__setitem__("str", PyType.fromClass(PyString.class)); dict.__setitem__("unicode", PyType.fromClass(PyUnicode.class)); dict.__setitem__("basestring", PyType.fromClass(PyBaseString.class)); dict.__setitem__("file", PyType.fromClass(PyFile.class)); dict.__setitem__("open", PyType.fromClass(PyFile.class)); /* - */ dict.__setitem__("None", Py.None); dict.__setitem__("NotImplemented", Py.NotImplemented); dict.__setitem__("Ellipsis", Py.Ellipsis); dict.__setitem__("True", Py.True); dict.__setitem__("False", Py.False); // Work in debug mode by default // Hopefully add -O option in the future to change this dict.__setitem__("__debug__", Py.One); dict.__setitem__("abs", new BuiltinFunctions("abs", 7, 1)); dict.__setitem__("apply", new BuiltinFunctions("apply", 9, 2, 3)); dict.__setitem__("callable", new BuiltinFunctions("callable", 14, 1)); dict.__setitem__("coerce", new BuiltinFunctions("coerce", 13, 2)); dict.__setitem__("chr", new BuiltinFunctions("chr", 0, 1)); dict.__setitem__("cmp", new BuiltinFunctions("cmp", 6, 2)); dict.__setitem__("globals", new BuiltinFunctions("globals", 4, 0)); dict.__setitem__("hash", new BuiltinFunctions("hash", 5, 1)); dict.__setitem__("id", new BuiltinFunctions("id", 11, 1)); dict.__setitem__("isinstance", new BuiltinFunctions("isinstance", 10, 2)); dict.__setitem__("len", new BuiltinFunctions("len", 1, 1)); dict.__setitem__("ord", new BuiltinFunctions("ord", 3, 1)); dict.__setitem__("range", new BuiltinFunctions("range", 2, 1, 3)); dict.__setitem__("sum", new BuiltinFunctions("sum", 12, 1, 2)); dict.__setitem__("unichr", new BuiltinFunctions("unichr", 6, 1)); dict.__setitem__("compile", new BuiltinFunctions("compile", 44, 3, -1)); dict.__setitem__("delattr", new BuiltinFunctions("delattr", 15, 2)); dict.__setitem__("dir", new BuiltinFunctions("dir", 16, 0, 1)); dict.__setitem__("divmod", new BuiltinFunctions("divmod", 17, 2)); dict.__setitem__("eval", new BuiltinFunctions("eval", 18, 1, 3)); dict.__setitem__("execfile", new BuiltinFunctions("execfile", 19, 1, 3)); dict.__setitem__("filter", new BuiltinFunctions("filter", 20, 2)); dict.__setitem__("getattr", new BuiltinFunctions("getattr", 21, 2, 3)); dict.__setitem__("hasattr", new BuiltinFunctions("hasattr", 22, 2)); dict.__setitem__("hex", new BuiltinFunctions("hex", 23, 1)); dict.__setitem__("input", new BuiltinFunctions("input", 24, 0, 1)); dict.__setitem__("intern", new BuiltinFunctions("intern", 25, 1)); dict.__setitem__("issubclass", new BuiltinFunctions("issubclass", 26, 2)); dict.__setitem__("iter", new BuiltinFunctions("iter", 27, 1, 2)); dict.__setitem__("locals", new BuiltinFunctions("locals", 28, 0)); dict.__setitem__("map", new BuiltinFunctions("map", 29, 2, -1)); dict.__setitem__("max", new BuiltinFunctions("max", 30, 1, -1)); dict.__setitem__("min", new BuiltinFunctions("min", 31, 1, -1)); dict.__setitem__("oct", new BuiltinFunctions("oct", 32, 1)); dict.__setitem__("pow", new BuiltinFunctions("pow", 33, 2, 3)); dict.__setitem__("raw_input", new BuiltinFunctions("raw_input", 34, 0, 1)); dict.__setitem__("reduce", new BuiltinFunctions("reduce", 35, 2, 3)); dict.__setitem__("reload", new BuiltinFunctions("reload", 36, 1)); dict.__setitem__("repr", new BuiltinFunctions("repr", 37, 1)); dict.__setitem__("round", new BuiltinFunctions("round", 38, 1, 2)); dict.__setitem__("setattr", new BuiltinFunctions("setattr", 39, 3)); dict.__setitem__("slice", new BuiltinFunctions("slice", 40, 1, 3)); dict.__setitem__("vars", new BuiltinFunctions("vars", 41, 0, 1)); dict.__setitem__("xrange", new BuiltinFunctions("xrange", 42, 1, 3)); dict.__setitem__("zip", new BuiltinFunctions("zip", 43, 1, -1)); dict.__setitem__("__import__", new ImportFunction()); }
diff --git a/classlib/modules/lang-management/src/main/java/org/apache/harmony/lang/management/DynamicMXBeanImpl.java b/classlib/modules/lang-management/src/main/java/org/apache/harmony/lang/management/DynamicMXBeanImpl.java index e09d0404..d0b261d3 100644 --- a/classlib/modules/lang-management/src/main/java/org/apache/harmony/lang/management/DynamicMXBeanImpl.java +++ b/classlib/modules/lang-management/src/main/java/org/apache/harmony/lang/management/DynamicMXBeanImpl.java @@ -1,422 +1,422 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.harmony.lang.management; import java.lang.reflect.Method; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.DynamicMBean; import javax.management.InvalidAttributeValueException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanParameterInfo; import javax.management.ReflectionException; import org.apache.harmony.lang.management.internals.nls.Messages; /** * Abstract implementation of the {@link DynamicMBean} interface that provides * behaviour required by a dynamic MBean. This class is subclassed by all of the * concrete MXBean types in this package. */ public abstract class DynamicMXBeanImpl implements DynamicMBean { protected MBeanInfo info; /** * @param info */ protected void setMBeanInfo(MBeanInfo info) { this.info = info; } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#getAttributes(java.lang.String[]) */ public AttributeList getAttributes(String[] attributes) { AttributeList result = new AttributeList(); for (int i = 0; i < attributes.length; i++) { try { Object value = getAttribute(attributes[i]); result.add(new Attribute(attributes[i], value)); } catch (Exception e) { // It is alright if the returned AttributeList is smaller in // size than the length of the input array. if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if } }// end for return result; } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#setAttributes(javax.management.AttributeList) */ public AttributeList setAttributes(AttributeList attributes) { AttributeList result = new AttributeList(); for (int i = 0; i < attributes.size(); i++) { Attribute attrib = (Attribute) attributes.get(i); String attribName = null; Object attribVal = null; try { this.setAttribute(attrib); attribName = attrib.getName(); // Note that the below getAttribute call will throw an // AttributeNotFoundException if the named attribute is not // readable for this bean. This is perfectly alright - the set // has worked as requested - it just means that the caller // does not get this information returned to them in the // result AttributeList. attribVal = getAttribute(attribName); result.add(new Attribute(attribName, attribVal)); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if } }// end for return result; } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#getMBeanInfo() */ public MBeanInfo getMBeanInfo() { return info; } /** * Simple enumeration of the different kinds of access that may be required * of a dynamic MBean attribute. */ enum AttributeAccessType { READING, WRITING }; /** * Tests to see if this <code>DynamicMXBean</code> has an attribute with * the name <code>attributeName</code>. If the test is passed, the * {@link MBeanAttributeInfo}representing the attribute is returned. * * @param attributeName * the name of the attribute being queried * @param access * an {@link AttributeAccessType}indication of whether the * caller is looking for a readable or writable attribute. * @return if the named attribute exists and is readable or writable * (depending on what was specified in <code>access</code>, an * instance of <code>MBeanAttributeInfo</code> that describes the * attribute, otherwise <code>null</code>. */ protected MBeanAttributeInfo getPresentAttribute(String attributeName, AttributeAccessType access) { MBeanAttributeInfo[] attribs = info.getAttributes(); MBeanAttributeInfo result = null; for (int i = 0; i < attribs.length; i++) { MBeanAttributeInfo attribInfo = attribs[i]; if (attribInfo.getName().equals(attributeName)) { if (access.equals(AttributeAccessType.READING)) { if (attribInfo.isReadable()) { result = attribInfo; break; } } else { if (attribInfo.isWritable()) { result = attribInfo; break; } } }// end if }// end for return result; } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#getAttribute(java.lang.String) */ public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException { Object result = null; Method getterMethod = null; MBeanAttributeInfo attribInfo = getPresentAttribute(attribute, AttributeAccessType.READING); if (attribInfo == null) { //lm.0A=No such attribute : {0} throw new AttributeNotFoundException(Messages.getString("lm.0A", attribute)); //$NON-NLs-1$ } try { String getterPrefix = attribInfo.isIs() ? "is" : "get"; getterMethod = this.getClass().getMethod(getterPrefix + attribute, (Class[]) null); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } String realReturnType = getterMethod.getReturnType().getName(); String openReturnType = attribInfo.getType(); result = invokeMethod(getterMethod, (Object[]) null); try { if (!realReturnType.equals(openReturnType)) { result = ManagementUtils .convertToOpenType(result, Class .forName(openReturnType), Class .forName(realReturnType)); }// end if conversion necessary } catch (ClassNotFoundException e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new MBeanException(e); } return result; } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#setAttribute(javax.management.Attribute) */ public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { // In Java 5.0 platform MXBeans the following applies for all // attribute setter methods : // 1. no conversion to open MBean types necessary // 2. all setter arguments are single value (i.e. not array or // collection types). // 3. all return null Class<?> argType = null; // Validate the attribute MBeanAttributeInfo attribInfo = getPresentAttribute( attribute.getName(), AttributeAccessType.WRITING); if (attribInfo == null) { //lm.0A=No such attribute : {0} - throw new AttributeNotFoundException(Messages.getString("lm.0A"), attribute); //$NON-NLs-1$ + throw new AttributeNotFoundException(Messages.getString("lm.0A", attribute)); //$NON-NLs-1$ } try { // Validate supplied parameter is of the expected type argType = ManagementUtils.getClassMaybePrimitive(attribInfo .getType()); } catch (ClassNotFoundException e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } if (argType.isPrimitive()) { if (!ManagementUtils.isWrapperClass( attribute.getValue().getClass(), argType)) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } } else if (!argType.equals(attribute.getValue().getClass())) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } Method setterMethod = null; try { setterMethod = this.getClass().getMethod( "set" + attribute.getName(), new Class[] { argType }); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } invokeMethod(setterMethod, attribute.getValue()); try { setterMethod.invoke(this, attribute.getValue()); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if Throwable root = e.getCause(); if (root instanceof RuntimeException) { throw (RuntimeException) root; } else { throw new MBeanException((Exception) root); }// end else }// end catch } /* * (non-Javadoc) * * @see javax.management.DynamicMBean#invoke(java.lang.String, * java.lang.Object[], java.lang.String[]) */ public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { Object result = null; // If null is passed in for the signature argument (if invoking a // method with no args for instance) then avoid any NPEs by working // with a zero length String array instead. String[] localSignature = signature; if (localSignature == null) { localSignature = new String[0]; } // Validate that we have the named action MBeanOperationInfo opInfo = getPresentOperation(actionName, localSignature); if (opInfo == null) { //lm.0C=No such operation : {0} throw new ReflectionException( new NoSuchMethodException (actionName), Messages.getString("lm.0C", actionName)); //$NON-NLS-1$ } // For Java 5.0 platform MXBeans, no conversion // to open MBean types is necessary for any of the arguments. // i.e. they are all simple types. Method operationMethod = null; try { Class<?>[] argTypes = new Class[localSignature.length]; for (int i = 0; i < localSignature.length; i++) { argTypes[i] = ManagementUtils .getClassMaybePrimitive(localSignature[i]); }// end for operationMethod = this.getClass().getMethod(actionName, argTypes); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } String realReturnType = operationMethod.getReturnType().getName(); String openReturnType = opInfo.getReturnType(); result = invokeMethod(operationMethod, params); try { if (!realReturnType.equals(openReturnType)) { result = ManagementUtils .convertToOpenType(result, Class .forName(openReturnType), Class .forName(realReturnType)); } } catch (ClassNotFoundException e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new MBeanException(e); }// end catch return result; } /** * Tests to see if this <code>DynamicMXBean</code> has an operation with * the name <code>actionName</code>. If the test is passed, the * {@link MBeanOperationInfo}representing the operation is returned to the * caller. * * @param actionName * the name of a possible method on this * <code>DynamicMXBean</code> * @param signature * the list of parameter types for the named operation in the * correct order * @return if the named operation exists, an instance of * <code>MBeanOperationInfo</code> that describes the operation, * otherwise <code>null</code>. */ protected MBeanOperationInfo getPresentOperation(String actionName, String[] signature) { MBeanOperationInfo[] operations = info.getOperations(); MBeanOperationInfo result = null; for (int i = 0; i < operations.length; i++) { MBeanOperationInfo opInfo = operations[i]; if (opInfo.getName().equals(actionName)) { // Do parameter numbers match ? if (signature.length == opInfo.getSignature().length) { // Do parameter types match ? boolean match = true; MBeanParameterInfo[] parameters = opInfo.getSignature(); for (int j = 0; j < parameters.length; j++) { MBeanParameterInfo paramInfo = parameters[j]; if (!paramInfo.getType().equals(signature[j])) { match = false; break; } }// end for all parameters if (match) { result = opInfo; break; } }// end if parameter counts match }// end if operation names match }// end for all operations return result; } /** * @param params * @param operationMethod * @return the result of the reflective method invocation * @throws MBeanException */ private Object invokeMethod(Method operationMethod, Object... params) throws MBeanException { Object result = null; try { result = operationMethod.invoke(this, params); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if Throwable root = e.getCause(); if (root instanceof RuntimeException) { throw (RuntimeException) root; } else { throw new MBeanException((Exception) root); }// end else }// end catch return result; } }
true
true
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { // In Java 5.0 platform MXBeans the following applies for all // attribute setter methods : // 1. no conversion to open MBean types necessary // 2. all setter arguments are single value (i.e. not array or // collection types). // 3. all return null Class<?> argType = null; // Validate the attribute MBeanAttributeInfo attribInfo = getPresentAttribute( attribute.getName(), AttributeAccessType.WRITING); if (attribInfo == null) { //lm.0A=No such attribute : {0} throw new AttributeNotFoundException(Messages.getString("lm.0A"), attribute); //$NON-NLs-1$ } try { // Validate supplied parameter is of the expected type argType = ManagementUtils.getClassMaybePrimitive(attribInfo .getType()); } catch (ClassNotFoundException e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } if (argType.isPrimitive()) { if (!ManagementUtils.isWrapperClass( attribute.getValue().getClass(), argType)) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } } else if (!argType.equals(attribute.getValue().getClass())) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } Method setterMethod = null; try { setterMethod = this.getClass().getMethod( "set" + attribute.getName(), new Class[] { argType }); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } invokeMethod(setterMethod, attribute.getValue()); try { setterMethod.invoke(this, attribute.getValue()); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if Throwable root = e.getCause(); if (root instanceof RuntimeException) { throw (RuntimeException) root; } else { throw new MBeanException((Exception) root); }// end else }// end catch }
public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException { // In Java 5.0 platform MXBeans the following applies for all // attribute setter methods : // 1. no conversion to open MBean types necessary // 2. all setter arguments are single value (i.e. not array or // collection types). // 3. all return null Class<?> argType = null; // Validate the attribute MBeanAttributeInfo attribInfo = getPresentAttribute( attribute.getName(), AttributeAccessType.WRITING); if (attribInfo == null) { //lm.0A=No such attribute : {0} throw new AttributeNotFoundException(Messages.getString("lm.0A", attribute)); //$NON-NLs-1$ } try { // Validate supplied parameter is of the expected type argType = ManagementUtils.getClassMaybePrimitive(attribInfo .getType()); } catch (ClassNotFoundException e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } if (argType.isPrimitive()) { if (!ManagementUtils.isWrapperClass( attribute.getValue().getClass(), argType)) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } } else if (!argType.equals(attribute.getValue().getClass())) { //lm.0B= {0} is a {1} attribute throw new InvalidAttributeValueException(Messages.getString("lm.0B", attribInfo.getName(), attribInfo.getType())); //$NON-NLS-1$ } Method setterMethod = null; try { setterMethod = this.getClass().getMethod( "set" + attribute.getName(), new Class[] { argType }); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if throw new ReflectionException(e); } invokeMethod(setterMethod, attribute.getValue()); try { setterMethod.invoke(this, attribute.getValue()); } catch (Exception e) { if (ManagementUtils.VERBOSE_MODE) { e.printStackTrace(System.err); }// end if Throwable root = e.getCause(); if (root instanceof RuntimeException) { throw (RuntimeException) root; } else { throw new MBeanException((Exception) root); }// end else }// end catch }
diff --git a/source/ch/cyberduck/core/aquaticprime/LicenseFactory.java b/source/ch/cyberduck/core/aquaticprime/LicenseFactory.java index a7c45b33f..ceb188c8d 100644 --- a/source/ch/cyberduck/core/aquaticprime/LicenseFactory.java +++ b/source/ch/cyberduck/core/aquaticprime/LicenseFactory.java @@ -1,123 +1,129 @@ package ch.cyberduck.core.aquaticprime; /* * Copyright (c) 2002-2010 David Kocher. All rights reserved. * * http://cyberduck.ch/ * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * Bug fixes, suggestions and comments should be sent to: * [email protected] */ import ch.cyberduck.core.Factory; import ch.cyberduck.core.Local; import ch.cyberduck.core.LocalFactory; import ch.cyberduck.core.Preferences; import ch.cyberduck.core.i18n.Locale; import org.apache.commons.io.FileUtils; import org.apache.commons.io.filefilter.FalseFileFilter; import org.apache.commons.io.filefilter.NameFileFilter; import org.apache.commons.io.filefilter.SuffixFileFilter; import org.apache.log4j.Logger; import java.io.File; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * @version $Id$ */ public abstract class LicenseFactory extends Factory<License> { private static Logger log = Logger.getLogger(LicenseFactory.class); /** * Registered factories */ protected static final Map<Platform, LicenseFactory> factories = new HashMap<Platform, LicenseFactory>(); /** * @param platform * @param f */ public static void addFactory(Factory.Platform platform, LicenseFactory f) { factories.put(platform, f); } /** * @param file * @return */ protected abstract License open(Local file); /** * @return */ public static License create(Local file) { if(!factories.containsKey(NATIVE_PLATFORM)) { throw new RuntimeException("No implementation for " + NATIVE_PLATFORM); } return factories.get(NATIVE_PLATFORM).open(file); } /** * @return If no license is installed a dummy license is returned. * @see #EMPTY_LICENSE */ public static License find() { - final Collection<File> licenses = FileUtils.listFiles( - new File(LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path")).getAbsolute()), - new SuffixFileFilter(".cyberducklicense"), FalseFileFilter.FALSE); - for(File license : licenses) { - return LicenseFactory.create(LocalFactory.createLocal(license)); + Local support = LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path")); + if(support.exists()) { + final Collection<File> keys = FileUtils.listFiles( + new File(support.getAbsolute()), + new SuffixFileFilter(".cyberducklicense"), FalseFileFilter.FALSE); + for(File key : keys) { + return LicenseFactory.create(LocalFactory.createLocal(key)); + } } - final Collection<File> receipts = FileUtils.listFiles( - new File(LocalFactory.createLocal(Preferences.instance().getProperty("application.receipt.path")).getAbsolute()), - new NameFileFilter("receipt"), FalseFileFilter.FALSE); - for(File receipt : receipts) { - return LicenseFactory.create(LocalFactory.createLocal(receipt)); + Local receipt = LocalFactory.createLocal(Preferences.instance().getProperty("application.receipt.path")); + if(receipt.exists()) { + final Collection<File> receipts = FileUtils.listFiles( + new File(receipt.getAbsolute()), + new NameFileFilter("receipt"), FalseFileFilter.FALSE); + for(File key : receipts) { + return LicenseFactory.create(LocalFactory.createLocal(key)); + } } log.info("No license found"); return EMPTY_LICENSE; } public static final License EMPTY_LICENSE = new License() { public boolean verify() { return false; } public String getValue(String property) { return null; } public String getName() { return Locale.localizedString("Not a valid donation key", "License"); } public boolean isReceipt() { return false; } @Override public boolean equals(Object obj) { return EMPTY_LICENSE == obj; } @Override public String toString() { return Locale.localizedString("Not a valid donation key", "License"); } }; }
false
true
public static License find() { final Collection<File> licenses = FileUtils.listFiles( new File(LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path")).getAbsolute()), new SuffixFileFilter(".cyberducklicense"), FalseFileFilter.FALSE); for(File license : licenses) { return LicenseFactory.create(LocalFactory.createLocal(license)); } final Collection<File> receipts = FileUtils.listFiles( new File(LocalFactory.createLocal(Preferences.instance().getProperty("application.receipt.path")).getAbsolute()), new NameFileFilter("receipt"), FalseFileFilter.FALSE); for(File receipt : receipts) { return LicenseFactory.create(LocalFactory.createLocal(receipt)); } log.info("No license found"); return EMPTY_LICENSE; }
public static License find() { Local support = LocalFactory.createLocal(Preferences.instance().getProperty("application.support.path")); if(support.exists()) { final Collection<File> keys = FileUtils.listFiles( new File(support.getAbsolute()), new SuffixFileFilter(".cyberducklicense"), FalseFileFilter.FALSE); for(File key : keys) { return LicenseFactory.create(LocalFactory.createLocal(key)); } } Local receipt = LocalFactory.createLocal(Preferences.instance().getProperty("application.receipt.path")); if(receipt.exists()) { final Collection<File> receipts = FileUtils.listFiles( new File(receipt.getAbsolute()), new NameFileFilter("receipt"), FalseFileFilter.FALSE); for(File key : receipts) { return LicenseFactory.create(LocalFactory.createLocal(key)); } } log.info("No license found"); return EMPTY_LICENSE; }
diff --git a/src/main/java/com/google/gerrit/server/ssh/Receive.java b/src/main/java/com/google/gerrit/server/ssh/Receive.java index db52a667e..b4ce970a9 100644 --- a/src/main/java/com/google/gerrit/server/ssh/Receive.java +++ b/src/main/java/com/google/gerrit/server/ssh/Receive.java @@ -1,1221 +1,1223 @@ // Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.ssh; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_HEAD; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_HEAD_CREATE; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_HEAD_REPLACE; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_HEAD_UPDATE; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_TAG; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_TAG_ANNOTATED; import static com.google.gerrit.client.reviewdb.ApprovalCategory.PUSH_TAG_ANY; import com.google.gerrit.client.Link; import com.google.gerrit.client.data.ApprovalType; import com.google.gerrit.client.reviewdb.AbstractAgreement; import com.google.gerrit.client.reviewdb.Account; import com.google.gerrit.client.reviewdb.AccountAgreement; import com.google.gerrit.client.reviewdb.AccountExternalId; import com.google.gerrit.client.reviewdb.AccountGroup; import com.google.gerrit.client.reviewdb.AccountGroupAgreement; import com.google.gerrit.client.reviewdb.ApprovalCategory; import com.google.gerrit.client.reviewdb.Branch; import com.google.gerrit.client.reviewdb.Change; import com.google.gerrit.client.reviewdb.ChangeApproval; import com.google.gerrit.client.reviewdb.ChangeMessage; import com.google.gerrit.client.reviewdb.ContributorAgreement; import com.google.gerrit.client.reviewdb.PatchSet; import com.google.gerrit.client.reviewdb.PatchSetInfo; import com.google.gerrit.client.reviewdb.ReviewDb; import com.google.gerrit.client.rpc.Common; import com.google.gerrit.git.PatchSetImporter; import com.google.gerrit.git.PushQueue; import com.google.gerrit.server.ChangeUtil; import com.google.gerrit.server.GerritServer; import com.google.gerrit.server.mail.CreateChangeSender; import com.google.gerrit.server.mail.EmailException; import com.google.gerrit.server.mail.MergedSender; import com.google.gerrit.server.mail.ReplacePatchSetSender; import com.google.gwtorm.client.OrmException; import com.google.gwtorm.client.OrmRunnable; import com.google.gwtorm.client.Transaction; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.Option; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spearce.jgit.lib.Constants; import org.spearce.jgit.lib.ObjectId; import org.spearce.jgit.lib.PersonIdent; import org.spearce.jgit.lib.Ref; import org.spearce.jgit.lib.RefUpdate; import org.spearce.jgit.revwalk.RevCommit; import org.spearce.jgit.revwalk.RevObject; import org.spearce.jgit.revwalk.RevSort; import org.spearce.jgit.revwalk.RevTag; import org.spearce.jgit.revwalk.RevWalk; import org.spearce.jgit.transport.PostReceiveHook; import org.spearce.jgit.transport.PreReceiveHook; import org.spearce.jgit.transport.ReceiveCommand; import org.spearce.jgit.transport.ReceivePack; import org.spearce.jgit.transport.ReceiveCommand.Result; import org.spearce.jgit.transport.ReceiveCommand.Type; import java.io.IOException; import java.io.PrintWriter; import java.sql.Timestamp; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Receives change upload over SSH using the Git receive-pack protocol. */ class Receive extends AbstractGitCommand { private static final Logger log = LoggerFactory.getLogger(Receive.class); private static final String NEW_CHANGE = "refs/for/"; private static final Pattern NEW_PATCHSET = Pattern.compile("^refs/changes/(?:[0-9][0-9]/)?([1-9][0-9]*)(?:/new)?$"); private final Set<Account.Id> reviewerId = new HashSet<Account.Id>(); private final Set<Account.Id> ccId = new HashSet<Account.Id>(); @Option(name = "--reviewer", aliases = {"--re"}, multiValued = true, metaVar = "EMAIL", usage = "request reviewer for change(s)") void addReviewer(final String nameOrEmail) throws CmdLineException { reviewerId.add(toAccountId(nameOrEmail)); } @Option(name = "--cc", aliases = {}, multiValued = true, metaVar = "EMAIL", usage = "CC user on change(s)") void addCC(final String nameOrEmail) throws CmdLineException { ccId.add(toAccountId(nameOrEmail)); } private GerritServer server; private ReceivePack rp; private PersonIdent refLogIdent; private ReceiveCommand newChange; private Branch destBranch; private final Set<String> myEmails = new HashSet<String>(); private final List<Change.Id> allNewChanges = new ArrayList<Change.Id>(); private final Map<Change.Id, ReceiveCommand> addByChange = new HashMap<Change.Id, ReceiveCommand>(); private final Map<ObjectId, Change> addByCommit = new HashMap<ObjectId, Change>(); private final Map<Change.Id, Change> changeCache = new HashMap<Change.Id, Change>(); private Map<ObjectId, Ref> refsById; @Override protected void preRun() throws Failure { super.preRun(); server = getGerritServer(); } @Override protected void runImpl() throws IOException, Failure { if (Common.getGerritConfig().isUseContributorAgreements() && proj.isUseContributorAgreements()) { verifyActiveContributorAgreement(); } loadMyEmails(); refLogIdent = ChangeUtil.toReflogIdent(userAccount, getRemoteAddress()); rp = new ReceivePack(repo); rp.setAllowCreates(true); rp.setAllowDeletes(true); rp.setAllowNonFastForwards(true); rp.setCheckReceivedObjects(true); rp.setRefLogIdent(refLogIdent); rp.setPreReceiveHook(new PreReceiveHook() { public void onPreReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { parseCommands(commands); createNewChanges(); appendPatchSets(); } }); rp.setPostReceiveHook(new PostReceiveHook() { public void onPostReceive(final ReceivePack arg0, final Collection<ReceiveCommand> commands) { for (final ReceiveCommand c : commands) { if (c.getResult() == Result.OK) { if (isHead(c)) { switch (c.getType()) { case CREATE: insertBranchEntity(c); autoCloseChanges(c); break; case DELETE: deleteBranchEntity(c); break; case UPDATE: case UPDATE_NONFASTFORWARD: autoCloseChanges(c); break; } } if (isHead(c) || isTag(c)) { // We only schedule heads and tags for replication. // Change refs are scheduled when they are created. // PushQueue.scheduleUpdate(proj.getNameKey(), c.getRefName()); } } } } }); rp.receive(in, out, err); if (!allNewChanges.isEmpty() && server.getCanonicalURL() != null) { // Make sure there isn't anything buffered; we want to give the // push client a chance to display its status report before we // show our own messages on standard error. // out.flush(); final String url = server.getCanonicalURL(); final PrintWriter msg = toPrintWriter(err); msg.write("\nNew Changes:\n"); for (final Change.Id c : allNewChanges) { msg.write(" " + url + c.get() + "\n"); } msg.write('\n'); msg.flush(); } } private void verifyActiveContributorAgreement() throws Failure { AbstractAgreement bestAgreement = null; ContributorAgreement bestCla = null; try { OUTER: for (final AccountGroup.Id groupId : getGroups()) { for (final AccountGroupAgreement a : db.accountGroupAgreements() .byGroup(groupId)) { final ContributorAgreement cla = db.contributorAgreements().get(a.getAgreementId()); if (cla == null) { continue; } bestAgreement = a; bestCla = cla; break OUTER; } } if (bestAgreement == null) { for (final AccountAgreement a : db.accountAgreements().byAccount( userAccount.getId()).toList()) { final ContributorAgreement cla = db.contributorAgreements().get(a.getAgreementId()); if (cla == null) { continue; } bestAgreement = a; bestCla = cla; break; } } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } if (bestCla != null && !bestCla.isActive()) { final StringBuilder msg = new StringBuilder(); msg.append("\nfatal: "); msg.append(bestCla.getShortName()); msg.append(" contributor agreement is expired.\n"); if (server.getCanonicalURL() != null) { msg.append("\nPlease complete a new agreement"); msg.append(":\n\n "); msg.append(server.getCanonicalURL()); msg.append("Gerrit#"); msg.append(Link.SETTINGS_AGREEMENTS); msg.append("\n"); } msg.append("\n"); throw new UnloggedFailure(1, msg.toString()); } if (bestCla != null && bestCla.isRequireContactInformation()) { boolean fail = false; fail |= missing(userAccount.getFullName()); fail |= missing(userAccount.getPreferredEmail()); fail |= !userAccount.isContactFiled(); if (fail) { final StringBuilder msg = new StringBuilder(); msg.append("\nfatal: "); msg.append(bestCla.getShortName()); msg.append(" contributor agreement requires"); msg.append(" current contact information.\n"); if (server.getCanonicalURL() != null) { msg.append("\nPlease review your contact information"); msg.append(":\n\n "); msg.append(server.getCanonicalURL()); msg.append("Gerrit#"); msg.append(Link.SETTINGS_CONTACT); msg.append("\n"); } msg.append("\n"); throw new UnloggedFailure(1, msg.toString()); } } if (bestAgreement != null) { switch (bestAgreement.getStatus()) { case VERIFIED: return; case REJECTED: throw new UnloggedFailure(1, "\nfatal: " + bestCla.getShortName() + " contributor agreement was rejected." + "\n (rejected on " + bestAgreement.getReviewedOn() + ")\n"); case NEW: throw new UnloggedFailure(1, "\nfatal: " + bestCla.getShortName() + " contributor agreement is still pending review.\n"); } } final StringBuilder msg = new StringBuilder(); msg.append("\nfatal: A Contributor Agreement" + " must be completed before uploading"); if (server.getCanonicalURL() != null) { msg.append(":\n\n "); msg.append(server.getCanonicalURL()); msg.append("Gerrit#"); msg.append(Link.SETTINGS_AGREEMENTS); msg.append("\n"); } else { msg.append("."); } msg.append("\n"); throw new UnloggedFailure(1, msg.toString()); } private static boolean missing(final String value) { return value == null || value.trim().equals(""); } private void loadMyEmails() throws Failure { addEmail(userAccount.getPreferredEmail()); try { for (final AccountExternalId id : db.accountExternalIds().byAccount( userAccount.getId())) { addEmail(id.getEmailAddress()); } } catch (OrmException e) { throw new Failure(1, "fatal: database error", e); } } private void addEmail(final String email) { if (email != null && email.length() > 0) { myEmails.add(email); } } private Account.Id toAccountId(final String nameOrEmail) throws CmdLineException { final String efmt = server.getEmailFormat(); final boolean haveFormat = efmt != null && efmt.contains("{0}"); try { final HashSet<Account.Id> matches = new HashSet<Account.Id>(); String email = splitEmail(nameOrEmail); if (email == null && haveFormat && !nameOrEmail.contains(" ")) { // Not a full name, since it has no space, and not an email // address either. Assume it is just the local portion of // the organizations standard email format, and complete out. // email = MessageFormat.format(efmt, nameOrEmail); } if (email == null) { // Not an email address implies it was a full name, search by // full name hoping to get a unique match. // final String n = nameOrEmail; for (final Account a : db.accounts().suggestByFullName(n, n, 2)) { matches.add(a.getId()); } } else { // Scan email addresses for any potential matches. // for (final AccountExternalId e : db.accountExternalIds() .byEmailAddress(email)) { matches.add(e.getAccountId()); } if (matches.isEmpty()) { for (final Account a : db.accounts().byPreferredEmail(email)) { matches.add(a.getId()); } } } switch (matches.size()) { case 0: throw new CmdLineException("\"" + nameOrEmail + "\" is not registered"); case 1: return (matches.iterator().next()); default: throw new CmdLineException("\"" + nameOrEmail + "\" matches multiple accounts"); } } catch (OrmException e) { log.error("Cannot lookup name/email address", e); throw new CmdLineException("database is down"); } } private static String splitEmail(final String nameOrEmail) { final int lt = nameOrEmail.indexOf('<'); final int gt = nameOrEmail.indexOf('>'); if (lt >= 0 && gt > lt) { return nameOrEmail.substring(lt + 1, gt); } if (nameOrEmail.contains("@")) { return nameOrEmail; } return null; } private void parseCommands(final Collection<ReceiveCommand> commands) { for (final ReceiveCommand cmd : commands) { if (cmd.getResult() != ReceiveCommand.Result.NOT_ATTEMPTED) { // Already rejected by the core receive process. // continue; } if (cmd.getRefName().startsWith(NEW_CHANGE)) { parseNewChangeCommand(cmd); continue; } final Matcher m = NEW_PATCHSET.matcher(cmd.getRefName()); if (m.matches()) { // The referenced change must exist and must still be open. // final Change.Id changeId = Change.Id.parse(m.group(1)); parseNewPatchSetCommand(cmd, changeId); continue; } switch (cmd.getType()) { case CREATE: parseCreate(cmd); continue; case UPDATE: parseUpdate(cmd); continue; case DELETE: case UPDATE_NONFASTFORWARD: parseRewindOrDelete(cmd); continue; } // Everything else is bogus as far as we are concerned. // reject(cmd); } } private void parseCreate(final ReceiveCommand cmd) { if (isHead(cmd) && canPerform(PUSH_HEAD, PUSH_HEAD_CREATE)) { // Let the core receive process handle it } else if (isTag(cmd) && canPerform(PUSH_TAG, (short) 1)) { parseCreateTag(cmd); } else { reject(cmd); } } private void parseCreateTag(final ReceiveCommand cmd) { try { final RevObject obj = rp.getRevWalk().parseAny(cmd.getNewId()); if (!(obj instanceof RevTag)) { reject(cmd, "not annotated tag"); return; } if (canPerform(PUSH_TAG, PUSH_TAG_ANY)) { // If we can push any tag, validation is sufficient at this point. // return; } final RevTag tag = (RevTag) obj; final PersonIdent tagger = tag.getTaggerIdent(); if (tagger == null) { reject(cmd, "no tagger"); return; } final String email = tagger.getEmailAddress(); if (!myEmails.contains(email)) { reject(cmd, "invalid tagger " + email); return; } if (tag.getFullMessage().contains("-----BEGIN PGP SIGNATURE-----\n")) { // Signed tags are currently assumed valid, as we don't have a GnuPG // key ring to validate them against, and we might be missing the // necessary (but currently optional) BouncyCastle Crypto libraries. // } else if (canPerform(PUSH_TAG, PUSH_TAG_ANNOTATED)) { // User is permitted to push an unsigned annotated tag. // } else { reject(cmd, "must be signed"); return; } // Let the core receive process handle it // } catch (IOException e) { log.error("Bad tag " + cmd.getRefName() + " " + cmd.getNewId().name(), e); reject(cmd, "invalid object"); } } private void parseUpdate(final ReceiveCommand cmd) { if (isHead(cmd) && canPerform(PUSH_HEAD, PUSH_HEAD_UPDATE)) { // Let the core receive process handle it } else { reject(cmd); } } private void parseRewindOrDelete(final ReceiveCommand cmd) { if (isHead(cmd) && canPerform(PUSH_HEAD, PUSH_HEAD_REPLACE)) { // Let the core receive process handle it } else if (isHead(cmd) && cmd.getType() == Type.UPDATE_NONFASTFORWARD) { cmd.setResult(ReceiveCommand.Result.REJECTED_NONFASTFORWARD); } else { reject(cmd); } } private void parseNewChangeCommand(final ReceiveCommand cmd) { // Permit exactly one new change request per push. // if (newChange != null) { reject(cmd, "duplicate request"); return; } newChange = cmd; String destBranchName = cmd.getRefName().substring(NEW_CHANGE.length()); if (!destBranchName.startsWith(Constants.R_REFS)) { destBranchName = Constants.R_HEADS + destBranchName; } try { destBranch = db.branches().get( new Branch.NameKey(proj.getNameKey(), destBranchName)); } catch (OrmException e) { log.error("Cannot lookup branch " + proj + " " + destBranchName, e); reject(cmd, "database error"); return; } if (destBranch == null) { String n = destBranchName; if (n.startsWith(Constants.R_HEADS)) n = n.substring(Constants.R_HEADS.length()); reject(cmd, "branch " + n + " not found"); return; } } private void parseNewPatchSetCommand(final ReceiveCommand cmd, final Change.Id changeId) { if (cmd.getType() != ReceiveCommand.Type.CREATE) { reject(cmd, "invalid usage"); return; } final Change changeEnt; try { changeEnt = db.changes().get(changeId); } catch (OrmException e) { log.error("Cannot lookup existing change " + changeId, e); reject(cmd, "database error"); return; } if (changeEnt == null) { reject(cmd, "change " + changeId.get() + " not found"); return; } if (changeEnt.getStatus().isClosed()) { reject(cmd, "change " + changeId.get() + " closed"); return; } if (addByChange.containsKey(changeId)) { reject(cmd, "duplicate request"); return; } if (addByCommit.containsKey(cmd.getNewId())) { reject(cmd, "duplicate request"); return; } addByChange.put(changeId, cmd); addByCommit.put(cmd.getNewId(), changeEnt); changeCache.put(changeId, changeEnt); } private void createNewChanges() { if (newChange == null || newChange.getResult() != ReceiveCommand.Result.NOT_ATTEMPTED) { return; } final List<RevCommit> toCreate = new ArrayList<RevCommit>(); final RevWalk walk = rp.getRevWalk(); walk.reset(); walk.sort(RevSort.TOPO); walk.sort(RevSort.REVERSE, true); try { walk.markStart(walk.parseCommit(newChange.getNewId())); for (final Ref r : rp.getAdvertisedRefs().values()) { try { walk.markUninteresting(walk.parseCommit(r.getObjectId())); } catch (IOException e) { continue; } } for (;;) { final RevCommit c = walk.next(); if (c == null) { break; } if (addByCommit.containsKey(c.copy())) { // This commit is slated to replace an existing PatchSet. // continue; } if (!validCommitter(newChange, c)) { return; } toCreate.add(c); } } catch (IOException e) { // Should never happen, the core receive process would have // identified the missing object earlier before we got control. // newChange.setResult(Result.REJECTED_MISSING_OBJECT); log.error("Invalid pack upload; one or more objects weren't sent", e); } if (toCreate.isEmpty() && addByChange.isEmpty()) { reject(newChange, "no new changes"); return; } for (final RevCommit c : toCreate) { try { createChange(walk, c); } catch (IOException e) { log.error("Error computing patch of commit " + c.name(), e); reject(newChange, "diff error"); return; } catch (OrmException e) { log.error("Error creating change for commit " + c.name(), e); reject(newChange, "database error"); return; } } newChange.setResult(ReceiveCommand.Result.OK); } private void createChange(final RevWalk walk, final RevCommit c) throws OrmException, IOException { walk.parseBody(c); final Transaction txn = db.beginTransaction(); final Account.Id me = userAccount.getId(); final Change change = new Change(new Change.Id(db.nextChangeId()), me, destBranch .getNameKey()); final PatchSet ps = new PatchSet(change.newPatchSetId()); ps.setCreatedOn(change.getCreatedOn()); ps.setUploader(me); final PatchSetImporter imp = new PatchSetImporter(server, db, proj.getNameKey(), repo, c, ps, true); imp.setTransaction(txn); imp.run(); change.setCurrentPatchSet(imp.getPatchSetInfo()); ChangeUtil.updated(change); db.changes().insert(Collections.singleton(change), txn); final Set<Account.Id> haveApprovals = new HashSet<Account.Id>(); final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); haveApprovals.add(me); if (allTypes.size() > 0) { final Account.Id authorId = imp.getPatchSetInfo().getAuthor() != null ? imp.getPatchSetInfo() .getAuthor().getAccount() : null; final Account.Id committerId = imp.getPatchSetInfo().getCommitter() != null ? imp.getPatchSetInfo() .getCommitter().getAccount() : null; final ApprovalCategory.Id catId = allTypes.get(allTypes.size() - 1).getCategory().getId(); if (authorId != null && haveApprovals.add(authorId)) { db.changeApprovals().insert( Collections.singleton(new ChangeApproval(new ChangeApproval.Key( change.getId(), authorId, catId), (short) 0)), txn); } if (committerId != null && haveApprovals.add(committerId)) { db.changeApprovals().insert( Collections.singleton(new ChangeApproval(new ChangeApproval.Key( change.getId(), committerId, catId), (short) 0)), txn); } for (final Account.Id reviewer : reviewerId) { if (haveApprovals.add(reviewer)) { db.changeApprovals().insert( Collections.singleton(new ChangeApproval(new ChangeApproval.Key( change.getId(), reviewer, catId), (short) 0)), txn); } } } txn.commit(); final RefUpdate ru = repo.updateRef(ps.getRefName()); ru.setForceUpdate(true); ru.setNewObjectId(c); ru.setRefLogIdent(refLogIdent); ru.setRefLogMessage("uploaded", false); if (ru.update(walk) != RefUpdate.Result.NEW) { throw new IOException("Failed to create ref " + ps.getRefName() + " in " + repo.getDirectory() + ": " + ru.getResult()); } PushQueue.scheduleUpdate(proj.getNameKey(), ru.getName()); allNewChanges.add(change.getId()); try { final CreateChangeSender cm = new CreateChangeSender(server, change); cm.setFrom(me); cm.setPatchSet(ps, imp.getPatchSetInfo()); cm.setReviewDb(db); cm.addReviewers(reviewerId); cm.addExtraCC(ccId); cm.send(); } catch (EmailException e) { log.error("Cannot send email for new change " + change.getId(), e); } } private void appendPatchSets() { for (Map.Entry<Change.Id, ReceiveCommand> e : addByChange.entrySet()) { final ReceiveCommand cmd = e.getValue(); final Change.Id changeId = e.getKey(); try { appendPatchSet(changeId, cmd); } catch (IOException err) { log.error("Error computing replacement patch for change " + changeId + ", commit " + cmd.getNewId().name(), err); reject(cmd, "diff error"); } catch (OrmException err) { log.error("Error storing replacement patch for change " + changeId + ", commit " + cmd.getNewId().name(), err); reject(cmd, "database error"); } if (cmd.getResult() == ReceiveCommand.Result.NOT_ATTEMPTED) { log.error("Replacement patch for change " + changeId + ", commit " + cmd.getNewId().name() + " wasn't attempted." + " This is a bug in the receive process implementation."); reject(cmd, "internal error"); } } } private void appendPatchSet(final Change.Id changeId, final ReceiveCommand cmd) throws IOException, OrmException { final RevCommit c = rp.getRevWalk().parseCommit(cmd.getNewId()); rp.getRevWalk().parseBody(c); if (!validCommitter(cmd, c)) { return; } final Account.Id me = userAccount.getId(); final ReplaceResult result; final Set<Account.Id> oldReviewers = new HashSet<Account.Id>(); final Set<Account.Id> oldCC = new HashSet<Account.Id>(); result = db.run(new OrmRunnable<ReplaceResult, ReviewDb>() { public ReplaceResult run(final ReviewDb db, final Transaction txn, final boolean isRetry) throws OrmException { final Change change; if (isRetry) { change = db.changes().get(changeId); if (change == null) { reject(cmd, "change " + changeId.get() + " not found"); return null; } if (change.getStatus().isClosed()) { reject(cmd, "change " + changeId.get() + " closed"); return null; } if (change.getDest() == null || !proj.getNameKey().equals(change.getDest().getParentKey())) { reject(cmd, "change " + changeId.get() + " not in " + proj.getName()); return null; } } else { change = changeCache.get(changeId); } final HashSet<String> existingRevisions = new HashSet<String>(); for (final PatchSet ps : db.patchSets().byChange(changeId)) { if (ps.getRevision() != null) { existingRevisions.add(ps.getRevision().get()); } } // Don't allow the same commit to appear twice on the same change // if (existingRevisions.contains(c.name())) { reject(cmd, "patch set exists"); return null; } // Don't allow a change to directly depend upon itself. This is a // very common error due to users making a new commit rather than // amending when trying to address review comments. // for (final RevCommit p : c.getParents()) { if (existingRevisions.contains(p.name())) { reject(cmd, "squash commits first"); return null; } } final PatchSet ps = new PatchSet(change.newPatchSetId()); ps.setCreatedOn(new Timestamp(System.currentTimeMillis())); ps.setUploader(userAccount.getId()); final PatchSetImporter imp = new PatchSetImporter(server, db, proj.getNameKey(), repo, c, ps, true); imp.setTransaction(txn); try { imp.run(); } catch (IOException e) { throw new OrmException(e); } final Ref mergedInto = findMergedInto(change.getDest().get(), c); final ReplaceResult result = new ReplaceResult(); result.mergedIntoRef = mergedInto != null ? mergedInto.getName() : null; result.change = change; result.patchSet = ps; result.info = imp.getPatchSetInfo(); final Account.Id authorId = imp.getPatchSetInfo().getAuthor() != null ? imp.getPatchSetInfo() .getAuthor().getAccount() : null; final Account.Id committerId = imp.getPatchSetInfo().getCommitter() != null ? imp .getPatchSetInfo().getCommitter().getAccount() : null; boolean haveAuthor = false; boolean haveCommitter = false; final Set<Account.Id> haveApprovals = new HashSet<Account.Id>(); oldReviewers.clear(); oldCC.clear(); result.approvals = db.changeApprovals().byChange(change.getId()).toList(); for (ChangeApproval a : result.approvals) { haveApprovals.add(a.getAccountId()); if (a.getValue() != 0) { oldReviewers.add(a.getAccountId()); } else { oldCC.add(a.getAccountId()); } if (!haveAuthor && authorId != null && a.getAccountId().equals(authorId)) { haveAuthor = true; } if (!haveCommitter && committerId != null && a.getAccountId().equals(committerId)) { haveCommitter = true; } if (me.equals(a.getAccountId())) { if (a.getValue() > 0 && ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { a.clear(); } else { // Leave my own approvals alone. // } } else if (a.getValue() > 0) { a.clear(); } } final ChangeMessage msg = new ChangeMessage(new ChangeMessage.Key(change.getId(), ChangeUtil .messageUUID(db)), me, ps.getCreatedOn()); msg.setMessage("Uploaded patch set " + ps.getPatchSetId() + "."); db.changeMessages().insert(Collections.singleton(msg), txn); result.msg = msg; if (result.mergedIntoRef != null) { // Change was already submitted to a branch, close it. // markChangeMergedByPush(db, txn, result); } else { // Change should be new, so it can go through review again. // change.setStatus(Change.Status.NEW); change.setCurrentPatchSet(imp.getPatchSetInfo()); ChangeUtil.updated(change); db.changeApprovals().update(result.approvals, txn); db.changes().update(Collections.singleton(change), txn); } final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); if (allTypes.size() > 0) { final ApprovalCategory.Id catId = allTypes.get(allTypes.size() - 1).getCategory().getId(); if (authorId != null && haveApprovals.add(authorId)) { insertDummyChangeApproval(result, authorId, catId, db, txn); } if (committerId != null && haveApprovals.add(committerId)) { insertDummyChangeApproval(result, committerId, catId, db, txn); } for (final Account.Id reviewer : reviewerId) { - insertDummyChangeApproval(result, reviewer, catId, db, txn); + if (haveApprovals.add(reviewer)) { + insertDummyChangeApproval(result, reviewer, catId, db, txn); + } } } return result; } }); if (result != null) { final PatchSet ps = result.patchSet; final RefUpdate ru = repo.updateRef(ps.getRefName()); ru.setForceUpdate(true); ru.setNewObjectId(c); ru.setRefLogIdent(refLogIdent); ru.setRefLogMessage("uploaded", false); if (ru.update(rp.getRevWalk()) != RefUpdate.Result.NEW) { throw new IOException("Failed to create ref " + ps.getRefName() + " in " + repo.getDirectory() + ": " + ru.getResult()); } PushQueue.scheduleUpdate(proj.getNameKey(), ru.getName()); cmd.setResult(ReceiveCommand.Result.OK); try { final ReplacePatchSetSender cm = new ReplacePatchSetSender(server, result.change); cm.setFrom(me); cm.setPatchSet(ps, result.info); cm.setChangeMessage(result.msg); cm.setReviewDb(db); cm.addReviewers(reviewerId); cm.addExtraCC(ccId); cm.addReviewers(oldReviewers); cm.addExtraCC(oldCC); cm.send(); } catch (EmailException e) { log.error("Cannot send email for new patch set " + ps.getId(), e); } } sendMergedEmail(result); } private void insertDummyChangeApproval(final ReplaceResult result, final Account.Id forAccount, final ApprovalCategory.Id catId, final ReviewDb db, final Transaction txn) throws OrmException { final ChangeApproval ca = new ChangeApproval(new ChangeApproval.Key(result.change.getId(), forAccount, catId), (short) 0); ca.cache(result.change); db.changeApprovals().insert(Collections.singleton(ca), txn); } private Ref findMergedInto(final String first, final RevCommit commit) { try { final Map<String, Ref> all = repo.getAllRefs(); Ref firstRef = all.get(first); if (firstRef != null && isMergedInto(commit, firstRef)) { return firstRef; } for (Ref ref : all.values()) { if (isHead(ref)) { if (isMergedInto(commit, ref)) { return ref; } } } return null; } catch (IOException e) { log.warn("Can't check for already submitted change", e); return null; } } private boolean isMergedInto(final RevCommit commit, final Ref ref) throws IOException { final RevWalk rw = rp.getRevWalk(); return rw.isMergedInto(commit, rw.parseCommit(ref.getObjectId())); } private static class ReplaceResult { Change change; PatchSet patchSet; PatchSetInfo info; ChangeMessage msg; String mergedIntoRef; List<ChangeApproval> approvals; } private boolean validCommitter(final ReceiveCommand cmd, final RevCommit c) { // Require that committer matches the uploader. final PersonIdent committer = c.getCommitterIdent(); final String email = committer.getEmailAddress(); if (myEmails.contains(email)) { return true; } else { reject(cmd, "invalid committer " + email); return false; } } private void insertBranchEntity(final ReceiveCommand c) { try { final Branch.NameKey nameKey = new Branch.NameKey(proj.getNameKey(), c.getRefName()); final Branch.Id idKey = new Branch.Id(db.nextBranchId()); final Branch b = new Branch(nameKey, idKey); db.branches().insert(Collections.singleton(b)); } catch (OrmException e) { final String msg = "database failure creating " + c.getRefName(); log.error(msg, e); try { err.write(("remote error: " + msg + "\n").getBytes("UTF-8")); err.flush(); } catch (IOException e2) { // Ignore errors writing to the client } } } private void deleteBranchEntity(final ReceiveCommand c) { try { final Branch.NameKey nameKey = new Branch.NameKey(proj.getNameKey(), c.getRefName()); final Branch b = db.branches().get(nameKey); if (b != null) { db.branches().delete(Collections.singleton(b)); } } catch (OrmException e) { final String msg = "database failure deleting " + c.getRefName(); log.error(msg, e); try { err.write(("remote error: " + msg + "\n").getBytes("UTF-8")); err.flush(); } catch (IOException e2) { // Ignore errors writing to the client } } } private void autoCloseChanges(final ReceiveCommand cmd) { final RevWalk rw = rp.getRevWalk(); try { rw.reset(); rw.markStart(rw.parseCommit(cmd.getNewId())); if (!ObjectId.zeroId().equals(cmd.getOldId())) { rw.markUninteresting(rw.parseCommit(cmd.getOldId())); } final Map<ObjectId, Ref> changes = changeRefsById(); RevCommit c; while ((c = rw.next()) != null) { Ref r = changes.get(c.copy()); if (r != null) { closeChange(cmd, PatchSet.Id.fromRef(r.getName())); } } } catch (IOException e) { log.error("Can't scan for changes to close", e); } catch (OrmException e) { log.error("Can't scan for changes to close", e); } } private void closeChange(final ReceiveCommand cmd, final PatchSet.Id psi) throws OrmException { final String refName = cmd.getRefName(); final Change.Id cid = psi.getParentKey(); final ReplaceResult result = db.run(new OrmRunnable<ReplaceResult, ReviewDb>() { @Override public ReplaceResult run(ReviewDb db, Transaction txn, boolean retry) throws OrmException { final Change change = db.changes().get(cid); final PatchSet ps = db.patchSets().get(psi); final PatchSetInfo psInfo = db.patchSetInfo().get(psi); if (change == null || ps == null || psInfo == null) { log.warn(proj.getName() + " " + psi + " is missing"); return null; } if (change.getStatus() == Change.Status.MERGED) { // If its already merged, don't make further updates, it // might just be moving from an experimental branch into // a more stable branch. // return null; } final ReplaceResult result = new ReplaceResult(); result.change = change; result.patchSet = ps; result.info = psInfo; result.mergedIntoRef = refName; markChangeMergedByPush(db, txn, result); return result; } }); sendMergedEmail(result); } private Map<ObjectId, Ref> changeRefsById() { if (refsById == null) { refsById = new HashMap<ObjectId, Ref>(); for (final Ref r : repo.getAllRefs().values()) { if (PatchSet.isRef(r.getName())) { refsById.put(r.getObjectId(), r); } } } return refsById; } private void markChangeMergedByPush(final ReviewDb db, final Transaction txn, final ReplaceResult result) throws OrmException { final Change change = result.change; final String mergedIntoRef = result.mergedIntoRef; change.setCurrentPatchSet(result.info); change.setStatus(Change.Status.MERGED); ChangeUtil.updated(change); if (result.approvals == null) { result.approvals = db.changeApprovals().byChange(change.getId()).toList(); } for (ChangeApproval a : result.approvals) { a.cache(change); } final StringBuilder msgBuf = new StringBuilder(); msgBuf.append("Change has been successfully pushed"); if (!mergedIntoRef.equals(change.getDest().get())) { msgBuf.append(" into "); if (mergedIntoRef.startsWith(Constants.R_HEADS)) { msgBuf.append("branch "); msgBuf.append(repo.shortenRefName(mergedIntoRef)); } else { msgBuf.append(mergedIntoRef); } } msgBuf.append("."); final ChangeMessage msg = new ChangeMessage(new ChangeMessage.Key(change.getId(), ChangeUtil .messageUUID(db)), getAccountId()); msg.setMessage(msgBuf.toString()); db.changeApprovals().update(result.approvals, txn); db.changeMessages().insert(Collections.singleton(msg), txn); db.changes().update(Collections.singleton(change), txn); } private void sendMergedEmail(final ReplaceResult result) { if (result != null && result.mergedIntoRef != null) { try { final MergedSender cm = new MergedSender(server, result.change); cm.setFrom(getAccountId()); cm.setReviewDb(db); cm.setPatchSet(result.patchSet, result.info); cm.setDest(new Branch.NameKey(proj.getNameKey(), result.mergedIntoRef)); cm.send(); } catch (EmailException e) { final PatchSet.Id psi = result.patchSet.getId(); log.error("Cannot send email for submitted patch set " + psi, e); } } } private static void reject(final ReceiveCommand cmd) { reject(cmd, "prohibited by Gerrit"); } private static void reject(final ReceiveCommand cmd, final String why) { cmd.setResult(ReceiveCommand.Result.REJECTED_OTHER_REASON, why); } private static boolean isTag(final ReceiveCommand cmd) { return cmd.getRefName().startsWith(Constants.R_TAGS); } private static boolean isHead(final Ref ref) { return ref.getName().startsWith(Constants.R_HEADS); } private static boolean isHead(final ReceiveCommand cmd) { return cmd.getRefName().startsWith(Constants.R_HEADS); } }
true
true
private void appendPatchSet(final Change.Id changeId, final ReceiveCommand cmd) throws IOException, OrmException { final RevCommit c = rp.getRevWalk().parseCommit(cmd.getNewId()); rp.getRevWalk().parseBody(c); if (!validCommitter(cmd, c)) { return; } final Account.Id me = userAccount.getId(); final ReplaceResult result; final Set<Account.Id> oldReviewers = new HashSet<Account.Id>(); final Set<Account.Id> oldCC = new HashSet<Account.Id>(); result = db.run(new OrmRunnable<ReplaceResult, ReviewDb>() { public ReplaceResult run(final ReviewDb db, final Transaction txn, final boolean isRetry) throws OrmException { final Change change; if (isRetry) { change = db.changes().get(changeId); if (change == null) { reject(cmd, "change " + changeId.get() + " not found"); return null; } if (change.getStatus().isClosed()) { reject(cmd, "change " + changeId.get() + " closed"); return null; } if (change.getDest() == null || !proj.getNameKey().equals(change.getDest().getParentKey())) { reject(cmd, "change " + changeId.get() + " not in " + proj.getName()); return null; } } else { change = changeCache.get(changeId); } final HashSet<String> existingRevisions = new HashSet<String>(); for (final PatchSet ps : db.patchSets().byChange(changeId)) { if (ps.getRevision() != null) { existingRevisions.add(ps.getRevision().get()); } } // Don't allow the same commit to appear twice on the same change // if (existingRevisions.contains(c.name())) { reject(cmd, "patch set exists"); return null; } // Don't allow a change to directly depend upon itself. This is a // very common error due to users making a new commit rather than // amending when trying to address review comments. // for (final RevCommit p : c.getParents()) { if (existingRevisions.contains(p.name())) { reject(cmd, "squash commits first"); return null; } } final PatchSet ps = new PatchSet(change.newPatchSetId()); ps.setCreatedOn(new Timestamp(System.currentTimeMillis())); ps.setUploader(userAccount.getId()); final PatchSetImporter imp = new PatchSetImporter(server, db, proj.getNameKey(), repo, c, ps, true); imp.setTransaction(txn); try { imp.run(); } catch (IOException e) { throw new OrmException(e); } final Ref mergedInto = findMergedInto(change.getDest().get(), c); final ReplaceResult result = new ReplaceResult(); result.mergedIntoRef = mergedInto != null ? mergedInto.getName() : null; result.change = change; result.patchSet = ps; result.info = imp.getPatchSetInfo(); final Account.Id authorId = imp.getPatchSetInfo().getAuthor() != null ? imp.getPatchSetInfo() .getAuthor().getAccount() : null; final Account.Id committerId = imp.getPatchSetInfo().getCommitter() != null ? imp .getPatchSetInfo().getCommitter().getAccount() : null; boolean haveAuthor = false; boolean haveCommitter = false; final Set<Account.Id> haveApprovals = new HashSet<Account.Id>(); oldReviewers.clear(); oldCC.clear(); result.approvals = db.changeApprovals().byChange(change.getId()).toList(); for (ChangeApproval a : result.approvals) { haveApprovals.add(a.getAccountId()); if (a.getValue() != 0) { oldReviewers.add(a.getAccountId()); } else { oldCC.add(a.getAccountId()); } if (!haveAuthor && authorId != null && a.getAccountId().equals(authorId)) { haveAuthor = true; } if (!haveCommitter && committerId != null && a.getAccountId().equals(committerId)) { haveCommitter = true; } if (me.equals(a.getAccountId())) { if (a.getValue() > 0 && ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { a.clear(); } else { // Leave my own approvals alone. // } } else if (a.getValue() > 0) { a.clear(); } } final ChangeMessage msg = new ChangeMessage(new ChangeMessage.Key(change.getId(), ChangeUtil .messageUUID(db)), me, ps.getCreatedOn()); msg.setMessage("Uploaded patch set " + ps.getPatchSetId() + "."); db.changeMessages().insert(Collections.singleton(msg), txn); result.msg = msg; if (result.mergedIntoRef != null) { // Change was already submitted to a branch, close it. // markChangeMergedByPush(db, txn, result); } else { // Change should be new, so it can go through review again. // change.setStatus(Change.Status.NEW); change.setCurrentPatchSet(imp.getPatchSetInfo()); ChangeUtil.updated(change); db.changeApprovals().update(result.approvals, txn); db.changes().update(Collections.singleton(change), txn); } final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); if (allTypes.size() > 0) { final ApprovalCategory.Id catId = allTypes.get(allTypes.size() - 1).getCategory().getId(); if (authorId != null && haveApprovals.add(authorId)) { insertDummyChangeApproval(result, authorId, catId, db, txn); } if (committerId != null && haveApprovals.add(committerId)) { insertDummyChangeApproval(result, committerId, catId, db, txn); } for (final Account.Id reviewer : reviewerId) { insertDummyChangeApproval(result, reviewer, catId, db, txn); } } return result; } }); if (result != null) { final PatchSet ps = result.patchSet; final RefUpdate ru = repo.updateRef(ps.getRefName()); ru.setForceUpdate(true); ru.setNewObjectId(c); ru.setRefLogIdent(refLogIdent); ru.setRefLogMessage("uploaded", false); if (ru.update(rp.getRevWalk()) != RefUpdate.Result.NEW) { throw new IOException("Failed to create ref " + ps.getRefName() + " in " + repo.getDirectory() + ": " + ru.getResult()); } PushQueue.scheduleUpdate(proj.getNameKey(), ru.getName()); cmd.setResult(ReceiveCommand.Result.OK); try { final ReplacePatchSetSender cm = new ReplacePatchSetSender(server, result.change); cm.setFrom(me); cm.setPatchSet(ps, result.info); cm.setChangeMessage(result.msg); cm.setReviewDb(db); cm.addReviewers(reviewerId); cm.addExtraCC(ccId); cm.addReviewers(oldReviewers); cm.addExtraCC(oldCC); cm.send(); } catch (EmailException e) { log.error("Cannot send email for new patch set " + ps.getId(), e); } } sendMergedEmail(result); }
private void appendPatchSet(final Change.Id changeId, final ReceiveCommand cmd) throws IOException, OrmException { final RevCommit c = rp.getRevWalk().parseCommit(cmd.getNewId()); rp.getRevWalk().parseBody(c); if (!validCommitter(cmd, c)) { return; } final Account.Id me = userAccount.getId(); final ReplaceResult result; final Set<Account.Id> oldReviewers = new HashSet<Account.Id>(); final Set<Account.Id> oldCC = new HashSet<Account.Id>(); result = db.run(new OrmRunnable<ReplaceResult, ReviewDb>() { public ReplaceResult run(final ReviewDb db, final Transaction txn, final boolean isRetry) throws OrmException { final Change change; if (isRetry) { change = db.changes().get(changeId); if (change == null) { reject(cmd, "change " + changeId.get() + " not found"); return null; } if (change.getStatus().isClosed()) { reject(cmd, "change " + changeId.get() + " closed"); return null; } if (change.getDest() == null || !proj.getNameKey().equals(change.getDest().getParentKey())) { reject(cmd, "change " + changeId.get() + " not in " + proj.getName()); return null; } } else { change = changeCache.get(changeId); } final HashSet<String> existingRevisions = new HashSet<String>(); for (final PatchSet ps : db.patchSets().byChange(changeId)) { if (ps.getRevision() != null) { existingRevisions.add(ps.getRevision().get()); } } // Don't allow the same commit to appear twice on the same change // if (existingRevisions.contains(c.name())) { reject(cmd, "patch set exists"); return null; } // Don't allow a change to directly depend upon itself. This is a // very common error due to users making a new commit rather than // amending when trying to address review comments. // for (final RevCommit p : c.getParents()) { if (existingRevisions.contains(p.name())) { reject(cmd, "squash commits first"); return null; } } final PatchSet ps = new PatchSet(change.newPatchSetId()); ps.setCreatedOn(new Timestamp(System.currentTimeMillis())); ps.setUploader(userAccount.getId()); final PatchSetImporter imp = new PatchSetImporter(server, db, proj.getNameKey(), repo, c, ps, true); imp.setTransaction(txn); try { imp.run(); } catch (IOException e) { throw new OrmException(e); } final Ref mergedInto = findMergedInto(change.getDest().get(), c); final ReplaceResult result = new ReplaceResult(); result.mergedIntoRef = mergedInto != null ? mergedInto.getName() : null; result.change = change; result.patchSet = ps; result.info = imp.getPatchSetInfo(); final Account.Id authorId = imp.getPatchSetInfo().getAuthor() != null ? imp.getPatchSetInfo() .getAuthor().getAccount() : null; final Account.Id committerId = imp.getPatchSetInfo().getCommitter() != null ? imp .getPatchSetInfo().getCommitter().getAccount() : null; boolean haveAuthor = false; boolean haveCommitter = false; final Set<Account.Id> haveApprovals = new HashSet<Account.Id>(); oldReviewers.clear(); oldCC.clear(); result.approvals = db.changeApprovals().byChange(change.getId()).toList(); for (ChangeApproval a : result.approvals) { haveApprovals.add(a.getAccountId()); if (a.getValue() != 0) { oldReviewers.add(a.getAccountId()); } else { oldCC.add(a.getAccountId()); } if (!haveAuthor && authorId != null && a.getAccountId().equals(authorId)) { haveAuthor = true; } if (!haveCommitter && committerId != null && a.getAccountId().equals(committerId)) { haveCommitter = true; } if (me.equals(a.getAccountId())) { if (a.getValue() > 0 && ApprovalCategory.SUBMIT.equals(a.getCategoryId())) { a.clear(); } else { // Leave my own approvals alone. // } } else if (a.getValue() > 0) { a.clear(); } } final ChangeMessage msg = new ChangeMessage(new ChangeMessage.Key(change.getId(), ChangeUtil .messageUUID(db)), me, ps.getCreatedOn()); msg.setMessage("Uploaded patch set " + ps.getPatchSetId() + "."); db.changeMessages().insert(Collections.singleton(msg), txn); result.msg = msg; if (result.mergedIntoRef != null) { // Change was already submitted to a branch, close it. // markChangeMergedByPush(db, txn, result); } else { // Change should be new, so it can go through review again. // change.setStatus(Change.Status.NEW); change.setCurrentPatchSet(imp.getPatchSetInfo()); ChangeUtil.updated(change); db.changeApprovals().update(result.approvals, txn); db.changes().update(Collections.singleton(change), txn); } final List<ApprovalType> allTypes = Common.getGerritConfig().getApprovalTypes(); if (allTypes.size() > 0) { final ApprovalCategory.Id catId = allTypes.get(allTypes.size() - 1).getCategory().getId(); if (authorId != null && haveApprovals.add(authorId)) { insertDummyChangeApproval(result, authorId, catId, db, txn); } if (committerId != null && haveApprovals.add(committerId)) { insertDummyChangeApproval(result, committerId, catId, db, txn); } for (final Account.Id reviewer : reviewerId) { if (haveApprovals.add(reviewer)) { insertDummyChangeApproval(result, reviewer, catId, db, txn); } } } return result; } }); if (result != null) { final PatchSet ps = result.patchSet; final RefUpdate ru = repo.updateRef(ps.getRefName()); ru.setForceUpdate(true); ru.setNewObjectId(c); ru.setRefLogIdent(refLogIdent); ru.setRefLogMessage("uploaded", false); if (ru.update(rp.getRevWalk()) != RefUpdate.Result.NEW) { throw new IOException("Failed to create ref " + ps.getRefName() + " in " + repo.getDirectory() + ": " + ru.getResult()); } PushQueue.scheduleUpdate(proj.getNameKey(), ru.getName()); cmd.setResult(ReceiveCommand.Result.OK); try { final ReplacePatchSetSender cm = new ReplacePatchSetSender(server, result.change); cm.setFrom(me); cm.setPatchSet(ps, result.info); cm.setChangeMessage(result.msg); cm.setReviewDb(db); cm.addReviewers(reviewerId); cm.addExtraCC(ccId); cm.addReviewers(oldReviewers); cm.addExtraCC(oldCC); cm.send(); } catch (EmailException e) { log.error("Cannot send email for new patch set " + ps.getId(), e); } } sendMergedEmail(result); }
diff --git a/historicalWeather/src/com/daemgahe/historicalWeather/DateScreen.java b/historicalWeather/src/com/daemgahe/historicalWeather/DateScreen.java index 8aac21f..88c64f1 100644 --- a/historicalWeather/src/com/daemgahe/historicalWeather/DateScreen.java +++ b/historicalWeather/src/com/daemgahe/historicalWeather/DateScreen.java @@ -1,218 +1,218 @@ package com.daemgahe.historicalWeather; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; public class DateScreen extends Activity { private String theIcao; //private Button submit; private TextView debug; //private String myURL; private DatePicker startDateField; private DatePicker endDateField; private DateFormat df; private Calendar calendar; private Date startDate; private Date endDate; private String startyear; private String startmonth; private String startday; private String endyear; private String endmonth; private String endday; private String completeURL; private String graphData; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.date); startDateField = (DatePicker) findViewById(R.id.start_date); df = new SimpleDateFormat("yyyy-MM-dd"); endDate = new Date(); calendar = Calendar.getInstance(); calendar.setTime(endDate); calendar.roll(Calendar.YEAR, -1); startDate = calendar.getTime(); String startDateValue = df.format(startDate); //startDateField.setText(startDateValue); endDateField = (DatePicker) findViewById(R.id.end_date); String endDateValue = df.format(endDate); //endDateField.setText(endDateValue); calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); startmonth = String.format("%02d", calendar.get(Calendar.MONTH)); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); endmonth = String.format("%02d", calendar.get(Calendar.MONTH)); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); startDateField.init(Integer.parseInt(startyear), Integer.parseInt(startmonth), Integer.parseInt(startday), null); endDateField.init(Integer.parseInt(endyear), Integer.parseInt(endmonth), Integer.parseInt(endday), null); // Create a bundle to get the intent parameters Bundle bundle = this.getIntent().getExtras(); theIcao = bundle.getString("icao"); debug = (TextView) findViewById(R.id.debugTextView); Button submitButton = (Button) findViewById(R.id.submitButton); // Button dataButton = (Button) findViewById(R.id.dataButton); submitButton.setOnClickListener (new View.OnClickListener() { @Override public void onClick(View v) { String startDateValue1 = String.format("%04d-%02d-%02d", startDateField.getYear(), startDateField.getMonth(), startDateField.getDayOfMonth()); String endDateValue1 = String.format("%04d-%02d-%02d", endDateField.getYear(), endDateField.getMonth(), endDateField.getDayOfMonth()); try { startDate = df.parse(startDateValue1); endDate = df.parse(endDateValue1); } catch (java.text.ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); - startmonth = String.format("%02d", calendar.get(Calendar.MONTH)); + startmonth = String.format("%02d", calendar.get(Calendar.MONTH)+2); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); - endmonth = String.format("%02d", calendar.get(Calendar.MONTH)); + endmonth = String.format("%02d", calendar.get(Calendar.MONTH)+2); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); //debug.setText(completeURL); try { getData(); //debug.setText(graphData); GoToGraphScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); /* dataButton.setOnClickListener (new View.OnClickListener() { public void onClick(View v) { //debug.setText(completeURL); try { getData(); //debug.setText(graphData); //GoToDataScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); */ } /* protected void GoToDataScreen() { Bundle bundle = new Bundle(); bundle.putString("graph", graphData); Intent dateToGraph = new Intent(this, DataScreen.class); dateToGraph.putExtras(bundle); startActivityForResult(dateToGraph,0); } */ protected void GoToGraphScreen() { Bundle bundle = new Bundle(); bundle.putString("graph", graphData); bundle.putLong("startDate", startDate.getTime()); bundle.putLong("endDate", endDate.getTime()); Intent dateToGraph = new Intent(this, GraphScreen.class); dateToGraph.putExtras(bundle); startActivityForResult(dateToGraph,0); } public void getData() throws Exception { // Prepare different parts of the URL String host = "http://www.wunderground.com/history/airport/"; String file = "CustomHistory.html?"; String urlEnd = "&req_city=NA&req_state=NA&req_statename=NA&format=1"; // Form URL completeURL = String.format("%s%s/%s/%s/%s/%sdayend=%s&monthend=%s&yearend=%s%s",host,theIcao,startyear,startmonth,startday,file,endday,endmonth,endyear,urlEnd); debug.setText(completeURL); BufferedReader in = null; try { HttpClient client = new DefaultHttpClient (); HttpGet request = new HttpGet(); request.setURI(new URI(completeURL)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); Log.v("Weather Graph", line+NL); } in.close(); graphData = new String(sb.toString()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.date); startDateField = (DatePicker) findViewById(R.id.start_date); df = new SimpleDateFormat("yyyy-MM-dd"); endDate = new Date(); calendar = Calendar.getInstance(); calendar.setTime(endDate); calendar.roll(Calendar.YEAR, -1); startDate = calendar.getTime(); String startDateValue = df.format(startDate); //startDateField.setText(startDateValue); endDateField = (DatePicker) findViewById(R.id.end_date); String endDateValue = df.format(endDate); //endDateField.setText(endDateValue); calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); startmonth = String.format("%02d", calendar.get(Calendar.MONTH)); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); endmonth = String.format("%02d", calendar.get(Calendar.MONTH)); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); startDateField.init(Integer.parseInt(startyear), Integer.parseInt(startmonth), Integer.parseInt(startday), null); endDateField.init(Integer.parseInt(endyear), Integer.parseInt(endmonth), Integer.parseInt(endday), null); // Create a bundle to get the intent parameters Bundle bundle = this.getIntent().getExtras(); theIcao = bundle.getString("icao"); debug = (TextView) findViewById(R.id.debugTextView); Button submitButton = (Button) findViewById(R.id.submitButton); // Button dataButton = (Button) findViewById(R.id.dataButton); submitButton.setOnClickListener (new View.OnClickListener() { @Override public void onClick(View v) { String startDateValue1 = String.format("%04d-%02d-%02d", startDateField.getYear(), startDateField.getMonth(), startDateField.getDayOfMonth()); String endDateValue1 = String.format("%04d-%02d-%02d", endDateField.getYear(), endDateField.getMonth(), endDateField.getDayOfMonth()); try { startDate = df.parse(startDateValue1); endDate = df.parse(endDateValue1); } catch (java.text.ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); startmonth = String.format("%02d", calendar.get(Calendar.MONTH)); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); endmonth = String.format("%02d", calendar.get(Calendar.MONTH)); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); //debug.setText(completeURL); try { getData(); //debug.setText(graphData); GoToGraphScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); /* dataButton.setOnClickListener (new View.OnClickListener() { public void onClick(View v) { //debug.setText(completeURL); try { getData(); //debug.setText(graphData); //GoToDataScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); */ }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.date); startDateField = (DatePicker) findViewById(R.id.start_date); df = new SimpleDateFormat("yyyy-MM-dd"); endDate = new Date(); calendar = Calendar.getInstance(); calendar.setTime(endDate); calendar.roll(Calendar.YEAR, -1); startDate = calendar.getTime(); String startDateValue = df.format(startDate); //startDateField.setText(startDateValue); endDateField = (DatePicker) findViewById(R.id.end_date); String endDateValue = df.format(endDate); //endDateField.setText(endDateValue); calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); startmonth = String.format("%02d", calendar.get(Calendar.MONTH)); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); endmonth = String.format("%02d", calendar.get(Calendar.MONTH)); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); startDateField.init(Integer.parseInt(startyear), Integer.parseInt(startmonth), Integer.parseInt(startday), null); endDateField.init(Integer.parseInt(endyear), Integer.parseInt(endmonth), Integer.parseInt(endday), null); // Create a bundle to get the intent parameters Bundle bundle = this.getIntent().getExtras(); theIcao = bundle.getString("icao"); debug = (TextView) findViewById(R.id.debugTextView); Button submitButton = (Button) findViewById(R.id.submitButton); // Button dataButton = (Button) findViewById(R.id.dataButton); submitButton.setOnClickListener (new View.OnClickListener() { @Override public void onClick(View v) { String startDateValue1 = String.format("%04d-%02d-%02d", startDateField.getYear(), startDateField.getMonth(), startDateField.getDayOfMonth()); String endDateValue1 = String.format("%04d-%02d-%02d", endDateField.getYear(), endDateField.getMonth(), endDateField.getDayOfMonth()); try { startDate = df.parse(startDateValue1); endDate = df.parse(endDateValue1); } catch (java.text.ParseException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return; } calendar.setTime(startDate); startyear = String.format("%04d", calendar.get(Calendar.YEAR)); startmonth = String.format("%02d", calendar.get(Calendar.MONTH)+2); startday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); calendar.setTime(endDate); endyear = String.format("%04d", calendar.get(Calendar.YEAR)); endmonth = String.format("%02d", calendar.get(Calendar.MONTH)+2); endday = String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)); //debug.setText(completeURL); try { getData(); //debug.setText(graphData); GoToGraphScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); /* dataButton.setOnClickListener (new View.OnClickListener() { public void onClick(View v) { //debug.setText(completeURL); try { getData(); //debug.setText(graphData); //GoToDataScreen(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); */ }
diff --git a/src/com/alecgorge/minecraft/jsonapi/dynamic/Argument.java b/src/com/alecgorge/minecraft/jsonapi/dynamic/Argument.java index e411bf9..a391989 100644 --- a/src/com/alecgorge/minecraft/jsonapi/dynamic/Argument.java +++ b/src/com/alecgorge/minecraft/jsonapi/dynamic/Argument.java @@ -1,95 +1,93 @@ package com.alecgorge.minecraft.jsonapi.dynamic; import java.util.HashMap; import org.json.simpleForBukkit.JSONArray; public class Argument { private Class<?> type; private String desc; private Object value = null; private static HashMap<String, Class<?>> mapping = new HashMap<String, Class<?>>(); static { mapping.put("int", int.class); mapping.put("String[]", String[].class); mapping.put("double", double.class); mapping.put("boolean", boolean.class); mapping.put("float", float.class); mapping.put("String", String.class); mapping.put("Integer", Integer.class); mapping.put("Float", Float.class); mapping.put("Double", Double.class); mapping.put("Boolean", Boolean.class); mapping.put("Player", org.bukkit.entity.Player.class); mapping.put("Server", org.bukkit.Server.class); mapping.put("World", org.bukkit.World.class); mapping.put("World[]", org.bukkit.World[].class); mapping.put("Player[]", org.bukkit.entity.Player[].class); mapping.put("Plugin", org.bukkit.plugin.Plugin.class); mapping.put("Plugin[]", org.bukkit.plugin.Plugin[].class); mapping.put("OfflinePlayer", org.bukkit.OfflinePlayer.class); mapping.put("OfflinePlayer[]", org.bukkit.OfflinePlayer[].class); mapping.put("Object[]", Object[].class); } public Argument(JSONArray a) { type = getClassFromName((String)a.get(0)); desc = (String)a.get(1); } public Argument(Class<?> a, String desc) { type = a; this.desc = desc; } public Class<?> getType() { return type; } public void setValue (Object o) { value = o; } public Object getValue () { return value; } public String getDesc () { return desc; } public static Class<?> getClassFromName(String name) { // auto translate from some of the defaults Class<?> ret = mapping.get(name); if(ret != null) { return ret; } ret = void.class; try { ret = Class.forName(name); } catch (ClassNotFoundException e) { try { ret = Class.forName("java.lang."+name); } catch (ClassNotFoundException e1) { try { ret = Class.forName("org.bukkit."+name); } catch (Exception e2) { try { ret = Class.forName("org.bukkit.entity."+name); } catch (Exception e3) { try { ret = Class.forName("net.milkbowl.vault.economy."+name); } catch (ClassNotFoundException e4) { - // TODO Auto-generated catch block - e4.printStackTrace(); } } } } } return ret; } }
true
true
public static Class<?> getClassFromName(String name) { // auto translate from some of the defaults Class<?> ret = mapping.get(name); if(ret != null) { return ret; } ret = void.class; try { ret = Class.forName(name); } catch (ClassNotFoundException e) { try { ret = Class.forName("java.lang."+name); } catch (ClassNotFoundException e1) { try { ret = Class.forName("org.bukkit."+name); } catch (Exception e2) { try { ret = Class.forName("org.bukkit.entity."+name); } catch (Exception e3) { try { ret = Class.forName("net.milkbowl.vault.economy."+name); } catch (ClassNotFoundException e4) { // TODO Auto-generated catch block e4.printStackTrace(); } } } } } return ret; }
public static Class<?> getClassFromName(String name) { // auto translate from some of the defaults Class<?> ret = mapping.get(name); if(ret != null) { return ret; } ret = void.class; try { ret = Class.forName(name); } catch (ClassNotFoundException e) { try { ret = Class.forName("java.lang."+name); } catch (ClassNotFoundException e1) { try { ret = Class.forName("org.bukkit."+name); } catch (Exception e2) { try { ret = Class.forName("org.bukkit.entity."+name); } catch (Exception e3) { try { ret = Class.forName("net.milkbowl.vault.economy."+name); } catch (ClassNotFoundException e4) { } } } } } return ret; }
diff --git a/projects/framework/java/test-contract/src/main/java/org/identityconnectors/contract/test/AuthenticationApiOpTests.java b/projects/framework/java/test-contract/src/main/java/org/identityconnectors/contract/test/AuthenticationApiOpTests.java index 822b034d..63ff9b34 100644 --- a/projects/framework/java/test-contract/src/main/java/org/identityconnectors/contract/test/AuthenticationApiOpTests.java +++ b/projects/framework/java/test-contract/src/main/java/org/identityconnectors/contract/test/AuthenticationApiOpTests.java @@ -1,619 +1,619 @@ /* * ==================== * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008-2009 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Common Development * and Distribution License("CDDL") (the "License"). You may not use this file * except in compliance with the License. * * You can obtain a copy of the License at * http://IdentityConnectors.dev.java.net/legal/license.txt * See the License for the specific language governing permissions and limitations * under the License. * * When distributing the Covered Code, include this CDDL Header Notice in each file * and include the License file at identityconnectors/legal/license.txt. * If applicable, add the following below this CDDL Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * "Portions Copyrighted [year] [name of copyright owner]" * ==================== */ package org.identityconnectors.contract.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.identityconnectors.common.logging.Log; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.contract.exceptions.ObjectNotFoundException; import org.identityconnectors.framework.api.operations.APIOperation; import org.identityconnectors.framework.api.operations.AuthenticationApiOp; import org.identityconnectors.framework.api.operations.CreateApiOp; import org.identityconnectors.framework.api.operations.DeleteApiOp; import org.identityconnectors.framework.api.operations.GetApiOp; import org.identityconnectors.framework.api.operations.UpdateApiOp; import org.identityconnectors.framework.common.exceptions.InvalidCredentialException; import org.identityconnectors.framework.common.exceptions.PasswordExpiredException; import org.identityconnectors.framework.common.objects.Attribute; import org.identityconnectors.framework.common.objects.AttributeBuilder; import org.identityconnectors.framework.common.objects.AttributeInfo; import org.identityconnectors.framework.common.objects.ConnectorObject; import org.identityconnectors.framework.common.objects.ObjectClass; import org.identityconnectors.framework.common.objects.ObjectClassInfo; import org.identityconnectors.framework.common.objects.OperationOptionsBuilder; import org.identityconnectors.framework.common.objects.OperationalAttributes; import org.identityconnectors.framework.common.objects.PredefinedAttributes; import org.identityconnectors.framework.common.objects.Uid; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; /** * Contract test of {@link AuthenticationApiOp} */ @RunWith(Parameterized.class) public class AuthenticationApiOpTests extends ObjectClassRunner { /** * Logging.. */ private static final Log LOG = Log.getLog(AuthenticationApiOpTests.class); static final String TEST_NAME = "Authentication"; static final String USERNAME_PROP = "username"; private static final String WRONG_PASSWORD_PROP = "wrong.password"; private static final String MAX_ITERATIONS = "maxIterations"; private static final String SLEEP_MILLISECONDS = "sleepMilliseconds"; public AuthenticationApiOpTests(ObjectClass oclass) { super(oclass); } /** * {@inheritDoc} */ @Override public Set<Class<? extends APIOperation>> getAPIOperations() { Set<Class<? extends APIOperation>> requiredOps = new HashSet<Class<? extends APIOperation>>(); // list of required operations by this test: requiredOps.add(CreateApiOp.class); requiredOps.add(AuthenticationApiOp.class); requiredOps.add(GetApiOp.class); return requiredOps; } /** * {@inheritDoc} */ @Override public void testRun() { Uid uid = null; try { // create a user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.PASSWORD_EXPIRED_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get the user to make sure it exists now ConnectorObject obj = getConnectorFacade().getObject(getObjectClass(), uid, getOperationOptionsByOp(GetApiOp.class)); assertNotNull("Unable to retrieve newly created object", obj); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); // test negative case with valid user, but wrong password boolean authenticateFailed = false; // get wrong password GuardedString wrongPassword = (GuardedString) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + WRONG_PASSWORD_PROP, TEST_NAME); authenticateFailed = authenticateExpectingInvalidCredentials(name, wrongPassword); assertTrue("Negative test case for Authentication failed, should throw InvalidCredentialException", authenticateFailed); // now try with the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClass().getObjectClassValue(), 0, false); Uid authenticatedUid = authenticateExpectingSuccess(name, password); String MSG = "Authenticate returned wrong Uid, expected: %s, returned: %s."; assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // test that PASSWORD change works, CURRENT_PASSWORD should be set // to old password value if supported if (isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_NAME)) { GuardedString newpassword = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, UpdateApiOpTests.MODIFIED, getObjectClass().getObjectClassValue(), 0, false); Set<Attribute> replaceAttrs = new HashSet<Attribute>(); replaceAttrs.add(AttributeBuilder.buildPassword(newpassword)); if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), OperationalAttributes.CURRENT_PASSWORD_NAME)) { // CURRENT_PASSWORD must be set to old password replaceAttrs.add(AttributeBuilder.buildCurrentPassword(password)); } // update to new password uid = getConnectorFacade().update(getObjectClass(), uid, replaceAttrs, getOperationOptionsByOp(UpdateApiOp.class)); // authenticate with new password authenticatedUid = authenticateExpectingSuccess(name, newpassword); assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // LAST_PASSWORD_CHANGE_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)) { LOG.info("LAST_PASSWORD_CHANGE_DATE test."); // LAST_PASSWORD_CHANGE_DATE must be readable, we suppose it is // add LAST_PASSWORD_CHANGE_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); - builder.setAttributesToGet(PredefinedAttributes.LAST_LOGIN_DATE_NAME); + builder.setAttributesToGet(PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME); ConnectorObject lastPasswordChange = getConnectorFacade().getObject( getObjectClass(), uid, builder.build()); // check that LAST_PASSWORD_CHANGE_DATE was set to a value assertNotNull("LAST_PASSWORD_CHANGE_DATE attribute is null.", lastPasswordChange.getAttributeByName(PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)); } else { LOG.info("Skipping LAST_PASSWORD_CHANGE_DATE test."); } } // LAST_LOGIN_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_LOGIN_DATE_NAME)) { LOG.info("LAST_LOGIN_DATE test."); // LAST_LOGIN_DATE must be readable, we suppose it is // add LAST_LOGIN_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet(PredefinedAttributes.LAST_LOGIN_DATE_NAME); ConnectorObject lastLogin = getConnectorFacade().getObject(getObjectClass(), uid, builder.build()); // check that LAST_LOGIN_DATE was set to some value assertNotNull("LAST_LOGIN_DATE attribute is null.", lastLogin.getAttributeByName(PredefinedAttributes.LAST_LOGIN_DATE_NAME)); } else { LOG.info("Skipping LAST_LOGIN_DATE test."); } } finally { if (uid != null) { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } } /** * Tests that disabled user cannot authenticate. * RuntimeException should be thrown. */ @Test public void testOpEnable() { // now try to set the password to be expired and authenticate again // it's possible only in case Update and PASSWORD_EXPIRED are supported if (ConnectorHelper.operationsSupported(getConnectorFacade(), getObjectClass(), getAPIOperations()) && isOperationalAttributeUpdateable(OperationalAttributes.ENABLE_NAME)) { Uid uid = null; try { // create an user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.PASSWORD_EXPIRED_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); Set<Attribute> updateAttrs = new HashSet<Attribute>(); updateAttrs.add(AttributeBuilder.buildEnabled(false)); Uid newUid = getConnectorFacade().update(getObjectClass(), uid, updateAttrs, null); if (!uid.equals(newUid) && newUid != null) { uid = newUid; } // get the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClassInfo().getType(), 0, false); // and now authenticate assertTrue("Authenticate must throw for disabled account", authenticateExpectingRuntimeException(name, password)); } finally { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } else { LOG.info("Skipping testOpEnable test."); } } /** * Tests that PasswordExpiredException is thrown in case PasswordExpirationDate is set to today. */ @Test public void testOpPasswordExpirationDate() { // now try to set the password to be expired and authenticate again // it's possible only in case Update and PASSWORD_EXPIRED if (ConnectorHelper.operationsSupported(getConnectorFacade(), getObjectClass(), getAPIOperations()) && isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME)) { Uid uid = null; try { // create an user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.ENABLE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRED_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); Set<Attribute> updateAttrs = new HashSet<Attribute>(); updateAttrs.add(AttributeBuilder.buildPasswordExpirationDate(new Date())); Uid newUid = getConnectorFacade().update(getObjectClass(), uid, updateAttrs, null); if (!uid.equals(newUid) && newUid != null) { uid = newUid; } // get the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClassInfo().getType(), 0, false); // and now authenticate PasswordExpiredException pwe = authenticateExpectingPasswordExpired(name, password); assertNotNull("Authenticate should throw PasswordExpiredException.", pwe); final String MSG = "PasswordExpiredException contains wrong Uid, expected: %s, returned: %s"; assertEquals(String.format(MSG, uid, pwe.getUid()), uid, pwe.getUid()); } finally { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } else { LOG.info("Skipping testOpPasswordExpirationDate test."); } } /** * Tests that PasswordExpiredException is thrown in case PasswordExpired is updated to true. */ @Test public void testOpPasswordExpired() { // now try to set the password to be expired and authenticate again // it's possible only in case Update and PASSWORD_EXPIRED if (ConnectorHelper.operationsSupported(getConnectorFacade(), getObjectClass(), getAPIOperations()) && isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_EXPIRED_NAME)) { Uid uid = null; try { // create an user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.ENABLE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); Set<Attribute> updateAttrs = new HashSet<Attribute>(); updateAttrs.add(AttributeBuilder.buildPasswordExpired(true)); Uid newUid = getConnectorFacade().update(getObjectClass(), uid, updateAttrs, null); if (!uid.equals(newUid) && newUid != null) { uid = newUid; } // get the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClassInfo().getType(), 0, false); // and now authenticate PasswordExpiredException pwe = authenticateExpectingPasswordExpired(name, password); assertNotNull("Authenticate should throw PasswordExpiredException.", pwe); final String MSG = "PasswordExpiredException contains wrong Uid, expected: %s, returned: %s"; assertEquals(String.format(MSG, uid, pwe.getUid()), uid, pwe.getUid()); } finally { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } else { LOG.info("Skipping testOpPasswordExpired test."); } } /** * Tests that connector respects order of PASSWORD and PASSWORD_EXPIRED * attributes during update. PASSWORD should be performed before * PASSWORD_EXPIRED. */ @Test public void testPasswordBeforePasswordExpired() { // run test only in case operation is supported and both PASSWORD and PASSWORD_EXPIRED are supported if (ConnectorHelper.operationsSupported(getConnectorFacade(), getObjectClass(), getAPIOperations()) && isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_NAME) && isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_EXPIRED_NAME)) { Uid uid = null; try { // create an user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.ENABLE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); // get new password GuardedString newpassword = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, UpdateApiOpTests.MODIFIED, getObjectClassInfo().getType(), 0, false); // change password and expire password Set<Attribute> replaceAttrs = new HashSet<Attribute>(); replaceAttrs.add(AttributeBuilder.buildPassword(newpassword)); replaceAttrs.add(AttributeBuilder.buildPasswordExpired(true)); if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), OperationalAttributes.CURRENT_PASSWORD_NAME)) { // get old password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClassInfo().getType(), 0, false); // CURRENT_PASSWORD must be set to old password replaceAttrs.add(AttributeBuilder.buildCurrentPassword(password)); } // update to new password and expire password uid = getConnectorFacade().update(getObjectClass(), uid, replaceAttrs, getOperationOptionsByOp(UpdateApiOp.class)); PasswordExpiredException pwe = authenticateExpectingPasswordExpired(name, newpassword); assertNotNull("Authenticate should throw PasswordExpiredException.", pwe); } finally { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } else { LOG.info("Skipping test ''testPasswordBeforePasswordExpired'' for object class {0}", getObjectClass()); } } /** * Returns true if operational attribute is supported and updateable. */ private boolean isOperationalAttributeUpdateable(String name) { ObjectClassInfo oinfo = getObjectClassInfo(); for (AttributeInfo ainfo : oinfo.getAttributeInfo()) { if (ainfo.is(name)) { return ainfo.isUpdateable(); } } return false; } /** * {@inheritDoc} */ @Override public String getTestName() { return TEST_NAME; } private long getLongTestParam(String name, long defaultValue) { long longValue = defaultValue; try { Object valueObject = getDataProvider().getTestSuiteAttribute(name, TEST_NAME); if(valueObject != null) { longValue = Long.parseLong(valueObject.toString()); } } catch (ObjectNotFoundException ex) { } return longValue; } private void sleepIngoringInterruption(long sleepTime) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { } } private boolean authenticateExpectingRuntimeException(String name, GuardedString password) { boolean authenticateFailed = false; for(int i=0;i<getLongTestParam(MAX_ITERATIONS, 1);i++) { try { getConnectorFacade().authenticate(ObjectClass.ACCOUNT, name,password, getOperationOptionsByOp(AuthenticationApiOp.class)); } catch (RuntimeException e) { // it failed as it should have authenticateFailed = true; break; } LOG.info(String.format("Retrying authentication - iteration %d", i)); sleepIngoringInterruption(getLongTestParam(SLEEP_MILLISECONDS, 0)); } return authenticateFailed; } private boolean authenticateExpectingInvalidCredentials(String name, GuardedString password) { boolean authenticateFailed = false; for(int i=0;i<getLongTestParam(MAX_ITERATIONS, 1);i++) { try { getConnectorFacade().authenticate(ObjectClass.ACCOUNT, name, password, getOperationOptionsByOp(AuthenticationApiOp.class)); } catch (InvalidCredentialException e) { // it failed as it should have authenticateFailed = true; break; } LOG.info(String.format("Retrying authentication - iteration %d", i)); sleepIngoringInterruption(getLongTestParam(SLEEP_MILLISECONDS, 0)); } return authenticateFailed; } private Uid authenticateExpectingSuccess(String name, GuardedString password) { Uid authenticatedUid = null; RuntimeException lastException = null; for(int i=0;i<getLongTestParam(MAX_ITERATIONS, 1);i++) { try { authenticatedUid = getConnectorFacade().authenticate(ObjectClass.ACCOUNT, name,password, getOperationOptionsByOp(AuthenticationApiOp.class)); lastException = null; break; } catch (RuntimeException e) { lastException = e; LOG.info(String.format("Retrying authentication - iteration %d", i)); sleepIngoringInterruption(getLongTestParam(SLEEP_MILLISECONDS, 0)); } } if(lastException != null) { throw lastException; } return authenticatedUid; } private PasswordExpiredException authenticateExpectingPasswordExpired(String name, GuardedString password) { PasswordExpiredException passwordExpiredException = null; RuntimeException lastException = null; for(int i=0;i<getLongTestParam(MAX_ITERATIONS, 1);i++) { try { getConnectorFacade().authenticate(ObjectClass.ACCOUNT, name,password, getOperationOptionsByOp(AuthenticationApiOp.class)); } catch (PasswordExpiredException e) { // it failed as it should have passwordExpiredException = e; lastException = null; break; } catch (RuntimeException e) { lastException = e; } LOG.info(String.format("Retrying authentication - iteration %d", i)); sleepIngoringInterruption(getLongTestParam(SLEEP_MILLISECONDS, 0)); } if(lastException != null) { throw lastException; } return passwordExpiredException; } }
true
true
public void testRun() { Uid uid = null; try { // create a user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.PASSWORD_EXPIRED_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get the user to make sure it exists now ConnectorObject obj = getConnectorFacade().getObject(getObjectClass(), uid, getOperationOptionsByOp(GetApiOp.class)); assertNotNull("Unable to retrieve newly created object", obj); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); // test negative case with valid user, but wrong password boolean authenticateFailed = false; // get wrong password GuardedString wrongPassword = (GuardedString) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + WRONG_PASSWORD_PROP, TEST_NAME); authenticateFailed = authenticateExpectingInvalidCredentials(name, wrongPassword); assertTrue("Negative test case for Authentication failed, should throw InvalidCredentialException", authenticateFailed); // now try with the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClass().getObjectClassValue(), 0, false); Uid authenticatedUid = authenticateExpectingSuccess(name, password); String MSG = "Authenticate returned wrong Uid, expected: %s, returned: %s."; assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // test that PASSWORD change works, CURRENT_PASSWORD should be set // to old password value if supported if (isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_NAME)) { GuardedString newpassword = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, UpdateApiOpTests.MODIFIED, getObjectClass().getObjectClassValue(), 0, false); Set<Attribute> replaceAttrs = new HashSet<Attribute>(); replaceAttrs.add(AttributeBuilder.buildPassword(newpassword)); if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), OperationalAttributes.CURRENT_PASSWORD_NAME)) { // CURRENT_PASSWORD must be set to old password replaceAttrs.add(AttributeBuilder.buildCurrentPassword(password)); } // update to new password uid = getConnectorFacade().update(getObjectClass(), uid, replaceAttrs, getOperationOptionsByOp(UpdateApiOp.class)); // authenticate with new password authenticatedUid = authenticateExpectingSuccess(name, newpassword); assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // LAST_PASSWORD_CHANGE_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)) { LOG.info("LAST_PASSWORD_CHANGE_DATE test."); // LAST_PASSWORD_CHANGE_DATE must be readable, we suppose it is // add LAST_PASSWORD_CHANGE_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet(PredefinedAttributes.LAST_LOGIN_DATE_NAME); ConnectorObject lastPasswordChange = getConnectorFacade().getObject( getObjectClass(), uid, builder.build()); // check that LAST_PASSWORD_CHANGE_DATE was set to a value assertNotNull("LAST_PASSWORD_CHANGE_DATE attribute is null.", lastPasswordChange.getAttributeByName(PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)); } else { LOG.info("Skipping LAST_PASSWORD_CHANGE_DATE test."); } } // LAST_LOGIN_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_LOGIN_DATE_NAME)) { LOG.info("LAST_LOGIN_DATE test."); // LAST_LOGIN_DATE must be readable, we suppose it is // add LAST_LOGIN_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet(PredefinedAttributes.LAST_LOGIN_DATE_NAME); ConnectorObject lastLogin = getConnectorFacade().getObject(getObjectClass(), uid, builder.build()); // check that LAST_LOGIN_DATE was set to some value assertNotNull("LAST_LOGIN_DATE attribute is null.", lastLogin.getAttributeByName(PredefinedAttributes.LAST_LOGIN_DATE_NAME)); } else { LOG.info("Skipping LAST_LOGIN_DATE test."); } } finally { if (uid != null) { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } }
public void testRun() { Uid uid = null; try { // create a user Set<Attribute> attrs = ConnectorHelper.getCreateableAttributes(getDataProvider(), getObjectClassInfo(), getTestName(), 0, true, false); // Remove enabled and password_expired, connector must create valid account then for (Iterator<Attribute> i = attrs.iterator(); i.hasNext();) { Attribute attr = i.next(); if (attr.is(OperationalAttributes.PASSWORD_EXPIRED_NAME) || attr.is(OperationalAttributes.PASSWORD_EXPIRATION_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_DATE_NAME) || attr.is(OperationalAttributes.ENABLE_NAME)) { if (!ConnectorHelper.isRequired(getObjectClassInfo(), attr)) { i.remove(); } } } uid = getConnectorFacade().create(getObjectClass(), attrs, getOperationOptionsByOp(CreateApiOp.class)); // get the user to make sure it exists now ConnectorObject obj = getConnectorFacade().getObject(getObjectClass(), uid, getOperationOptionsByOp(GetApiOp.class)); assertNotNull("Unable to retrieve newly created object", obj); // get username String name = (String) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + USERNAME_PROP, TEST_NAME); // test negative case with valid user, but wrong password boolean authenticateFailed = false; // get wrong password GuardedString wrongPassword = (GuardedString) getDataProvider().getTestSuiteAttribute(getObjectClass().getObjectClassValue() + "." + WRONG_PASSWORD_PROP, TEST_NAME); authenticateFailed = authenticateExpectingInvalidCredentials(name, wrongPassword); assertTrue("Negative test case for Authentication failed, should throw InvalidCredentialException", authenticateFailed); // now try with the right password GuardedString password = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, getObjectClass().getObjectClassValue(), 0, false); Uid authenticatedUid = authenticateExpectingSuccess(name, password); String MSG = "Authenticate returned wrong Uid, expected: %s, returned: %s."; assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // test that PASSWORD change works, CURRENT_PASSWORD should be set // to old password value if supported if (isOperationalAttributeUpdateable(OperationalAttributes.PASSWORD_NAME)) { GuardedString newpassword = (GuardedString) ConnectorHelper.get(getDataProvider(), getTestName(), GuardedString.class, OperationalAttributes.PASSWORD_NAME, UpdateApiOpTests.MODIFIED, getObjectClass().getObjectClassValue(), 0, false); Set<Attribute> replaceAttrs = new HashSet<Attribute>(); replaceAttrs.add(AttributeBuilder.buildPassword(newpassword)); if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), OperationalAttributes.CURRENT_PASSWORD_NAME)) { // CURRENT_PASSWORD must be set to old password replaceAttrs.add(AttributeBuilder.buildCurrentPassword(password)); } // update to new password uid = getConnectorFacade().update(getObjectClass(), uid, replaceAttrs, getOperationOptionsByOp(UpdateApiOp.class)); // authenticate with new password authenticatedUid = authenticateExpectingSuccess(name, newpassword); assertEquals(String.format(MSG, uid, authenticatedUid), uid, authenticatedUid); // LAST_PASSWORD_CHANGE_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)) { LOG.info("LAST_PASSWORD_CHANGE_DATE test."); // LAST_PASSWORD_CHANGE_DATE must be readable, we suppose it is // add LAST_PASSWORD_CHANGE_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet(PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME); ConnectorObject lastPasswordChange = getConnectorFacade().getObject( getObjectClass(), uid, builder.build()); // check that LAST_PASSWORD_CHANGE_DATE was set to a value assertNotNull("LAST_PASSWORD_CHANGE_DATE attribute is null.", lastPasswordChange.getAttributeByName(PredefinedAttributes.LAST_PASSWORD_CHANGE_DATE_NAME)); } else { LOG.info("Skipping LAST_PASSWORD_CHANGE_DATE test."); } } // LAST_LOGIN_DATE if (ConnectorHelper.isAttrSupported(getObjectClassInfo(), PredefinedAttributes.LAST_LOGIN_DATE_NAME)) { LOG.info("LAST_LOGIN_DATE test."); // LAST_LOGIN_DATE must be readable, we suppose it is // add LAST_LOGIN_DATE to ATTRS_TO_GET OperationOptionsBuilder builder = new OperationOptionsBuilder(); builder.setAttributesToGet(PredefinedAttributes.LAST_LOGIN_DATE_NAME); ConnectorObject lastLogin = getConnectorFacade().getObject(getObjectClass(), uid, builder.build()); // check that LAST_LOGIN_DATE was set to some value assertNotNull("LAST_LOGIN_DATE attribute is null.", lastLogin.getAttributeByName(PredefinedAttributes.LAST_LOGIN_DATE_NAME)); } else { LOG.info("Skipping LAST_LOGIN_DATE test."); } } finally { if (uid != null) { // delete the object ConnectorHelper.deleteObject(getConnectorFacade(), getSupportedObjectClass(), uid, false, getOperationOptionsByOp(DeleteApiOp.class)); } } }
diff --git a/src/protocol/cdc_application/classes/com/sun/midp/io/j2me/socket/Protocol.java b/src/protocol/cdc_application/classes/com/sun/midp/io/j2me/socket/Protocol.java index 52f3eff0..c2728cd8 100644 --- a/src/protocol/cdc_application/classes/com/sun/midp/io/j2me/socket/Protocol.java +++ b/src/protocol/cdc_application/classes/com/sun/midp/io/j2me/socket/Protocol.java @@ -1,135 +1,150 @@ /* * * * Copyright 1990-2007 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License version * 2 only, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License version 2 for more details (a copy is * included at /legal/license.txt). * * You should have received a copy of the GNU General Public License * version 2 along with this work; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa * Clara, CA 95054 or visit www.sun.com if you need additional * information or have any questions. */ package com.sun.midp.io.j2me.socket; import java.io.*; import java.net.*; import javax.microedition.io.*; import com.sun.j2me.security.AccessController; public class Protocol extends com.sun.cdc.io.j2me.socket.Protocol { public static final String CLIENT_PERMISSION_NAME = "javax.microedition.io.Connector.socket"; private static final String SERVER_PERMISSION_NAME = "javax.microedition.io.Connector.serversocket"; /** Number of input streams that were opened. */ protected int iStreams = 0; /** * Maximum number of open input streams. Set this * to zero to prevent openInputStream from giving out a stream in * write-only mode. */ protected int maxIStreams = 1; /* * Open the input stream if it has not already been opened. * @exception IOException is thrown if it has already been * opened. */ public InputStream openInputStream() throws IOException { if (maxIStreams == 0) { throw new IOException("no more input streams available"); } InputStream i = super.openInputStream(); maxIStreams--; iStreams++; return i; } public DataInputStream openDataInputStream() throws IOException { return new DataInputStream(openInputStream()); } /* * This class overrides the setSocketOption() to allow 0 as a valid * value for sendBufferSize and receiveBufferSize. * The underlying CDC networking layer considers 0 as illegal * value and throws IAE which causes the TCK test to fail. */ public void setSocketOption(byte option, int value) throws IllegalArgumentException, IOException { if (option == SocketConnection.SNDBUF || option == SocketConnection.RCVBUF) { if (value == 0) { value = 1; super.setSocketOption(option, value); } } super.setSocketOption(option, value); } /** * Check to see if the application has permission to use * the given resource. * * @param host the name of the host to contact. If the * empty string, this is a request for a * serversocket. * * @param port the port number to use. * * @exception SecurityException if the MIDP permission * check fails. */ protected void checkPermission(String host, int port) throws SecurityException { if (port < 0) { throw new IllegalArgumentException("bad port: " + port); } + try { + AccessController.checkPermission(AccessController.TRUSTED_APP_PERMISSION_NAME); + } catch (SecurityException exc) { + /* + * JTWI security check, untrusted MIDlets cannot open port 80 or + * 8080 or 443. This is so they cannot perform HTTP and HTTPS + * requests on server without using the system code. The + * system HTTP code will add a "UNTRUSTED/1.0" to the user agent + * field for untrusted MIDlets. + */ + if (port == 80 || port == 8080 || port == 443) { + throw new SecurityException( + "Target port denied to untrusted applications"); + } + } if ("".equals(host)) { AccessController.checkPermission(SERVER_PERMISSION_NAME, "TCP Server" + port); } else { AccessController.checkPermission(CLIENT_PERMISSION_NAME, "TCP" + ":" + host + ":" + port); } return; } /* * For MIDP version of the protocol handler, only a single * check on open is required. */ protected void outputStreamPermissionCheck() { return; } /* * For MIDP version of the protocol handler, only a single * check on open is required. */ protected void inputStreamPermissionCheck() { return; } }
true
true
protected void checkPermission(String host, int port) throws SecurityException { if (port < 0) { throw new IllegalArgumentException("bad port: " + port); } if ("".equals(host)) { AccessController.checkPermission(SERVER_PERMISSION_NAME, "TCP Server" + port); } else { AccessController.checkPermission(CLIENT_PERMISSION_NAME, "TCP" + ":" + host + ":" + port); } return; }
protected void checkPermission(String host, int port) throws SecurityException { if (port < 0) { throw new IllegalArgumentException("bad port: " + port); } try { AccessController.checkPermission(AccessController.TRUSTED_APP_PERMISSION_NAME); } catch (SecurityException exc) { /* * JTWI security check, untrusted MIDlets cannot open port 80 or * 8080 or 443. This is so they cannot perform HTTP and HTTPS * requests on server without using the system code. The * system HTTP code will add a "UNTRUSTED/1.0" to the user agent * field for untrusted MIDlets. */ if (port == 80 || port == 8080 || port == 443) { throw new SecurityException( "Target port denied to untrusted applications"); } } if ("".equals(host)) { AccessController.checkPermission(SERVER_PERMISSION_NAME, "TCP Server" + port); } else { AccessController.checkPermission(CLIENT_PERMISSION_NAME, "TCP" + ":" + host + ":" + port); } return; }
diff --git a/src/core/org/apache/hadoop/http/HttpServer.java b/src/core/org/apache/hadoop/http/HttpServer.java index 47d05001e..4fc44c1e0 100644 --- a/src/core/org/apache/hadoop/http/HttpServer.java +++ b/src/core/org/apache/hadoop/http/HttpServer.java @@ -1,545 +1,544 @@ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.http; import java.io.IOException; import java.io.PrintWriter; import java.net.BindException; import java.net.InetSocketAddress; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.nio.channels.ServerSocketChannel; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.log.LogLevel; import org.apache.hadoop.util.ReflectionUtils; import org.mortbay.jetty.Connector; import org.mortbay.jetty.Handler; import org.mortbay.jetty.Server; import org.mortbay.jetty.handler.ContextHandlerCollection; import org.mortbay.jetty.nio.SelectChannelConnector; import org.mortbay.jetty.security.SslSocketConnector; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.DefaultServlet; import org.mortbay.jetty.servlet.FilterHolder; import org.mortbay.jetty.servlet.FilterMapping; import org.mortbay.jetty.servlet.ServletHandler; import org.mortbay.jetty.servlet.ServletHolder; import org.mortbay.jetty.webapp.WebAppContext; import org.mortbay.thread.QueuedThreadPool; import org.mortbay.util.MultiException; /** * Create a Jetty embedded server to answer http requests. The primary goal * is to serve up status information for the server. * There are three contexts: * "/logs/" -> points to the log directory * "/static/" -> points to common static files (src/webapps/static) * "/" -> the jsp server code from (src/webapps/<name>) */ public class HttpServer implements FilterContainer { public static final Log LOG = LogFactory.getLog(HttpServer.class); static final String FILTER_INITIALIZER_PROPERTY = "hadoop.http.filter.initializers"; protected final Server webServer; protected final Connector listener; protected final WebAppContext webAppContext; protected final boolean findPort; protected final Map<Context, Boolean> defaultContexts = new HashMap<Context, Boolean>(); protected final List<String> filterNames = new ArrayList<String>(); private static final int MAX_RETRIES = 10; /** Same as this(name, bindAddress, port, findPort, null); */ public HttpServer(String name, String bindAddress, int port, boolean findPort ) throws IOException { this(name, bindAddress, port, findPort, new Configuration()); } /** * Create a status server on the given port. * The jsp scripts are taken from src/webapps/<name>. * @param name The name of the server * @param port The port to use on the server * @param findPort whether the server should start at the given port and * increment by 1 until it finds a free port. * @param conf Configuration */ public HttpServer(String name, String bindAddress, int port, boolean findPort, Configuration conf) throws IOException { webServer = new Server(); this.findPort = findPort; listener = createBaseListener(conf); listener.setHost(bindAddress); listener.setPort(port); webServer.addConnector(listener); webServer.setThreadPool(new QueuedThreadPool()); final String appDir = getWebAppsPath(); ContextHandlerCollection contexts = new ContextHandlerCollection(); webServer.setHandler(contexts); webAppContext = new WebAppContext(); webAppContext.setContextPath("/"); webAppContext.setWar(appDir + "/" + name); webServer.addHandler(webAppContext); addDefaultApps(contexts, appDir); final FilterInitializer[] initializers = getFilterInitializers(conf); if (initializers != null) { for(FilterInitializer c : initializers) { c.initFilter(this); } } addDefaultServlets(); } /** * Create a required listener for the Jetty instance listening on the port * provided. This wrapper and all subclasses must create at least one * listener. */ protected Connector createBaseListener(Configuration conf) throws IOException { SelectChannelConnector ret = new SelectChannelConnector(); ret.setLowResourceMaxIdleTime(10000); ret.setAcceptQueueSize(128); ret.setResolveNames(false); ret.setUseDirectBuffers(false); return ret; } /** Get an array of FilterConfiguration specified in the conf */ private static FilterInitializer[] getFilterInitializers(Configuration conf) { if (conf == null) { return null; } Class<?>[] classes = conf.getClasses(FILTER_INITIALIZER_PROPERTY); if (classes == null) { return null; } FilterInitializer[] initializers = new FilterInitializer[classes.length]; for(int i = 0; i < classes.length; i++) { initializers[i] = (FilterInitializer)ReflectionUtils.newInstance( classes[i], conf); } return initializers; } /** * Add default apps. * @param appDir The application directory * @throws IOException */ protected void addDefaultApps(ContextHandlerCollection parent, final String appDir) throws IOException { // set up the context for "/logs/" if "hadoop.log.dir" property is defined. String logDir = System.getProperty("hadoop.log.dir"); if (logDir != null) { Context logContext = new Context(parent, "/logs"); logContext.setResourceBase(logDir); logContext.addServlet(DefaultServlet.class, "/"); defaultContexts.put(logContext, true); } // set up the context for "/static/*" Context staticContext = new Context(parent, "/static"); staticContext.setResourceBase(appDir + "/static"); staticContext.addServlet(DefaultServlet.class, "/*"); defaultContexts.put(staticContext, true); } /** * Add default servlets. */ protected void addDefaultServlets() { // set up default servlets addServlet("stacks", "/stacks", StackServlet.class); addServlet("logLevel", "/logLevel", LogLevel.Servlet.class); } public void addContext(Context ctxt, boolean isFiltered) throws IOException { webServer.addHandler(ctxt); defaultContexts.put(ctxt, isFiltered); } /** * Add a context * @param pathSpec The path spec for the context * @param dir The directory containing the context * @param isFiltered if true, the servlet is added to the filter path mapping * @throws IOException */ protected void addContext(String pathSpec, String dir, boolean isFiltered) throws IOException { if (0 == webServer.getHandlers().length) { throw new RuntimeException("Couldn't find handler"); } WebAppContext webAppCtx = new WebAppContext(); webAppCtx.setContextPath(pathSpec); webAppCtx.setWar(dir); addContext(webAppCtx, true); } /** * Set a value in the webapp context. These values are available to the jsp * pages as "application.getAttribute(name)". * @param name The name of the attribute * @param value The value of the attribute */ public void setAttribute(String name, Object value) { webAppContext.setAttribute(name, value); } /** * Add a servlet in the server. * @param name The name of the servlet (can be passed as null) * @param pathSpec The path spec for the servlet * @param clazz The servlet class */ public void addServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz) { addInternalServlet(name, pathSpec, clazz); addFilterPathMapping(pathSpec, webAppContext); } /** * Add an internal servlet in the server. * @param name The name of the servlet (can be passed as null) * @param pathSpec The path spec for the servlet * @param clazz The servlet class * @deprecated this is a temporary method */ @Deprecated public void addInternalServlet(String name, String pathSpec, Class<? extends HttpServlet> clazz) { ServletHolder holder = new ServletHolder(clazz); if (name != null) { holder.setName(name); } webAppContext.addServlet(holder, pathSpec); } /** {@inheritDoc} */ public void addFilter(String name, String classname, Map<String, String> parameters) { final String[] USER_FACING_URLS = { "*.html", "*.jsp" }; defineFilter(webAppContext, name, classname, parameters, USER_FACING_URLS); final String[] ALL_URLS = { "/*" }; for (Map.Entry<Context, Boolean> e : defaultContexts.entrySet()) { if (e.getValue()) { Context ctx = e.getKey(); defineFilter(ctx, name, classname, parameters, ALL_URLS); LOG.info("Added filter " + name + " (class=" + classname + ") to context " + ctx.getDisplayName()); } } filterNames.add(name); } /** {@inheritDoc} */ public void addGlobalFilter(String name, String classname, Map<String, String> parameters) { final String[] ALL_URLS = { "/*" }; defineFilter(webAppContext, name, classname, parameters, ALL_URLS); for (Context ctx : defaultContexts.keySet()) { defineFilter(ctx, name, classname, parameters, ALL_URLS); } LOG.info("Added global filter" + name + " (class=" + classname + ")"); } /** * Define a filter for a context and set up default url mappings. */ protected void defineFilter(Context ctx, String name, String classname, Map<String,String> parameters, String[] urls) { FilterHolder holder = new FilterHolder(); holder.setName(name); holder.setClassName(classname); holder.setInitParameters(parameters); FilterMapping fmap = new FilterMapping(); fmap.setPathSpecs(urls); fmap.setDispatches(Handler.ALL); fmap.setFilterName(name); ServletHandler handler = ctx.getServletHandler(); handler.addFilter(holder, fmap); } /** * Add the path spec to the filter path mapping. * @param pathSpec The path spec * @param webAppCtx The WebApplicationContext to add to */ protected void addFilterPathMapping(String pathSpec, Context webAppCtx) { ServletHandler handler = webAppCtx.getServletHandler(); for(String name : filterNames) { FilterMapping fmap = new FilterMapping(); fmap.setPathSpec(pathSpec); fmap.setFilterName(name); fmap.setDispatches(Handler.ALL); handler.addFilterMapping(fmap); } } /** * Get the value in the webapp context. * @param name The name of the attribute * @return The value of the attribute */ public Object getAttribute(String name) { return webAppContext.getAttribute(name); } /** * Get the pathname to the webapps files. * @return the pathname as a URL * @throws IOException if 'webapps' directory cannot be found on CLASSPATH. */ protected String getWebAppsPath() throws IOException { URL url = getClass().getClassLoader().getResource("webapps"); if (url == null) throw new IOException("webapps not found in CLASSPATH"); return url.toString(); } /** * Get the port that the server is on * @return the port */ public int getPort() { return webServer.getConnectors()[0].getLocalPort(); } /** * Set the min, max number of worker threads (simultaneous connections). */ public void setThreads(int min, int max) { QueuedThreadPool pool = (QueuedThreadPool) webServer.getThreadPool() ; pool.setMinThreads(min); pool.setMaxThreads(max); } /** * Configure an ssl listener on the server. * @param addr address to listen on * @param keystore location of the keystore * @param storPass password for the keystore * @param keyPass password for the key * @deprecated Use {@link #addSslListener(InetSocketAddress, Configuration, boolean)} */ @Deprecated public void addSslListener(InetSocketAddress addr, String keystore, String storPass, String keyPass) throws IOException { if (webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } SslSocketConnector sslListener = new SslSocketConnector(); sslListener.setHost(addr.getHostName()); sslListener.setPort(addr.getPort()); sslListener.setKeystore(keystore); sslListener.setPassword(storPass); sslListener.setKeyPassword(keyPass); webServer.addConnector(sslListener); } /** * Configure an ssl listener on the server. * @param addr address to listen on * @param sslConf conf to retrieve ssl options * @param needClientAuth whether client authentication is required */ public void addSslListener(InetSocketAddress addr, Configuration sslConf, boolean needClientAuth) throws IOException { if (webServer.isStarted()) { throw new IOException("Failed to add ssl listener"); } if (needClientAuth) { // setting up SSL truststore for authenticating clients System.setProperty("javax.net.ssl.trustStore", sslConf.get( "ssl.server.truststore.location", "")); System.setProperty("javax.net.ssl.trustStorePassword", sslConf.get( "ssl.server.truststore.password", "")); System.setProperty("javax.net.ssl.trustStoreType", sslConf.get( "ssl.server.truststore.type", "jks")); } SslSocketConnector sslListener = new SslSocketConnector(); sslListener.setHost(addr.getHostName()); sslListener.setPort(addr.getPort()); sslListener.setKeystore(sslConf.get("ssl.server.keystore.location")); sslListener.setPassword(sslConf.get("ssl.server.keystore.password", "")); sslListener.setKeyPassword(sslConf.get("ssl.server.keystore.keypassword", "")); sslListener.setKeystoreType(sslConf.get("ssl.server.keystore.type", "jks")); sslListener.setNeedClientAuth(needClientAuth); webServer.addConnector(sslListener); } /** * Start the server. Does not wait for the server to start. */ public void start() throws IOException { try { int port = 0; int oriPort = listener.getPort(); // The original requested port while (true) { try { port = webServer.getConnectors()[0].getLocalPort(); LOG.info("Port returned by webServer.getConnectors()[0]." + "getLocalPort() before open() is "+ port + ". Opening the listener on " + oriPort); listener.open(); port = listener.getLocalPort(); LOG.info("listener.getLocalPort() returned " + listener.getLocalPort() + " webServer.getConnectors()[0].getLocalPort() returned " + webServer.getConnectors()[0].getLocalPort()); //Workaround to handle the problem reported in HADOOP-4744 if (port < 0) { Thread.sleep(100); int numRetries = 1; while (port < 0) { LOG.warn("listener.getLocalPort returned " + port); if (numRetries++ > MAX_RETRIES) { throw new Exception(" listener.getLocalPort is returning " + "less than 0 even after " +numRetries+" resets"); } for (int i = 0; i < 2; i++) { LOG.info("Retrying listener.getLocalPort()"); port = listener.getLocalPort(); if (port > 0) { break; } Thread.sleep(200); } if (port > 0) { break; } LOG.info("Bouncing the listener"); listener.close(); Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); port = listener.getLocalPort(); } } //Workaround end LOG.info("Jetty bound to port " + port); webServer.start(); // Workaround for HADOOP-6386 port = listener.getLocalPort(); if (port < 0) { LOG.warn("Bounds port is " + port + " after webserver start"); - Random r = new Random(1000); for (int i = 0; i < MAX_RETRIES/2; i++) { try { webServer.stop(); } catch (Exception e) { LOG.warn("Can't stop web-server", e); } - Thread.sleep(r.nextInt()); + Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); webServer.start(); LOG.info(i + "attempts to restart webserver"); port = listener.getLocalPort(); if (port > 0) break; } if (port < 0) throw new Exception("listener.getLocalPort() is returning " + "less than 0 even after " +MAX_RETRIES+" resets"); } // End of HADOOP-6386 workaround break; } catch (IOException ex) { // if this is a bind exception, // then try the next port number. if (ex instanceof BindException) { if (!findPort) { throw (BindException) ex; } } else { LOG.info("HttpServer.start() threw a non Bind IOException"); throw ex; } } catch (MultiException ex) { LOG.info("HttpServer.start() threw a MultiException"); throw ex; } listener.setPort((oriPort += 1)); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Problem starting http server", e); } } /** * stop the server */ public void stop() throws Exception { listener.close(); webServer.stop(); } public void join() throws InterruptedException { webServer.join(); } /** * A very simple servlet to serve up a text representation of the current * stack traces. It both returns the stacks to the caller and logs them. * Currently the stack traces are done sequentially rather than exactly the * same data. */ public static class StackServlet extends HttpServlet { private static final long serialVersionUID = -6284183679759467039L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = new PrintWriter(response.getOutputStream()); ReflectionUtils.printThreadInfo(out, ""); out.close(); ReflectionUtils.logThreadInfo(LOG, "jsp requested", 1); } } }
false
true
public void start() throws IOException { try { int port = 0; int oriPort = listener.getPort(); // The original requested port while (true) { try { port = webServer.getConnectors()[0].getLocalPort(); LOG.info("Port returned by webServer.getConnectors()[0]." + "getLocalPort() before open() is "+ port + ". Opening the listener on " + oriPort); listener.open(); port = listener.getLocalPort(); LOG.info("listener.getLocalPort() returned " + listener.getLocalPort() + " webServer.getConnectors()[0].getLocalPort() returned " + webServer.getConnectors()[0].getLocalPort()); //Workaround to handle the problem reported in HADOOP-4744 if (port < 0) { Thread.sleep(100); int numRetries = 1; while (port < 0) { LOG.warn("listener.getLocalPort returned " + port); if (numRetries++ > MAX_RETRIES) { throw new Exception(" listener.getLocalPort is returning " + "less than 0 even after " +numRetries+" resets"); } for (int i = 0; i < 2; i++) { LOG.info("Retrying listener.getLocalPort()"); port = listener.getLocalPort(); if (port > 0) { break; } Thread.sleep(200); } if (port > 0) { break; } LOG.info("Bouncing the listener"); listener.close(); Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); port = listener.getLocalPort(); } } //Workaround end LOG.info("Jetty bound to port " + port); webServer.start(); // Workaround for HADOOP-6386 port = listener.getLocalPort(); if (port < 0) { LOG.warn("Bounds port is " + port + " after webserver start"); Random r = new Random(1000); for (int i = 0; i < MAX_RETRIES/2; i++) { try { webServer.stop(); } catch (Exception e) { LOG.warn("Can't stop web-server", e); } Thread.sleep(r.nextInt()); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); webServer.start(); LOG.info(i + "attempts to restart webserver"); port = listener.getLocalPort(); if (port > 0) break; } if (port < 0) throw new Exception("listener.getLocalPort() is returning " + "less than 0 even after " +MAX_RETRIES+" resets"); } // End of HADOOP-6386 workaround break; } catch (IOException ex) { // if this is a bind exception, // then try the next port number. if (ex instanceof BindException) { if (!findPort) { throw (BindException) ex; } } else { LOG.info("HttpServer.start() threw a non Bind IOException"); throw ex; } } catch (MultiException ex) { LOG.info("HttpServer.start() threw a MultiException"); throw ex; } listener.setPort((oriPort += 1)); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Problem starting http server", e); } }
public void start() throws IOException { try { int port = 0; int oriPort = listener.getPort(); // The original requested port while (true) { try { port = webServer.getConnectors()[0].getLocalPort(); LOG.info("Port returned by webServer.getConnectors()[0]." + "getLocalPort() before open() is "+ port + ". Opening the listener on " + oriPort); listener.open(); port = listener.getLocalPort(); LOG.info("listener.getLocalPort() returned " + listener.getLocalPort() + " webServer.getConnectors()[0].getLocalPort() returned " + webServer.getConnectors()[0].getLocalPort()); //Workaround to handle the problem reported in HADOOP-4744 if (port < 0) { Thread.sleep(100); int numRetries = 1; while (port < 0) { LOG.warn("listener.getLocalPort returned " + port); if (numRetries++ > MAX_RETRIES) { throw new Exception(" listener.getLocalPort is returning " + "less than 0 even after " +numRetries+" resets"); } for (int i = 0; i < 2; i++) { LOG.info("Retrying listener.getLocalPort()"); port = listener.getLocalPort(); if (port > 0) { break; } Thread.sleep(200); } if (port > 0) { break; } LOG.info("Bouncing the listener"); listener.close(); Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); port = listener.getLocalPort(); } } //Workaround end LOG.info("Jetty bound to port " + port); webServer.start(); // Workaround for HADOOP-6386 port = listener.getLocalPort(); if (port < 0) { LOG.warn("Bounds port is " + port + " after webserver start"); for (int i = 0; i < MAX_RETRIES/2; i++) { try { webServer.stop(); } catch (Exception e) { LOG.warn("Can't stop web-server", e); } Thread.sleep(1000); listener.setPort(oriPort == 0 ? 0 : (oriPort += 1)); listener.open(); Thread.sleep(100); webServer.start(); LOG.info(i + "attempts to restart webserver"); port = listener.getLocalPort(); if (port > 0) break; } if (port < 0) throw new Exception("listener.getLocalPort() is returning " + "less than 0 even after " +MAX_RETRIES+" resets"); } // End of HADOOP-6386 workaround break; } catch (IOException ex) { // if this is a bind exception, // then try the next port number. if (ex instanceof BindException) { if (!findPort) { throw (BindException) ex; } } else { LOG.info("HttpServer.start() threw a non Bind IOException"); throw ex; } } catch (MultiException ex) { LOG.info("HttpServer.start() threw a MultiException"); throw ex; } listener.setPort((oriPort += 1)); } } catch (IOException e) { throw e; } catch (Exception e) { throw new IOException("Problem starting http server", e); } }
diff --git a/src/main/org/testng/xml/XmlTest.java b/src/main/org/testng/xml/XmlTest.java index 53e1d51..b2c6b98 100644 --- a/src/main/org/testng/xml/XmlTest.java +++ b/src/main/org/testng/xml/XmlTest.java @@ -1,472 +1,473 @@ package org.testng.xml; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.testng.TestNG; import org.testng.internal.AnnotationTypeEnum; import org.testng.reporters.XMLStringBuffer; /** * This class describes the tag &lt;test&gt; in testng.xml. * * @author <a href = "mailto:cedric&#64;beust.com">Cedric Beust</a> * @author <a href = 'mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class XmlTest implements Serializable, Cloneable { private final XmlSuite m_suite; private String m_name = TestNG.DEFAULT_COMMAND_LINE_SUITE_NAME; private Integer m_verbose; private Boolean m_isJUnit; private List<XmlClass> m_xmlClasses = new ArrayList<XmlClass>(); private List<String> m_includedGroups = new ArrayList<String>(); private List<String> m_excludedGroups = new ArrayList<String>(); private final Map<String, List<String>> m_metaGroups = new HashMap<String, List<String>>(); private Map<String, String> m_parameters = new HashMap<String, String>(); private String m_parallel; /** */ private AnnotationTypeEnum m_annotations; // BeanShell expression private String m_expression; private List<XmlMethodSelector> m_methodSelectors = new ArrayList<XmlMethodSelector>(); // test level packages private List<XmlPackage> m_xmlPackages = new ArrayList<XmlPackage>(); private String m_timeOut; /** * Constructs a <code>XmlTest</code> and adds it to suite's list of tests. * * @param suite the parent suite. */ public XmlTest(XmlSuite suite) { m_suite = suite; m_suite.getTests().add(this); } public void setXmlPackages(List<XmlPackage> packages) { m_xmlPackages = packages; } public List<XmlPackage> getXmlPackages() { return m_xmlPackages; } public List<XmlMethodSelector> getMethodSelectors() { return m_methodSelectors; } public void setMethodSelectors(List<XmlMethodSelector> methodSelectors) { m_methodSelectors = methodSelectors; } /** * Returns the suite this test is part of. * @return the suite this test is part of. */ public XmlSuite getSuite() { return m_suite; } /** * @return Returns the includedGroups. */ public List<String> getIncludedGroups() { return m_includedGroups; } /** * Sets the XML Classes. * @param classes The classes to set. * @deprecated use setXmlClasses */ public void setClassNames(List<XmlClass> classes) { m_xmlClasses = classes; } /** * @return Returns the classes. */ public List<XmlClass> getXmlClasses() { return m_xmlClasses; } /** * Sets the XML Classes. * @param classes The classes to set. */ public void setXmlClasses(List<XmlClass> classes) { m_xmlClasses = classes; } /** * @return Returns the name. */ public String getName() { return m_name; } /** * @param name The name to set. */ public void setName(String name) { m_name = name; } /** * @param i */ public void setVerbose(int v) { m_verbose = new Integer(v); } /** * @param currentIncludedGroups */ public void setIncludedGroups(List<String> g) { m_includedGroups = g; } /** * @param excludedGrousps The excludedGrousps to set. */ public void setExcludedGroups(List<String> g) { m_excludedGroups = g; } /** * @return Returns the excludedGroups. */ public List<String> getExcludedGroups() { return m_excludedGroups; } /** * @return Returns the verbose. */ public int getVerbose() { Integer result = m_verbose; if (null == result) { result = m_suite.getVerbose(); } return result.intValue(); } /** * @return Returns the isJUnit. */ public boolean isJUnit() { Boolean result = m_isJUnit; if (null == result) { result = m_suite.isJUnit(); } return result; } /** * @param isJUnit The isJUnit to set. */ public void setJUnit(boolean isJUnit) { m_isJUnit = isJUnit; } public void addMetaGroup(String name, List<String> metaGroup) { m_metaGroups.put(name, metaGroup); } /** * @return Returns the metaGroups. */ public Map<String, List<String>> getMetaGroups() { return m_metaGroups; } /** * @param currentTestParameters */ public void setParameters(Map parameters) { m_parameters = parameters; } public void addParameter(String key, String value) { m_parameters.put(key, value); } public String getParameter(String name) { String result = m_parameters.get(name); if (null == result) { result = m_suite.getParameter(name); } return result; } /** * Returns a merge of the the test parameters and its parent suite parameters. Test parameters * have precedence over suite parameters. * * @return a merge of the the test parameters and its parent suite parameters. */ public Map<String, String> getParameters() { Map<String, String> result = new HashMap<String, String>(); for (String key : getSuite().getParameters().keySet()) { result.put(key, getSuite().getParameters().get(key)); } for (String key : m_parameters.keySet()) { result.put(key, m_parameters.get(key)); } return result; } public void setParallel(String parallel) { m_parallel = parallel; } public String getParallel() { String result = null; if (null != m_parallel) { result = m_parallel; } else { result = m_suite.getParallel(); } return result; } public String getTimeOut() { String result = null; if (null != m_timeOut) { result = m_timeOut; } else { result = m_suite.getTimeOut(); } return result; } public long getTimeOut(long def) { long result = def; if (getTimeOut() != null) { result = new Long(getTimeOut()).longValue(); } return result; } public String getAnnotations() { return null != m_annotations ? m_annotations.toString() : m_suite.getAnnotations(); } public void setAnnotations(String annotations) { m_annotations = AnnotationTypeEnum.valueOf(annotations); } public void setBeanShellExpression(String expression) { m_expression = expression; } public String getExpression() { return m_expression; } public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { - for (String paramName: m_parameters.keySet()) { - Properties paramProps = new Properties(); - paramProps.setProperty("name", paramName); - paramProps.setProperty("value", m_parameters.get(paramName)); + for(Map.Entry<String, String> para: m_parameters.entrySet()) { + Properties paramProps= new Properties(); + paramProps.setProperty("name", para.getKey()); + paramProps.setProperty("value", para.getValue()); + xsb.addEmptyElement("property", paramProps); // BUGFIX: TESTNG-27 } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); } @Override public String toString() { StringBuffer result = new StringBuffer("[Test: \"" + m_name + "\"") .append(" verbose:" + m_verbose); result.append("[parameters:"); for (String k : m_parameters.keySet()) { String v = m_parameters.get(k); result.append(k + "=>" + v); } result.append("]"); result.append("[metagroups:"); for (String g : m_metaGroups.keySet()) { List<String> mg = m_metaGroups.get(g); result.append(g).append("="); for (String n : mg) { result.append(n).append(","); } } result.append("] "); result.append("[included: "); for (String g : m_includedGroups) { result.append(g).append(" "); } result.append("]"); result.append("[excluded: "); for (String g : m_excludedGroups) { result.append(g).append(""); } result.append("] "); result.append(" classes:"); for (XmlClass cl : m_xmlClasses) { result.append(cl).append(" "); } result.append("] "); return result.toString(); } static void ppp(String s) { System.out.println("[XmlTest] " + s); } /** * Clone the <TT>source</TT> <CODE>XmlTest</CODE> by including: * - test attributes * - groups definitions * - parameters * * The &lt;classes&gt; sub element is ignored for the moment. * * @param suite * @param source * @return */ @Override public Object clone() { XmlTest result = new XmlTest(getSuite()); result.setName(getName()); result.setAnnotations(getAnnotations()); result.setIncludedGroups(getIncludedGroups()); result.setExcludedGroups(getExcludedGroups()); result.setJUnit(isJUnit()); result.setParallel(getParallel()); result.setVerbose(getVerbose()); result.setParameters(getParameters()); result.setXmlPackages(getXmlPackages()); Map<String, List<String>> metagroups = getMetaGroups(); for (String groupName: metagroups.keySet()) { result.addMetaGroup(groupName, metagroups.get(groupName)); } return result; } }
true
true
public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { for (String paramName: m_parameters.keySet()) { Properties paramProps = new Properties(); paramProps.setProperty("name", paramName); paramProps.setProperty("value", m_parameters.get(paramName)); } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); }
public String toXml(String indent) { XMLStringBuffer xsb = new XMLStringBuffer(indent); Properties p = new Properties(); p.setProperty("name", getName()); p.setProperty("junit", m_isJUnit != null ? m_isJUnit.toString() : "false"); if (null != m_parallel && !"".equals(m_parallel)) { p.setProperty("parallel", m_parallel); } if (null != m_verbose) { p.setProperty("verbose", m_verbose.toString()); } if (null != m_annotations) { p.setProperty("annotations", m_annotations.toString()); } xsb.push("test", p); if (null != getMethodSelectors() && !getMethodSelectors().isEmpty()) { xsb.push("method-selectors"); for (XmlMethodSelector selector: getMethodSelectors()) { xsb.getStringBuffer().append(selector.toXml(indent + " ")); } xsb.pop("method-selectors"); } // parameters if (!m_parameters.isEmpty()) { for(Map.Entry<String, String> para: m_parameters.entrySet()) { Properties paramProps= new Properties(); paramProps.setProperty("name", para.getKey()); paramProps.setProperty("value", para.getValue()); xsb.addEmptyElement("property", paramProps); // BUGFIX: TESTNG-27 } } // groups if (!m_metaGroups.isEmpty() || !m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("groups"); // define for (String metaGroupName: m_metaGroups.keySet()) { Properties metaGroupProp= new Properties(); metaGroupProp.setProperty("name", metaGroupName); xsb.push("define", metaGroupProp); for (String groupName: m_metaGroups.get(metaGroupName)) { Properties includeProps = new Properties(); includeProps.setProperty("name", groupName); xsb.addEmptyElement("include", includeProps); } xsb.pop("define"); } if (!m_includedGroups.isEmpty() || !m_excludedGroups.isEmpty()) { xsb.push("run"); for (String includeGroupName: m_includedGroups) { Properties includeProps = new Properties(); includeProps.setProperty("name", includeGroupName); xsb.addEmptyElement("include", includeProps); } for (String excludeGroupName: m_excludedGroups) { Properties excludeProps = new Properties(); excludeProps.setProperty("name", excludeGroupName); xsb.addEmptyElement("exclude", excludeProps); } xsb.pop("run"); } xsb.pop("groups"); } // HINT: don't call getXmlPackages() cause you will retrieve the suite packages too if (null != m_xmlPackages && !m_xmlPackages.isEmpty()) { xsb.push("packages"); for (XmlPackage pack: m_xmlPackages) { xsb.getStringBuffer().append(pack.toXml(" ")); } xsb.pop("packages"); } // classes if (null != getXmlClasses() && !getXmlClasses().isEmpty()) { xsb.push("classes"); for (XmlClass cls : getXmlClasses()) { xsb.getStringBuffer().append(cls.toXml(indent + " ")); } xsb.pop("classes"); } xsb.pop("test"); return xsb.toXML(); }
diff --git a/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/SelectionMonitor.java b/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/SelectionMonitor.java index c1c97f21..ca22c715 100644 --- a/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/SelectionMonitor.java +++ b/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/SelectionMonitor.java @@ -1,188 +1,188 @@ /******************************************************************************* * Copyright (c) 2004 - 2005 University Of British Columbia and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * University Of British Columbia - initial API and implementation *******************************************************************************/ /* * Created on Jun 10, 2005 */ package org.eclipse.mylar.monitor; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.eclipse.core.internal.preferences.Base64; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IPath; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.internal.ui.actions.SelectionConverter; import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jface.text.TextSelection; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.mylar.core.AbstractSelectionMonitor; import org.eclipse.mylar.core.IMylarElement; import org.eclipse.mylar.core.InteractionEvent; import org.eclipse.mylar.core.MylarPlugin; import org.eclipse.mylar.core.internal.MylarContextManager; import org.eclipse.ui.IEditorInput; import org.eclipse.ui.IPathEditorInput; import org.eclipse.ui.IWorkbenchPart; import org.eclipse.ui.part.EditorPart; /** * Limited to Java selections. * * @author Mik Kersten */ public class SelectionMonitor extends AbstractSelectionMonitor { public static final String SELECTION_DEFAULT = "selected"; public static final String SELECTION_NEW = "new"; public static final String SELECTION_DECAYED = "decayed"; public static final String SELECTION_PREDICTED = "predicted"; private IJavaElement lastSelectedElement = null; @Override protected void handleWorkbenchPartSelection(IWorkbenchPart part, ISelection selection) { // ignored, since not using taskscape monitoring facilities } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { String structureKind = "?"; String obfuscatedElementHandle = "?"; String elementHandle = "?"; InteractionEvent.Kind interactionKind = InteractionEvent.Kind.SELECTION; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection)selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject == null) return; if (selectedObject instanceof IJavaElement) { IJavaElement javaElement = (IJavaElement)selectedObject; structureKind = "java:" + javaElement.getClass(); elementHandle = javaElement.getHandleIdentifier(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); lastSelectedElement = javaElement; } else { structureKind = "?: " + selectedObject.getClass(); if (selectedObject instanceof IAdaptable) { IResource resource = (IResource)((IAdaptable)selectedObject).getAdapter(IResource.class); if (resource != null) { obfuscatedElementHandle = obfuscateResourcePath(resource.getProjectRelativePath()); } } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { TextSelection textSelection = (TextSelection)selection; IJavaElement javaElement; try { javaElement = SelectionConverter.resolveEnclosingElement((JavaEditor)part, textSelection); if (javaElement != null) { structureKind = "java:" + javaElement.getClass(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); elementHandle = javaElement.getHandleIdentifier(); if (javaElement != null && javaElement.equals(lastSelectedElement)) { interactionKind = InteractionEvent.Kind.EDIT; } lastSelectedElement = javaElement; } } catch (JavaModelException e) { // ignore unresolved elements // MylarPlugin.log("Could not resolve java element from text selection.", this); } } else if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart)part; IEditorInput input = editorPart.getEditorInput(); if (input instanceof IPathEditorInput) { structureKind = "file"; obfuscatedElementHandle = obfuscateResourcePath(((IPathEditorInput)input).getPath()); } } } - IMylarElement node = MylarPlugin.getContextManager().getNode(elementHandle); + IMylarElement node = MylarPlugin.getContextManager().getElement(elementHandle); String delta = ""; float selectionFactor = MylarContextManager.getScalingFactors().get(InteractionEvent.Kind.SELECTION).getValue(); // XXX: need unit test for these rules. if (node != null) { if (node.getDegreeOfInterest().getEncodedValue() <= selectionFactor && node.getDegreeOfInterest().getValue() > selectionFactor) { delta = SELECTION_PREDICTED; } else if (node.getDegreeOfInterest().getEncodedValue() < selectionFactor && node.getDegreeOfInterest().getDecayValue() > selectionFactor) { delta = SELECTION_DECAYED; } else if (node.getDegreeOfInterest().getValue() == selectionFactor && node.getDegreeOfInterest().getDecayValue() < selectionFactor) { delta = SELECTION_NEW; } else { delta = SELECTION_DEFAULT; } } InteractionEvent event = new InteractionEvent( interactionKind, structureKind, obfuscatedElementHandle, part.getSite().getId(), "null", delta, 0); MylarPlugin.getDefault().notifyInteractionObserved(event); } private String obfuscateResourcePath(IPath path) { StringBuffer obfuscatedPath = new StringBuffer(); for (int i = 0; i < path.segmentCount(); i++) { obfuscatedPath.append(obfuscateString(path.segments()[i])); if (i < path.segmentCount()-1) obfuscatedPath.append('/'); } return obfuscatedPath.toString(); } /** * Encrypts the string using SHA, then makes it reasonable to print. */ private String obfuscateString(String string) { String obfuscatedString = null; try { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(string.getBytes()); byte[] digest = md.digest(); obfuscatedString = new String(Base64.encode(digest)).replace('/', '='); // obfuscatedString = "" + new String(digest).hashCode(); } catch (NoSuchAlgorithmException e) { MylarPlugin.log("SHA not available", this); obfuscatedString = "<failed to obfuscate>"; } return obfuscatedString; } private String obfuscateJavaElementHandle(IJavaElement javaElement) { try { StringBuffer obfuscatedPath = new StringBuffer(); IResource resource; resource = (IResource)javaElement.getUnderlyingResource(); if (resource != null &&(resource instanceof IFile)) { IFile file = (IFile)resource; obfuscatedPath.append(obfuscateResourcePath(file.getProjectRelativePath())); obfuscatedPath.append(':'); obfuscatedPath.append(obfuscateString(javaElement.getElementName())); return obfuscatedPath.toString(); } } catch (JavaModelException e) { // ignore non-existing element // MylarPlugin.log(this, "failed to resolve java element for element: " + javaElement.getHandleIdentifier()); } return "(non-source element)"; } }
true
true
public void selectionChanged(IWorkbenchPart part, ISelection selection) { String structureKind = "?"; String obfuscatedElementHandle = "?"; String elementHandle = "?"; InteractionEvent.Kind interactionKind = InteractionEvent.Kind.SELECTION; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection)selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject == null) return; if (selectedObject instanceof IJavaElement) { IJavaElement javaElement = (IJavaElement)selectedObject; structureKind = "java:" + javaElement.getClass(); elementHandle = javaElement.getHandleIdentifier(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); lastSelectedElement = javaElement; } else { structureKind = "?: " + selectedObject.getClass(); if (selectedObject instanceof IAdaptable) { IResource resource = (IResource)((IAdaptable)selectedObject).getAdapter(IResource.class); if (resource != null) { obfuscatedElementHandle = obfuscateResourcePath(resource.getProjectRelativePath()); } } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { TextSelection textSelection = (TextSelection)selection; IJavaElement javaElement; try { javaElement = SelectionConverter.resolveEnclosingElement((JavaEditor)part, textSelection); if (javaElement != null) { structureKind = "java:" + javaElement.getClass(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); elementHandle = javaElement.getHandleIdentifier(); if (javaElement != null && javaElement.equals(lastSelectedElement)) { interactionKind = InteractionEvent.Kind.EDIT; } lastSelectedElement = javaElement; } } catch (JavaModelException e) { // ignore unresolved elements // MylarPlugin.log("Could not resolve java element from text selection.", this); } } else if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart)part; IEditorInput input = editorPart.getEditorInput(); if (input instanceof IPathEditorInput) { structureKind = "file"; obfuscatedElementHandle = obfuscateResourcePath(((IPathEditorInput)input).getPath()); } } } IMylarElement node = MylarPlugin.getContextManager().getNode(elementHandle); String delta = ""; float selectionFactor = MylarContextManager.getScalingFactors().get(InteractionEvent.Kind.SELECTION).getValue(); // XXX: need unit test for these rules. if (node != null) { if (node.getDegreeOfInterest().getEncodedValue() <= selectionFactor && node.getDegreeOfInterest().getValue() > selectionFactor) { delta = SELECTION_PREDICTED; } else if (node.getDegreeOfInterest().getEncodedValue() < selectionFactor && node.getDegreeOfInterest().getDecayValue() > selectionFactor) { delta = SELECTION_DECAYED; } else if (node.getDegreeOfInterest().getValue() == selectionFactor && node.getDegreeOfInterest().getDecayValue() < selectionFactor) { delta = SELECTION_NEW; } else { delta = SELECTION_DEFAULT; } } InteractionEvent event = new InteractionEvent( interactionKind, structureKind, obfuscatedElementHandle, part.getSite().getId(), "null", delta, 0); MylarPlugin.getDefault().notifyInteractionObserved(event); }
public void selectionChanged(IWorkbenchPart part, ISelection selection) { String structureKind = "?"; String obfuscatedElementHandle = "?"; String elementHandle = "?"; InteractionEvent.Kind interactionKind = InteractionEvent.Kind.SELECTION; if (selection instanceof StructuredSelection) { StructuredSelection structuredSelection = (StructuredSelection)selection; Object selectedObject = structuredSelection.getFirstElement(); if (selectedObject == null) return; if (selectedObject instanceof IJavaElement) { IJavaElement javaElement = (IJavaElement)selectedObject; structureKind = "java:" + javaElement.getClass(); elementHandle = javaElement.getHandleIdentifier(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); lastSelectedElement = javaElement; } else { structureKind = "?: " + selectedObject.getClass(); if (selectedObject instanceof IAdaptable) { IResource resource = (IResource)((IAdaptable)selectedObject).getAdapter(IResource.class); if (resource != null) { obfuscatedElementHandle = obfuscateResourcePath(resource.getProjectRelativePath()); } } } } else { if (selection instanceof TextSelection && part instanceof JavaEditor) { TextSelection textSelection = (TextSelection)selection; IJavaElement javaElement; try { javaElement = SelectionConverter.resolveEnclosingElement((JavaEditor)part, textSelection); if (javaElement != null) { structureKind = "java:" + javaElement.getClass(); obfuscatedElementHandle = obfuscateJavaElementHandle(javaElement); elementHandle = javaElement.getHandleIdentifier(); if (javaElement != null && javaElement.equals(lastSelectedElement)) { interactionKind = InteractionEvent.Kind.EDIT; } lastSelectedElement = javaElement; } } catch (JavaModelException e) { // ignore unresolved elements // MylarPlugin.log("Could not resolve java element from text selection.", this); } } else if (part instanceof EditorPart) { EditorPart editorPart = (EditorPart)part; IEditorInput input = editorPart.getEditorInput(); if (input instanceof IPathEditorInput) { structureKind = "file"; obfuscatedElementHandle = obfuscateResourcePath(((IPathEditorInput)input).getPath()); } } } IMylarElement node = MylarPlugin.getContextManager().getElement(elementHandle); String delta = ""; float selectionFactor = MylarContextManager.getScalingFactors().get(InteractionEvent.Kind.SELECTION).getValue(); // XXX: need unit test for these rules. if (node != null) { if (node.getDegreeOfInterest().getEncodedValue() <= selectionFactor && node.getDegreeOfInterest().getValue() > selectionFactor) { delta = SELECTION_PREDICTED; } else if (node.getDegreeOfInterest().getEncodedValue() < selectionFactor && node.getDegreeOfInterest().getDecayValue() > selectionFactor) { delta = SELECTION_DECAYED; } else if (node.getDegreeOfInterest().getValue() == selectionFactor && node.getDegreeOfInterest().getDecayValue() < selectionFactor) { delta = SELECTION_NEW; } else { delta = SELECTION_DEFAULT; } } InteractionEvent event = new InteractionEvent( interactionKind, structureKind, obfuscatedElementHandle, part.getSite().getId(), "null", delta, 0); MylarPlugin.getDefault().notifyInteractionObserved(event); }
diff --git a/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/structure/StructureData.java b/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/structure/StructureData.java index cd14ea39..904aaca3 100644 --- a/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/structure/StructureData.java +++ b/Demigods-Engine/src/main/java/com/censoredsoftware/demigods/engine/structure/StructureData.java @@ -1,399 +1,399 @@ package com.censoredsoftware.demigods.engine.structure; import com.censoredsoftware.censoredlib.data.location.CLocation; import com.censoredsoftware.censoredlib.data.location.Region; import com.censoredsoftware.demigods.engine.Demigods; import com.censoredsoftware.demigods.engine.data.DataManager; import com.censoredsoftware.demigods.engine.data.util.CLocations; import com.censoredsoftware.demigods.engine.player.DCharacter; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.serialization.ConfigurationSerializable; import java.util.*; public class StructureData implements ConfigurationSerializable { private UUID id; private String type; private UUID referenceLocation; private List<String> flags; private String region; private String design; private Float corruption, sanctity; private Boolean active; private UUID owner; private Map<String, Long> corruptors, sanctifiers; public StructureData() {} public StructureData(UUID id, ConfigurationSection conf) { this.id = id; type = conf.getString("type"); referenceLocation = UUID.fromString(conf.getString("referenceLocation")); flags = conf.getStringList("flags"); region = conf.getString("region"); design = conf.getString("design"); if(conf.contains("corruption")) { try { corruption = Float.valueOf(conf.getString("corruption")); } catch(Throwable ignored) {} } if(conf.contains("sanctity")) { try { sanctity = Float.valueOf(conf.getString("sanctity")); } catch(Throwable ignored) {} } if(conf.getString("active") != null) active = conf.getBoolean("active"); if(conf.getString("owner") != null) owner = UUID.fromString(conf.getString("owner")); if(conf.isConfigurationSection("corruptors")) { - corruptors = Maps.transformValues(conf.getConfigurationSection("corruptors").getValues(false), new Function<Object, Long>() + corruptors = Maps.newHashMap(Maps.transformValues(conf.getConfigurationSection("corruptors").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } - }); + })); } if(conf.isConfigurationSection("sanctifiers")) { - sanctifiers = Maps.transformValues(conf.getConfigurationSection("sanctifiers").getValues(false), new Function<Object, Long>() + sanctifiers = Maps.newHashMap(Maps.transformValues(conf.getConfigurationSection("sanctifiers").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } - }); + })); } } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<String, Object>(); map.put("type", type); map.put("referenceLocation", referenceLocation.toString()); map.put("flags", flags); map.put("region", region); map.put("design", design); if(sanctity != null) map.put("sanctity", sanctity.toString()); if(active != null) map.put("active", active); if(owner != null) map.put("owner", owner.toString()); if(corruptors != null && !corruptors .isEmpty()) map.put("corruptors", corruptors); if(sanctifiers != null && !sanctifiers.isEmpty()) map.put("sanctifiers", sanctifiers); return map; } public void generateId() { id = UUID.randomUUID(); } public void setType(String type) { this.type = type; } public void setSanctity(float sanctity) { this.sanctity = sanctity; } public void corrupt(DCharacter character, float amount) { if(getType().corrupt(this, character)) { addCorruptor(character.getId()); corrupt(amount); if(getCorruption() >= getSanctity() && getType().kill(this, character)) kill(character); } } public void corrupt(float amount) { if(corruption == null || corruption < 0F) corruption = 0F; corruption = corruption + amount; save(); } public void kill(DCharacter character) { if(getType().kill(this, character)) remove(); remove(); } public void setDesign(String name) { this.design = name; } public void setReferenceLocation(Location reference) { CLocation dLocation = CLocations.create(reference); this.referenceLocation = dLocation.getId(); setRegion(dLocation.getRegion()); } public void setOwner(UUID id) { this.owner = id; addSanctifier(id); } public void sanctify(DCharacter character, float amount) { if(getType().sanctify(this, character)) { addSanctifier(character.getId()); sanctify(amount); } } public void sanctify(float amount) { if(sanctity == null || sanctity < 0F) sanctity = 0F; sanctity = sanctity + amount; save(); } public void setCorruptors(Map<String, Long> corruptors) { this.corruptors = corruptors; } public void addCorruptor(UUID id) { if(corruptors == null) corruptors = Maps.newHashMap(); corruptors.put(id.toString(), System.currentTimeMillis()); save(); } public void removeCorruptor(UUID id) { corruptors.remove(id.toString()); } public void setSanctifiers(Map<String, Long> sanctifiers) { this.sanctifiers = sanctifiers; } public void addSanctifier(UUID id) { if(sanctifiers == null) sanctifiers = Maps.newHashMap(); sanctifiers.put(id.toString(), System.currentTimeMillis()); save(); } public void removeSanctifier(UUID id) { sanctifiers.remove(id.toString()); } public void setActive(Boolean bool) { this.active = bool; } public Location getReferenceLocation() { return CLocations.load(referenceLocation).toLocation(); } public Set<Location> getClickableBlocks() { return getType().getDesign(design).getClickableBlocks(getReferenceLocation()); } public Set<Location> getLocations() { return getType().getDesign(design).getSchematic().getLocations(getReferenceLocation()); } public Structure getType() { for(Structure structure : Demigods.mythos().getStructures()) if(structure.getName().equalsIgnoreCase(this.type)) return structure; return null; } public Boolean hasOwner() { return this.owner != null; } public Float getCorruption() { if(corruption == null || corruption <= 0F) corruption = getType().getDefSanctity(); return corruption; } public Float getSanctity() { if(sanctity == null || sanctity <= 0F) sanctity = getType().getDefSanctity(); return sanctity; } public UUID getOwner() { return this.owner; } public Boolean hasMembers() { return this.sanctifiers != null && !sanctifiers.isEmpty(); } public Collection<UUID> getCorruptors() { return Collections2.transform(corruptors.keySet(), new Function<String, UUID>() { @Override public UUID apply(String s) { return UUID.fromString(s); } }); } public Collection<UUID> getSanctifiers() { return Collections2.transform(sanctifiers.keySet(), new Function<String, UUID>() { @Override public UUID apply(String s) { return UUID.fromString(s); } }); } public String getTypeName() { return type; } public Boolean getActive() { return this.active; } private void setRegion(Region region) { this.region = region.toString(); } public String getRegion() { return region; } public void addFlags(Set<Structure.Flag> flags) { for(Structure.Flag flag : flags) getRawFlags().add(flag.name()); } public List<String> getRawFlags() { if(this.flags == null) flags = Lists.newArrayList(); return this.flags; } public UUID getId() { return this.id; } public void generate() { getType().getDesign(design).getSchematic().generate(getReferenceLocation()); } public void save() { DataManager.structures.put(getId(), this); } public void remove() { for(Location location : getLocations()) location.getBlock().setType(Material.AIR); CLocations.delete(referenceLocation); Util.remove(id); } @Override public String toString() { return Objects.toStringHelper(this).add("id", this.id).toString(); } @Override public int hashCode() { return Objects.hashCode(id); } @Override public boolean equals(Object other) { return other != null && other instanceof StructureData && ((StructureData) other).getId() == getId(); } public static class Util { public static void remove(UUID id) { DataManager.structures.remove(id); } public static StructureData load(UUID id) { return DataManager.structures.get(id); } public static Collection<StructureData> loadAll() { return DataManager.structures.values(); } public static Collection<StructureData> findAll(Predicate<StructureData> predicate) { return Collections2.filter(DataManager.structures.values(), predicate); } } }
false
true
public StructureData(UUID id, ConfigurationSection conf) { this.id = id; type = conf.getString("type"); referenceLocation = UUID.fromString(conf.getString("referenceLocation")); flags = conf.getStringList("flags"); region = conf.getString("region"); design = conf.getString("design"); if(conf.contains("corruption")) { try { corruption = Float.valueOf(conf.getString("corruption")); } catch(Throwable ignored) {} } if(conf.contains("sanctity")) { try { sanctity = Float.valueOf(conf.getString("sanctity")); } catch(Throwable ignored) {} } if(conf.getString("active") != null) active = conf.getBoolean("active"); if(conf.getString("owner") != null) owner = UUID.fromString(conf.getString("owner")); if(conf.isConfigurationSection("corruptors")) { corruptors = Maps.transformValues(conf.getConfigurationSection("corruptors").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } }); } if(conf.isConfigurationSection("sanctifiers")) { sanctifiers = Maps.transformValues(conf.getConfigurationSection("sanctifiers").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } }); } }
public StructureData(UUID id, ConfigurationSection conf) { this.id = id; type = conf.getString("type"); referenceLocation = UUID.fromString(conf.getString("referenceLocation")); flags = conf.getStringList("flags"); region = conf.getString("region"); design = conf.getString("design"); if(conf.contains("corruption")) { try { corruption = Float.valueOf(conf.getString("corruption")); } catch(Throwable ignored) {} } if(conf.contains("sanctity")) { try { sanctity = Float.valueOf(conf.getString("sanctity")); } catch(Throwable ignored) {} } if(conf.getString("active") != null) active = conf.getBoolean("active"); if(conf.getString("owner") != null) owner = UUID.fromString(conf.getString("owner")); if(conf.isConfigurationSection("corruptors")) { corruptors = Maps.newHashMap(Maps.transformValues(conf.getConfigurationSection("corruptors").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } })); } if(conf.isConfigurationSection("sanctifiers")) { sanctifiers = Maps.newHashMap(Maps.transformValues(conf.getConfigurationSection("sanctifiers").getValues(false), new Function<Object, Long>() { @Override public Long apply(Object o) { try { return Long.parseLong(o.toString()); } catch(Throwable ignored) {} return null; } })); } }
diff --git a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSRepositoryPropertiesPage.java b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSRepositoryPropertiesPage.java index a31e9ec78..efe42d63b 100644 --- a/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSRepositoryPropertiesPage.java +++ b/bundles/org.eclipse.team.cvs.ui/src/org/eclipse/team/internal/ccvs/ui/CVSRepositoryPropertiesPage.java @@ -1,311 +1,311 @@ /******************************************************************************* * Copyright (c) 2002 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM - Initial API and implementation ******************************************************************************/ package org.eclipse.team.internal.ccvs.ui; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.dialogs.ProgressMonitorDialog; import org.eclipse.jface.operation.IRunnableWithProgress; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Text; import org.eclipse.team.core.RepositoryProvider; import org.eclipse.team.core.TeamException; import org.eclipse.team.internal.ccvs.core.CVSProviderPlugin; import org.eclipse.team.internal.ccvs.core.CVSTeamProvider; import org.eclipse.team.internal.ccvs.core.ICVSRepositoryLocation; import org.eclipse.team.internal.ccvs.core.IUserInfo; import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation; import org.eclipse.ui.dialogs.PropertyPage; public class CVSRepositoryPropertiesPage extends PropertyPage { ICVSRepositoryLocation location; // Widgets Text userText; Text passwordText; Combo methodType; Label hostLabel; Label pathLabel; Label portLabel; boolean passwordChanged; boolean connectionInfoChanged; IUserInfo info; /* * @see PreferencesPage#createContents */ protected Control createContents(Composite parent) { initialize(); Composite composite = new Composite(parent, SWT.NULL); composite.setLayoutData(new GridData(GridData.FILL_BOTH)); GridLayout layout = new GridLayout(); layout.numColumns = 3; composite.setLayout(layout); Label label = createLabel(composite, Policy.bind("CVSPropertiesPage.connectionType"), 1); //$NON-NLS-1$ methodType = createCombo(composite); label = createLabel(composite, Policy.bind("CVSPropertiesPage.user"), 1); //$NON-NLS-1$ userText = createTextField(composite); label = createLabel(composite, Policy.bind("CVSPropertiesPage.password"), 1); //$NON-NLS-1$ passwordText = createTextField(composite); passwordText.setEchoChar('*'); label = createLabel(composite, Policy.bind("CVSPropertiesPage.host"), 1); //$NON-NLS-1$ hostLabel = createLabel(composite, "", 2); //$NON-NLS-1$ label = createLabel(composite, Policy.bind("CVSPropertiesPage.port"), 1); //$NON-NLS-1$ portLabel = createLabel(composite, "", 2); //$NON-NLS-1$ label = createLabel(composite, Policy.bind("CVSPropertiesPage.path"), 1); //$NON-NLS-1$ pathLabel = createLabel(composite, "", 2); //$NON-NLS-1$ initializeValues(); passwordText.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { passwordChanged = true; } }); userText.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { connectionInfoChanged = true; } }); methodType.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { connectionInfoChanged = true; } }); return composite; } /** * Utility method that creates a combo box * * @param parent the parent for the new label * @return the new widget */ protected Combo createCombo(Composite parent) { Combo combo = new Combo(parent, SWT.READ_ONLY); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; data.horizontalSpan = 2; combo.setLayoutData(data); return combo; } /** * Utility method that creates a label instance * and sets the default layout data. * * @param parent the parent for the new label * @param text the text for the new label * @return the new label */ protected Label createLabel(Composite parent, String text, int span) { Label label = new Label(parent, SWT.LEFT); label.setText(text); GridData data = new GridData(); data.horizontalSpan = span; data.horizontalAlignment = GridData.FILL; label.setLayoutData(data); return label; } /** * Create a text field specific for this application * * @param parent the parent of the new text field * @return the new text field */ protected Text createTextField(Composite parent) { Text text = new Text(parent, SWT.SINGLE | SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.verticalAlignment = GridData.CENTER; data.grabExcessVerticalSpace = false; data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; data.horizontalSpan = 2; text.setLayoutData(data); return text; } /** * Initializes the page */ private void initialize() { location = null; IAdaptable element = getElement(); if (element instanceof ICVSRepositoryLocation) { location = (ICVSRepositoryLocation)element; } else { Object adapter = element.getAdapter(ICVSRepositoryLocation.class); if (adapter instanceof ICVSRepositoryLocation) { location = (ICVSRepositoryLocation)adapter; } } } /** * Set the initial values of the widgets */ private void initializeValues() { passwordChanged = false; String[] methods = CVSProviderPlugin.getProvider().getSupportedConnectionMethods(); for (int i = 0; i < methods.length; i++) { methodType.add(methods[i]); } String method = location.getMethod().getName(); methodType.select(methodType.indexOf(method)); info = location.getUserInfo(true); userText.setText(info.getUsername()); passwordText.setText("*********"); //$NON-NLS-1$ hostLabel.setText(location.getHost()); int port = location.getPort(); if (port == ICVSRepositoryLocation.USE_DEFAULT_PORT) { portLabel.setText(Policy.bind("CVSPropertiesPage.defaultPort")); //$NON-NLS-1$ } else { portLabel.setText("" + port); //$NON-NLS-1$ } pathLabel.setText(location.getRootDirectory()); } /* * @see PreferencesPage#performOk */ public boolean performOk() { if (!connectionInfoChanged && !passwordChanged) { return true; } info.setUsername(userText.getText()); if (passwordChanged) { info.setPassword(passwordText.getText()); } final String type = methodType.getText(); final String password = passwordText.getText(); final boolean[] result = new boolean[] { false }; try { - new ProgressMonitorDialog(getShell()).run(true, false, new IRunnableWithProgress() { + new ProgressMonitorDialog(getShell()).run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // Check if the password was the only thing to change. if (passwordChanged && !connectionInfoChanged) { CVSRepositoryLocation oldLocation = (CVSRepositoryLocation)location; oldLocation.setPassword(password); oldLocation.updateCache(); result[0] = true; return; } // Create a new repository location with the new information CVSRepositoryLocation newLocation = CVSRepositoryLocation.fromString(location.getLocation()); newLocation.setMethod(type); newLocation.setUserInfo(info); // For each project shared with the old location, set connection info to the new one List projects = new ArrayList(); IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (int i = 0; i < allProjects.length; i++) { RepositoryProvider teamProvider = RepositoryProvider.getProvider(allProjects[i], CVSProviderPlugin.getTypeId()); if (teamProvider != null) { CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; if (cvsProvider.getCVSWorkspaceRoot().getRemoteLocation().equals(location)) { projects.add(allProjects[i]); break; } } } if (projects.size() > 0) { // To do: warn the user boolean r = MessageDialog.openConfirm(getShell(), Policy.bind("CVSRepositoryPropertiesPage.Confirm_Project_Sharing_Changes_1"), Policy.bind("CVSRepositoryPropertiesPage.There_are_projects_in_the_workspace_shared_with_this_repository._The_projects_will_be_updated_with_the_new_information_that_you_have_entered_2")); //$NON-NLS-1$ //$NON-NLS-2$ if (!r) { result[0] = false; return; } monitor.beginTask(null, 1000 * projects.size()); try { Iterator it = projects.iterator(); while (it.hasNext()) { IProject project = (IProject)it.next(); RepositoryProvider teamProvider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; cvsProvider.setRemoteRoot(newLocation, Policy.subMonitorFor(monitor, 1000)); } } finally { monitor.done(); } } // Dispose the old repository location CVSProviderPlugin.getProvider().disposeRepository(location); } catch (TeamException e) { throw new InvocationTargetException(e); } result[0] = true; } }); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof TeamException) { handle((TeamException)t); } else if (t instanceof CoreException) { handle(((CoreException)t).getStatus()); } else { IStatus status = new Status(IStatus.ERROR, CVSUIPlugin.ID, 1, Policy.bind("internal"), t); //$NON-NLS-1$ handle(status); CVSUIPlugin.log(status); } } catch (InterruptedException e) { } return result[0]; } /** * Shows the given errors to the user. */ protected void handle(TeamException e) { handle(e.getStatus()); } protected void handle(IStatus status) { if (!status.isOK()) { IStatus toShow = status; if (status.isMultiStatus()) { IStatus[] children = status.getChildren(); if (children.length == 1) { toShow = children[0]; } } ErrorDialog.openError(getShell(), status.getMessage(), null, toShow); } } }
true
true
public boolean performOk() { if (!connectionInfoChanged && !passwordChanged) { return true; } info.setUsername(userText.getText()); if (passwordChanged) { info.setPassword(passwordText.getText()); } final String type = methodType.getText(); final String password = passwordText.getText(); final boolean[] result = new boolean[] { false }; try { new ProgressMonitorDialog(getShell()).run(true, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // Check if the password was the only thing to change. if (passwordChanged && !connectionInfoChanged) { CVSRepositoryLocation oldLocation = (CVSRepositoryLocation)location; oldLocation.setPassword(password); oldLocation.updateCache(); result[0] = true; return; } // Create a new repository location with the new information CVSRepositoryLocation newLocation = CVSRepositoryLocation.fromString(location.getLocation()); newLocation.setMethod(type); newLocation.setUserInfo(info); // For each project shared with the old location, set connection info to the new one List projects = new ArrayList(); IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (int i = 0; i < allProjects.length; i++) { RepositoryProvider teamProvider = RepositoryProvider.getProvider(allProjects[i], CVSProviderPlugin.getTypeId()); if (teamProvider != null) { CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; if (cvsProvider.getCVSWorkspaceRoot().getRemoteLocation().equals(location)) { projects.add(allProjects[i]); break; } } } if (projects.size() > 0) { // To do: warn the user boolean r = MessageDialog.openConfirm(getShell(), Policy.bind("CVSRepositoryPropertiesPage.Confirm_Project_Sharing_Changes_1"), Policy.bind("CVSRepositoryPropertiesPage.There_are_projects_in_the_workspace_shared_with_this_repository._The_projects_will_be_updated_with_the_new_information_that_you_have_entered_2")); //$NON-NLS-1$ //$NON-NLS-2$ if (!r) { result[0] = false; return; } monitor.beginTask(null, 1000 * projects.size()); try { Iterator it = projects.iterator(); while (it.hasNext()) { IProject project = (IProject)it.next(); RepositoryProvider teamProvider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; cvsProvider.setRemoteRoot(newLocation, Policy.subMonitorFor(monitor, 1000)); } } finally { monitor.done(); } } // Dispose the old repository location CVSProviderPlugin.getProvider().disposeRepository(location); } catch (TeamException e) { throw new InvocationTargetException(e); } result[0] = true; } }); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof TeamException) { handle((TeamException)t); } else if (t instanceof CoreException) { handle(((CoreException)t).getStatus()); } else { IStatus status = new Status(IStatus.ERROR, CVSUIPlugin.ID, 1, Policy.bind("internal"), t); //$NON-NLS-1$ handle(status); CVSUIPlugin.log(status); } } catch (InterruptedException e) { } return result[0]; }
public boolean performOk() { if (!connectionInfoChanged && !passwordChanged) { return true; } info.setUsername(userText.getText()); if (passwordChanged) { info.setPassword(passwordText.getText()); } final String type = methodType.getText(); final String password = passwordText.getText(); final boolean[] result = new boolean[] { false }; try { new ProgressMonitorDialog(getShell()).run(false, false, new IRunnableWithProgress() { public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { // Check if the password was the only thing to change. if (passwordChanged && !connectionInfoChanged) { CVSRepositoryLocation oldLocation = (CVSRepositoryLocation)location; oldLocation.setPassword(password); oldLocation.updateCache(); result[0] = true; return; } // Create a new repository location with the new information CVSRepositoryLocation newLocation = CVSRepositoryLocation.fromString(location.getLocation()); newLocation.setMethod(type); newLocation.setUserInfo(info); // For each project shared with the old location, set connection info to the new one List projects = new ArrayList(); IProject[] allProjects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); for (int i = 0; i < allProjects.length; i++) { RepositoryProvider teamProvider = RepositoryProvider.getProvider(allProjects[i], CVSProviderPlugin.getTypeId()); if (teamProvider != null) { CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; if (cvsProvider.getCVSWorkspaceRoot().getRemoteLocation().equals(location)) { projects.add(allProjects[i]); break; } } } if (projects.size() > 0) { // To do: warn the user boolean r = MessageDialog.openConfirm(getShell(), Policy.bind("CVSRepositoryPropertiesPage.Confirm_Project_Sharing_Changes_1"), Policy.bind("CVSRepositoryPropertiesPage.There_are_projects_in_the_workspace_shared_with_this_repository._The_projects_will_be_updated_with_the_new_information_that_you_have_entered_2")); //$NON-NLS-1$ //$NON-NLS-2$ if (!r) { result[0] = false; return; } monitor.beginTask(null, 1000 * projects.size()); try { Iterator it = projects.iterator(); while (it.hasNext()) { IProject project = (IProject)it.next(); RepositoryProvider teamProvider = RepositoryProvider.getProvider(project, CVSProviderPlugin.getTypeId()); CVSTeamProvider cvsProvider = (CVSTeamProvider)teamProvider; cvsProvider.setRemoteRoot(newLocation, Policy.subMonitorFor(monitor, 1000)); } } finally { monitor.done(); } } // Dispose the old repository location CVSProviderPlugin.getProvider().disposeRepository(location); } catch (TeamException e) { throw new InvocationTargetException(e); } result[0] = true; } }); } catch (InvocationTargetException e) { Throwable t = e.getTargetException(); if (t instanceof TeamException) { handle((TeamException)t); } else if (t instanceof CoreException) { handle(((CoreException)t).getStatus()); } else { IStatus status = new Status(IStatus.ERROR, CVSUIPlugin.ID, 1, Policy.bind("internal"), t); //$NON-NLS-1$ handle(status); CVSUIPlugin.log(status); } } catch (InterruptedException e) { } return result[0]; }
diff --git a/testsuites/sparql/src/main/java/org/openrdf/query/parser/sparql/ManifestTest.java b/testsuites/sparql/src/main/java/org/openrdf/query/parser/sparql/ManifestTest.java index c69b18901..7ca093faf 100644 --- a/testsuites/sparql/src/main/java/org/openrdf/query/parser/sparql/ManifestTest.java +++ b/testsuites/sparql/src/main/java/org/openrdf/query/parser/sparql/ManifestTest.java @@ -1,158 +1,160 @@ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2008. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.query.parser.sparql; import java.io.IOException; import java.io.InputStream; import java.net.URL; import junit.framework.TestSuite; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.aduna.net.ParsedURI; import org.openrdf.OpenRDFUtil; import org.openrdf.model.Resource; import org.openrdf.model.ValueFactory; import org.openrdf.query.BindingSet; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQueryResult; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.repository.util.RDFInserter; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RDFParser; import org.openrdf.rio.turtle.TurtleParser; import org.openrdf.sail.memory.MemoryStore; public class ManifestTest { static final Logger logger = LoggerFactory.getLogger(ManifestTest.class); private static final boolean REMOTE = false; public static final String MANIFEST_FILE; static { if (REMOTE) { MANIFEST_FILE = "http://www.w3.org/2001/sw/DataAccess/tests/data-r2/manifest-evaluation.ttl"; } else { MANIFEST_FILE = ManifestTest.class.getResource( "/testcases-dawg/data-r2/manifest-evaluation.ttl") .toString(); } } public static TestSuite suite(SPARQLQueryTest.Factory factory) throws Exception { TestSuite suite = new TestSuite(factory.getClass().getName()); Repository manifestRep = new SailRepository(new MemoryStore()); manifestRep.initialize(); RepositoryConnection con = manifestRep.getConnection(); addTurtle(con, new URL(MANIFEST_FILE), MANIFEST_FILE); String query = "SELECT DISTINCT manifestFile " + "FROM {x} rdf:first {manifestFile} " + "USING NAMESPACE " + " mf = <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>, " + " qt = <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>"; TupleQueryResult manifestResults = con.prepareTupleQuery( QueryLanguage.SERQL, query, MANIFEST_FILE).evaluate(); while (manifestResults.hasNext()) { BindingSet bindingSet = manifestResults.next(); String manifestFile = bindingSet.getValue("manifestFile") .toString(); suite.addTest(SPARQLQueryTest.suite(manifestFile, factory)); } manifestResults.close(); con.close(); manifestRep.shutDown(); logger.info("Created aggregated test suite with " + suite.countTestCases() + " test cases."); return suite; } static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts) throws IOException, RepositoryException, RDFParseException { if (baseURI == null) { baseURI = url.toExternalForm(); } InputStream in = url.openStream(); try { OpenRDFUtil.verifyContextNotNull(contexts); final ValueFactory vf = con.getRepository().getValueFactory(); RDFParser rdfParser = new TurtleParser() { @Override protected void setBaseURI(final String uriSpec) { ParsedURI baseURI = new ParsedURI(uriSpec) { private boolean jarFile = uriSpec.startsWith("jar:file:"); private int idx = uriSpec.indexOf('!') + 1; - private ParsedURI file = new ParsedURI("file:" + private ParsedURI file = new ParsedURI("jar-file:" + uriSpec.substring(idx)); @Override public ParsedURI resolve(ParsedURI uri) { if (jarFile) { - String path = file.resolve(uri).toString() - .substring(5); - String c = uriSpec.substring(0, idx) + path; - return new ParsedURI(c); + String resolved = file.resolve(uri).toString(); + if (resolved.startsWith("jar-file:")) { + String path = resolved.substring("jar-file:".length()); + String c = uriSpec.substring(0, idx) + path; + return new ParsedURI(c); + } } return super.resolve(uri); } }; baseURI.normalize(); setBaseURI(baseURI); } }; rdfParser.setValueFactory(vf); rdfParser.setVerifyData(false); rdfParser.setStopAtFirstError(true); rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); RDFInserter rdfInserter = new RDFInserter(con); rdfInserter.enforceContext(contexts); rdfParser.setRDFHandler(rdfInserter); boolean autoCommit = con.isAutoCommit(); con.setAutoCommit(false); try { rdfParser.parse(in, baseURI); } catch (RDFHandlerException e) { if (autoCommit) { con.rollback(); } // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); } catch (RuntimeException e) { if (autoCommit) { con.rollback(); } throw e; } finally { con.setAutoCommit(autoCommit); } } finally { in.close(); } } }
false
true
static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts) throws IOException, RepositoryException, RDFParseException { if (baseURI == null) { baseURI = url.toExternalForm(); } InputStream in = url.openStream(); try { OpenRDFUtil.verifyContextNotNull(contexts); final ValueFactory vf = con.getRepository().getValueFactory(); RDFParser rdfParser = new TurtleParser() { @Override protected void setBaseURI(final String uriSpec) { ParsedURI baseURI = new ParsedURI(uriSpec) { private boolean jarFile = uriSpec.startsWith("jar:file:"); private int idx = uriSpec.indexOf('!') + 1; private ParsedURI file = new ParsedURI("file:" + uriSpec.substring(idx)); @Override public ParsedURI resolve(ParsedURI uri) { if (jarFile) { String path = file.resolve(uri).toString() .substring(5); String c = uriSpec.substring(0, idx) + path; return new ParsedURI(c); } return super.resolve(uri); } }; baseURI.normalize(); setBaseURI(baseURI); } }; rdfParser.setValueFactory(vf); rdfParser.setVerifyData(false); rdfParser.setStopAtFirstError(true); rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); RDFInserter rdfInserter = new RDFInserter(con); rdfInserter.enforceContext(contexts); rdfParser.setRDFHandler(rdfInserter); boolean autoCommit = con.isAutoCommit(); con.setAutoCommit(false); try { rdfParser.parse(in, baseURI); } catch (RDFHandlerException e) { if (autoCommit) { con.rollback(); } // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); } catch (RuntimeException e) { if (autoCommit) { con.rollback(); } throw e; } finally { con.setAutoCommit(autoCommit); } } finally { in.close(); } }
static void addTurtle(RepositoryConnection con, URL url, String baseURI, Resource... contexts) throws IOException, RepositoryException, RDFParseException { if (baseURI == null) { baseURI = url.toExternalForm(); } InputStream in = url.openStream(); try { OpenRDFUtil.verifyContextNotNull(contexts); final ValueFactory vf = con.getRepository().getValueFactory(); RDFParser rdfParser = new TurtleParser() { @Override protected void setBaseURI(final String uriSpec) { ParsedURI baseURI = new ParsedURI(uriSpec) { private boolean jarFile = uriSpec.startsWith("jar:file:"); private int idx = uriSpec.indexOf('!') + 1; private ParsedURI file = new ParsedURI("jar-file:" + uriSpec.substring(idx)); @Override public ParsedURI resolve(ParsedURI uri) { if (jarFile) { String resolved = file.resolve(uri).toString(); if (resolved.startsWith("jar-file:")) { String path = resolved.substring("jar-file:".length()); String c = uriSpec.substring(0, idx) + path; return new ParsedURI(c); } } return super.resolve(uri); } }; baseURI.normalize(); setBaseURI(baseURI); } }; rdfParser.setValueFactory(vf); rdfParser.setVerifyData(false); rdfParser.setStopAtFirstError(true); rdfParser.setDatatypeHandling(RDFParser.DatatypeHandling.IGNORE); RDFInserter rdfInserter = new RDFInserter(con); rdfInserter.enforceContext(contexts); rdfParser.setRDFHandler(rdfInserter); boolean autoCommit = con.isAutoCommit(); con.setAutoCommit(false); try { rdfParser.parse(in, baseURI); } catch (RDFHandlerException e) { if (autoCommit) { con.rollback(); } // RDFInserter only throws wrapped RepositoryExceptions throw (RepositoryException) e.getCause(); } catch (RuntimeException e) { if (autoCommit) { con.rollback(); } throw e; } finally { con.setAutoCommit(autoCommit); } } finally { in.close(); } }
diff --git a/src/com/android/contacts/datepicker/DatePicker.java b/src/com/android/contacts/datepicker/DatePicker.java index fe234152..d0510ab4 100644 --- a/src/com/android/contacts/datepicker/DatePicker.java +++ b/src/com/android/contacts/datepicker/DatePicker.java @@ -1,491 +1,489 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.datepicker; // This is a fork of the standard Android DatePicker that additionally allows toggling the year // on/off. It uses some private API so that not everything has to be copied. import android.animation.LayoutTransition; import android.annotation.Widget; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.text.format.DateFormat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.NumberPicker.OnValueChangeListener; import com.android.contacts.R; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; /** * A view for selecting a month / year / day based on a calendar like layout. * * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-datepicker.html">Date Picker * tutorial</a>.</p> * * For a dialog using this view, see {@link android.app.DatePickerDialog}. */ @Widget public class DatePicker extends FrameLayout { /** Magic year that represents "no year" */ public static int NO_YEAR = 0; private static final int DEFAULT_START_YEAR = 1900; private static final int DEFAULT_END_YEAR = 2100; /* UI Components */ private final LinearLayout mPickerContainer; private final CheckBox mYearToggle; private final NumberPicker mDayPicker; private final NumberPicker mMonthPicker; private final NumberPicker mYearPicker; /** * How we notify users the date has changed. */ private OnDateChangedListener mOnDateChangedListener; private int mDay; private int mMonth; private int mYear; private boolean mYearOptional; private boolean mHasYear; /** * The callback used to indicate the user changes the date. */ public interface OnDateChangedListener { /** * @param view The view associated with this listener. * @param year The year that was set or {@link DatePicker#NO_YEAR} if no year was set * @param monthOfYear The month that was set (0-11) for compatibility * with {@link java.util.Calendar}. * @param dayOfMonth The day of the month that was set. */ void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth); } public DatePicker(Context context) { this(context, null); } public DatePicker(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } - mMonthPicker.setMinValue(1); - mMonthPicker.setMaxValue(12); } else { - mMonthPicker.setMinValue(1); - mMonthPicker.setMaxValue(12); mMonthPicker.setDisplayedValues(months); } + mMonthPicker.setMinValue(1); + mMonthPicker.setMaxValue(12); mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); mDayPicker.setEnabled(enabled); mMonthPicker.setEnabled(enabled); mYearPicker.setEnabled(enabled); } private void reorderPickers(String[] months) { java.text.DateFormat format; String order; /* * If the user is in a locale where the medium date format is * still numeric (Japanese and Czech, for example), respect * the date format order setting. Otherwise, use the order * that the locale says is appropriate for a spelled-out date. */ if (months[0].startsWith("1")) { format = DateFormat.getDateFormat(getContext()); } else { format = DateFormat.getMediumDateFormat(getContext()); } if (format instanceof SimpleDateFormat) { order = ((SimpleDateFormat) format).toPattern(); } else { // Shouldn't happen, but just in case. order = new String(DateFormat.getDateFormatOrder(getContext())); } /* Remove the 3 pickers from their parent and then add them back in the * required order. */ mPickerContainer.removeAllViews(); boolean quoted = false; boolean didDay = false, didMonth = false, didYear = false; for (int i = 0; i < order.length(); i++) { char c = order.charAt(i); if (c == '\'') { quoted = !quoted; } if (!quoted) { if (c == DateFormat.DATE && !didDay) { mPickerContainer.addView(mDayPicker); didDay = true; } else if ((c == DateFormat.MONTH || c == 'L') && !didMonth) { mPickerContainer.addView(mMonthPicker); didMonth = true; } else if (c == DateFormat.YEAR && !didYear) { mPickerContainer.addView (mYearPicker); didYear = true; } } } // Shouldn't happen, but just in case. if (!didMonth) { mPickerContainer.addView(mMonthPicker); } if (!didDay) { mPickerContainer.addView(mDayPicker); } if (!didYear) { mPickerContainer.addView(mYearPicker); } } public void updateDate(int year, int monthOfYear, int dayOfMonth) { if (mYear != year || mMonth != monthOfYear || mDay != dayOfMonth) { mYear = (mYearOptional && year == NO_YEAR) ? getCurrentYear() : year; mMonth = monthOfYear; mDay = dayOfMonth; updateSpinners(); reorderPickers(new DateFormatSymbols().getShortMonths()); notifyDateChanged(); } } private int getCurrentYear() { return Calendar.getInstance().get(Calendar.YEAR); } private static class SavedState extends BaseSavedState { private final int mYear; private final int mMonth; private final int mDay; private final boolean mHasYear; private final boolean mYearOptional; /** * Constructor called from {@link DatePicker#onSaveInstanceState()} */ private SavedState(Parcelable superState, int year, int month, int day, boolean hasYear, boolean yearOptional) { super(superState); mYear = year; mMonth = month; mDay = day; mHasYear = hasYear; mYearOptional = yearOptional; } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); mYear = in.readInt(); mMonth = in.readInt(); mDay = in.readInt(); mHasYear = in.readInt() != 0; mYearOptional = in.readInt() != 0; } public int getYear() { return mYear; } public int getMonth() { return mMonth; } public int getDay() { return mDay; } public boolean hasYear() { return mHasYear; } public boolean isYearOptional() { return mYearOptional; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(mYear); dest.writeInt(mMonth); dest.writeInt(mDay); dest.writeInt(mHasYear ? 1 : 0); dest.writeInt(mYearOptional ? 1 : 0); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * Override so we are in complete control of save / restore for this widget. */ @Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { dispatchThawSelfOnly(container); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); return new SavedState(superState, mYear, mMonth, mDay, mHasYear, mYearOptional); } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mYear = ss.getYear(); mMonth = ss.getMonth(); mDay = ss.getDay(); mHasYear = ss.hasYear(); mYearOptional = ss.isYearOptional(); updateSpinners(); } /** * Initialize the state. * @param year The initial year. * @param monthOfYear The initial month. * @param dayOfMonth The initial day of the month. * @param onDateChangedListener How user is notified date is changed by user, can be null. */ public void init(int year, int monthOfYear, int dayOfMonth, OnDateChangedListener onDateChangedListener) { init(year, monthOfYear, dayOfMonth, false, onDateChangedListener); } /** * Initialize the state. * @param year The initial year or {@link #NO_YEAR} if no year has been specified * @param monthOfYear The initial month. * @param dayOfMonth The initial day of the month. * @param yearOptional True if the user can toggle the year * @param onDateChangedListener How user is notified date is changed by user, can be null. */ public void init(int year, int monthOfYear, int dayOfMonth, boolean yearOptional, OnDateChangedListener onDateChangedListener) { mYear = (yearOptional && year == NO_YEAR) ? getCurrentYear() : year; mMonth = monthOfYear; mDay = dayOfMonth; mYearOptional = yearOptional; mHasYear = yearOptional ? (year != NO_YEAR) : true; mOnDateChangedListener = onDateChangedListener; updateSpinners(); } private void updateSpinners() { updateDaySpinner(); mYearToggle.setChecked(mHasYear); mYearToggle.setVisibility(mYearOptional ? View.VISIBLE : View.GONE); mYearPicker.setValue(mYear); mYearPicker.setVisibility(mHasYear ? View.VISIBLE : View.GONE); /* The month display uses 1-12 but our internal state stores it * 0-11 so add one when setting the display. */ mMonthPicker.setValue(mMonth + 1); } private void updateDaySpinner() { Calendar cal = Calendar.getInstance(); // if year was not set, use 2000 as it was a leap year cal.set(mHasYear ? mYear : 2000, mMonth, 1); int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH); mDayPicker.setMinValue(1); mDayPicker.setMaxValue(max); mDayPicker.setValue(mDay); } public int getYear() { return (mYearOptional && !mHasYear) ? NO_YEAR : mYear; } public boolean isYearOptional() { return mYearOptional; } public int getMonth() { return mMonth; } public int getDayOfMonth() { return mDay; } private void adjustMaxDay(){ Calendar cal = Calendar.getInstance(); // if year was not set, use 2000 as it was a leap year cal.set(Calendar.YEAR, mHasYear ? mYear : 2000); cal.set(Calendar.MONTH, mMonth); int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (mDay > max) { mDay = max; } } private void notifyDateChanged() { if (mOnDateChangedListener != null) { int year = (mYearOptional && !mHasYear) ? NO_YEAR : mYear; mOnDateChangedListener.onDateChanged(DatePicker.this, year, mMonth, mDay); } } }
false
true
public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); } else { mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); mMonthPicker.setDisplayedValues(months); } mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } }
public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } } else { mMonthPicker.setDisplayedValues(months); } mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } }
diff --git a/src/java/org/apache/fop/fonts/type1/PFMInputStream.java b/src/java/org/apache/fop/fonts/type1/PFMInputStream.java index 85f39b6f3..f563059c3 100644 --- a/src/java/org/apache/fop/fonts/type1/PFMInputStream.java +++ b/src/java/org/apache/fop/fonts/type1/PFMInputStream.java @@ -1,113 +1,113 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* $Id$ */ package org.apache.fop.fonts.type1; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.DataInputStream; import java.io.InputStreamReader; /** * This is a helper class for reading PFM files. It defines functions for * extracting specific values out of the stream. */ public class PFMInputStream extends java.io.FilterInputStream { private final DataInputStream datain; /** * Constructs a PFMInputStream based on an InputStream representing the * PFM file. * * @param in The stream from which to read the PFM file */ public PFMInputStream(InputStream in) { super(in); datain = new DataInputStream(in); } /** * Parses a one byte value out of the stream. * * @return The value extracted * @throws IOException In case of an I/O problem */ public short readByte() throws IOException { short s = datain.readByte(); // Now, we've got to trick Java into forgetting the sign int s1 = (((s & 0xF0) >>> 4) << 4) + (s & 0x0F); return (short)s1; } /** * Parses a two byte value out of the stream. * * @return The value extracted * @throws IOException In case of an I/O problem */ public int readShort() throws IOException { int i = datain.readShort(); // Change byte order int high = (i & 0xFF00) >>> 8; int low = (i & 0x00FF) << 8; return low + high; } /** * Parses a four byte value out of the stream. * * @return The value extracted * @throws IOException In case of an I/O problem */ public long readInt() throws IOException { int i = datain.readInt(); // Change byte order int i1 = (i & 0xFF000000) >>> 24; int i2 = (i & 0x00FF0000) >>> 8; int i3 = (i & 0x0000FF00) << 8; int i4 = (i & 0x000000FF) << 24; return i1 + i2 + i3 + i4; } /** * Parses a zero-terminated string out of the stream. * * @return The value extracted * @throws IOException In case of an I/O problem */ public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); - while (ch != 0) { + while (ch > 0) { buf.append((char)ch); ch = reader.read(); - if (ch == -1) { - throw new EOFException("Unexpected end of stream reached"); - } + } + if (ch == -1) { + throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); } }
false
true
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch != 0) { buf.append((char)ch); ch = reader.read(); if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } } return buf.toString(); }
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch > 0) { buf.append((char)ch); ch = reader.read(); } if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); }
diff --git a/src/VASSAL/tools/image/ImageUtils.java b/src/VASSAL/tools/image/ImageUtils.java index ce54593c..4f399520 100644 --- a/src/VASSAL/tools/image/ImageUtils.java +++ b/src/VASSAL/tools/image/ImageUtils.java @@ -1,655 +1,655 @@ /* * $Id$ * * Copyright (c) 2007-2009 by Joel Uckelman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License (LGPL) as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, copies are available * at http://www.opensource.org. */ package VASSAL.tools.image; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorConvertOp; import java.awt.image.PixelGrabber; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import javax.imageio.stream.MemoryCacheImageInputStream; import javax.swing.ImageIcon; import org.jdesktop.swingx.graphics.GraphicsUtilities; import VASSAL.build.BadDataReport; import VASSAL.tools.ErrorDialog; import VASSAL.tools.image.memmap.MappedBufferedImage; import VASSAL.tools.imageop.Op; import VASSAL.tools.io.IOUtils; import VASSAL.tools.io.RereadableInputStream; public class ImageUtils { private ImageUtils() {} // negative, because historically we've done it this way private static final double DEGTORAD = -Math.PI/180.0; public static final BufferedImage NULL_IMAGE = createCompatibleImage(1,1); private static final GeneralFilter.Filter upscale = new GeneralFilter.MitchellFilter(); private static final GeneralFilter.Filter downscale = new GeneralFilter.Lanczos3Filter(); public static final String PREFER_MEMORY_MAPPED = "preferMemoryMapped"; //$NON-NLS-1$ private static final int MAPPED = 0; private static final int RAM = 1; private static int largeImageLoadMethod = RAM; public static boolean useMappedImages() { return largeImageLoadMethod == MAPPED; } public static final String SCALER_ALGORITHM = "scalerAlgorithm"; //$NON-NLS-1$ private static final int MEDIUM = 1; private static final int GOOD = 2; private static int scalingQuality = GOOD; private static final Map<RenderingHints.Key,Object> defaultHints = new HashMap<RenderingHints.Key,Object>(); static { // Initialise Image prefs prior to Preferences being read. setPreferMemoryMappedFiles(false); setHighQualityScaling(true); // set up map for creating default RenderingHints defaultHints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); defaultHints.put(RenderingClues.KEY_EXT_INTERPOLATION, RenderingClues.VALUE_INTERPOLATION_LANCZOS_MITCHELL); defaultHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); } public static void setPreferMemoryMappedFiles(boolean b) { largeImageLoadMethod = b ? MAPPED : RAM; } public static void setHighQualityScaling(boolean b) { final int newQual = b ? GOOD : MEDIUM; if (newQual != scalingQuality) { scalingQuality = newQual; Op.clearCache(); defaultHints.put(RenderingClues.KEY_EXT_INTERPOLATION, scalingQuality == GOOD ? RenderingClues.VALUE_INTERPOLATION_LANCZOS_MITCHELL : RenderingClues.VALUE_INTERPOLATION_BILINEAR); } } public static RenderingHints getDefaultHints() { return new RenderingClues(defaultHints); } public static Rectangle transform(Rectangle srect, double scale, double angle) { final AffineTransform t = AffineTransform.getRotateInstance( DEGTORAD*angle, srect.getCenterX(), srect.getCenterY()); t.scale(scale, scale); return t.createTransformedShape(srect).getBounds(); } public static BufferedImage transform(BufferedImage src, double scale, double angle) { return transform(src, scale, angle, getDefaultHints(), scalingQuality); } public static BufferedImage transform(BufferedImage src, double scale, double angle, RenderingHints hints) { return transform(src, scale, angle, hints, scalingQuality); } public static BufferedImage transform(BufferedImage src, double scale, double angle, RenderingHints hints, int quality) { // bail on null source if (src == null) return null; // nothing to do, return source if (scale == 1.0 && angle == 0.0) { return src; } // return null image if scaling makes source vanish if (src.getWidth() * scale == 0 || src.getHeight() * scale == 0) { return NULL_IMAGE; } // use the default hints if we weren't given any if (hints == null) hints = getDefaultHints(); if (scale == 1.0 && angle % 90.0 == 0.0) { // this is an unscaled quadrant rotation, we can do this simply hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, src.getTransparency() != BufferedImage.OPAQUE ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } else if (hints.get(RenderingClues.KEY_EXT_INTERPOLATION) == RenderingClues.VALUE_INTERPOLATION_LANCZOS_MITCHELL) { // do high-quality scaling if (angle != 0.0) { final Rectangle ubox = getBounds(src); // FIXME: this duplicates the standard scaling case // FIXME: check whether AffineTransformOp is faster final Rectangle rbox = transform(ubox, 1.0, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage rot = new BufferedImage( rbox.width, rbox.height, src.getTransparency() == BufferedImage.OPAQUE && angle % 90.0 == 0.0 ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB ); // FIXME: rotation via bilinear interpolation probably decreases quality final AffineTransform tx = new AffineTransform(); tx.translate(-rbox.x, -rbox.y); tx.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); tx.translate(ubox.x, ubox.y); final Graphics2D g = rot.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, tx, null); g.dispose(); src = rot; } else { src = coerceToIntType(src); } final Rectangle sbox = transform(getBounds(src), scale, 0.0); return GeneralFilter.zoom(sbox, src, scale > 1.0 ? upscale : downscale); } else { // do standard scaling final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, - src.getTransparency() == BufferedImage.OPAQUE && angle % 90.0 == 0.0 + src.getTransparency() != BufferedImage.OPAQUE || angle % 90.0 != 0.0 ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } } @SuppressWarnings("fallthrough") public static BufferedImage coerceToIntType(BufferedImage img) { // ensure that img is a type which GeneralFilter can handle switch (img.getType()) { case BufferedImage.TYPE_INT_RGB: case BufferedImage.TYPE_INT_ARGB: return img; case BufferedImage.TYPE_CUSTOM: if (img instanceof MappedBufferedImage) return img; default: return toType(img, img.getTransparency() == BufferedImage.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB); } } /** * @param im * @return the boundaries of this image, where (0,0) is the * pseudo-center of the image */ public static Rectangle getBounds(BufferedImage im) { return new Rectangle(-im.getWidth()/2, -im.getHeight()/2, im.getWidth(), im.getHeight()); } public static Rectangle getBounds(Dimension d) { return new Rectangle(-d.width / 2, -d.height / 2, d.width, d.height); } @Deprecated public static Dimension getImageSize(InputStream in) throws IOException { final ImageInputStream stream = new MemoryCacheImageInputStream(in); try { final Iterator<ImageReader> i = ImageIO.getImageReaders(stream); if (!i.hasNext()) throw new UnrecognizedImageTypeException(); final ImageReader reader = i.next(); try { reader.setInput(stream); final Dimension size = new Dimension(reader.getWidth(0), reader.getHeight(0)); in.close(); return size; } finally { reader.dispose(); } } finally { IOUtils.closeQuietly(in); } } public static Dimension getImageSize(String name, InputStream in) throws ImageIOException { try { final ImageInputStream stream = new MemoryCacheImageInputStream(in); final Iterator<ImageReader> i = ImageIO.getImageReaders(stream); if (!i.hasNext()) throw new UnrecognizedImageTypeException(name); final ImageReader reader = i.next(); try { reader.setInput(stream); Dimension size = null; try { size = new Dimension(reader.getWidth(0), reader.getHeight(0)); } catch (IllegalArgumentException e) { // Note: ImageIO can throw IllegalArgumentExceptions for certain // kinds of broken images, e.g., JPEGs which are in the RGB color // space but have non-RGB color profiles (see Bug 2673589 for an // example of this). This problem is noted in Sun Bug 6404011, // // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6404011 // // and supposedly is fixed in 1.6.0 JVMs. Once we move to Java 6, // this will no longer be a problem, and we can remove this catch. // // We catch IllegalArgumentException here in a last-ditch effort // to prevent broken images---which are bad data, not bugs---from // causing an uncaught exception and raising a Bug Dialog. ErrorDialog.dataError(new BadDataReport("Broken image", name)); throw (IOException) new IOException().initCause(e); } in.close(); return size; } finally { reader.dispose(); } } catch (IOException e) { throw new ImageIOException(name, e); } finally { IOUtils.closeQuietly(in); } } /** * @deprecated Use {@link #getImage(String,InputStream)} instead. */ @Deprecated public static BufferedImage getImage(InputStream in) throws IOException { final BufferedImage img = ImageIO.read(new MemoryCacheImageInputStream(in)); if (img == null) throw new UnrecognizedImageTypeException(); return toCompatibleImage(img); } private static final boolean iTXtBug; static { final String jvmver = System.getProperty("java.version"); iTXtBug = jvmver == null || jvmver.startsWith("1.5.0"); } public static boolean useImageIO(InputStream in) throws IOException { final DataInputStream din = new DataInputStream(in); // Bail immediately if this stream is not a PNG. if (!PNGDecoder.decodeSignature(din)) return true; // Numbers in comments after chunk cases here refer to sections in the // PNG standard, found at http://www.w3.org/TR/PNG/ PNGDecoder.Chunk ch = PNGDecoder.decodeChunk(din); // This is not a PNG if IHDR is not the first chunk. if (ch.type != PNGDecoder.IHDR) return true; // Check whether this is an 8-bit-per-channel Truecolor image if (ch.data[8] != 8 || ch.data[9] != 2) { // // ImageIO in Java 1.5 fails to handle iTXt chunks properly, so we // must check whether this is a 1.5 JVM. If so, we cannot use ImageIO // to load this PNG. // // See Sun Bug 6541476, at // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6541476 // return !iTXtBug; } // IHDR is required to be first, and tRNS is required to appear before // the first IDAT chunk; therefore, if we find an IDAT we're done. while (true) { ch = PNGDecoder.decodeChunk(din); /* System.out.println(new char[]{ (char)((ch.type >> 24) & 0xff), (char)((ch.type >> 16) & 0xff), (char)((ch.type >> 8) & 0xff), (char)(ch.type & 0xff) }); */ switch (ch.type) { case PNGDecoder.tRNS: // 11.3.2 return false; case PNGDecoder.IDAT: // 12.2.4 return true; default: } } } public static BufferedImage getImageResource(String name) throws ImageIOException { final InputStream in = ImageUtils.class.getResourceAsStream(name); if (in == null) throw new ImageNotFoundException(name); return getImage(name, in); } public static BufferedImage getImage(String name, InputStream in) throws ImageIOException { // FIXME: At present, ImageIO does not honor the tRNS chunk in 8-bit // color type 2 (RGB) PNGs. This is not a bug per se, as the PNG // standard the does not require compliant decoders to use ancillary // chunks. However, every other PNG decoder we can find *does* honor // the tRNS chunk for this type of image, and so the appearance for // users is that VASSAL is broken when their 8-bit RGB PNGs don't show // the correct transparency. // // Therefore, we provide a workaround: Check the image metadata to see // whether we have an image which ImageIO will not handle fully, and if // we find one, load it using Toolkit.createImage() instead. // // Someday, when both ImageIO is fixed and everyone's JRE contains // that fix, we can once again do this the simple way: // // final BufferedImage img = // ImageIO.read(new MemoryCacheImageInputStream(in)); // if (img == null) throw new UnrecognizedImageTypeException(); // return toCompatibleImage(img); // // See Sun Bug 6788458, at // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6788458 // // Additionally, Toolkit.createImage() is unforgiving about malformed // PNGs, but instead of throwing an exception or returning null, it // returns a useless Image with negative width and height. (Though it // might also print a stack trace to the log.) There is at least one // piece of software (SplitImage) which writes tRNS chunks for type 2 // images which are only 3 bytes long, and because this kind of thing // is used by module designers for slicing up scans of countersheets, // we can expect to see such crap from time to time. Therefore, if // Toolkit.createImage() fails, we fallback to ImageIO.read() and hope // for the best. // BufferedImage img = null; RereadableInputStream rin = null; try { rin = new RereadableInputStream(in); rin.mark(512); final boolean useToolkit = !useImageIO(rin); rin.reset(); if (useToolkit) { rin.mark(4096); // Load the Image; note that we forceLoad() to ensure that the // subsequent calls to getWidth() and getHeight() return the // actual width and height of the Image. final Image i = forceLoad( Toolkit.getDefaultToolkit().createImage(IOUtils.toByteArray(rin)) ); // check that we received a valid Image from the Toolkit if (i.getWidth(null) > 0 && i.getHeight(null) > 0) { img = toBufferedImage(i); } else { // Toolkit failed for some reason. Probably this means that // we have a broken PNG, so gently notify the user and fallback // to ImageIO.read(). ErrorDialog.dataError(new BadDataReport("Broken PNG image", name)); rin.reset(); } } if (img == null) { try { img = ImageIO.read(new MemoryCacheImageInputStream(rin)); } catch (IllegalArgumentException e) { // Note: ImageIO can throw IllegalArgumentExceptions for certain // kinds of broken images, e.g., JPEGs which are in the RGB color // space but have non-RGB color profiles (see Bug 2673589 for an // example of this). This problem is noted in Sun Bug 6404011, // // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6404011 // // and supposedly is fixed in 1.6.0 JVMs. Once we move to Java 6, // this will no longer be a problem, and we can remove this catch. // // We catch IllegalArgumentException here in a last-ditch effort // to prevent broken images---which are bad data, not bugs---from // causing an uncaught exception and raising a Bug Dialog. ErrorDialog.dataError(new BadDataReport("Broken image", name)); throw (IOException) new IOException().initCause(e); } if (img == null) throw new UnrecognizedImageTypeException(); img = toCompatibleImage(img); } rin.close(); return img; } catch (UnrecognizedImageTypeException e) { throw new UnrecognizedImageTypeException(name, e); } catch (IOException e) { throw new ImageIOException(name, e); } finally { IOUtils.closeQuietly(rin); } } // FIXME: check speed private static BufferedImage colorConvertCopy(BufferedImage src, BufferedImage dst) { final ColorConvertOp op = new ColorConvertOp( src.getColorModel().getColorSpace(), dst.getColorModel().getColorSpace(), null); op.filter(src, dst); return dst; } public static BufferedImage toType(BufferedImage src, int type) { final BufferedImage dst = new BufferedImage(src.getWidth(), src.getHeight(), type); return colorConvertCopy(src, dst); } public static Image forceLoad(Image img) { // ensure that the image is loaded return new ImageIcon(img).getImage(); } public static boolean isTransparent(Image img) { // determine whether this image has an alpha channel final PixelGrabber pg = new PixelGrabber(img, 0, 0, 1, 1, false); try { pg.grabPixels(); } catch (InterruptedException e) { ErrorDialog.bug(e); } return pg.getColorModel().hasAlpha(); } /** * Transform an <code>Image</code> to a <code>BufferedImage</code>. * * @param src the <code>Image</code> to transform */ public static BufferedImage toBufferedImage(Image src) { if (src == null) return null; if (src instanceof BufferedImage) return toCompatibleImage((BufferedImage) src); // ensure that the image is loaded src = forceLoad(src); final BufferedImage dst = createCompatibleImage( src.getWidth(null), src.getHeight(null), isTransparent(src) ); final Graphics2D g = dst.createGraphics(); g.drawImage(src, 0, 0, null); g.dispose(); return dst; } public static BufferedImage createCompatibleImage(int w, int h) { return GraphicsUtilities.createCompatibleImage(w, h); } public static BufferedImage createCompatibleImage(int w, int h, boolean transparent) { return transparent ? GraphicsUtilities.createCompatibleTranslucentImage(w, h) : GraphicsUtilities.createCompatibleImage(w, h); } public static BufferedImage createCompatibleTranslucentImage(int w, int h) { return GraphicsUtilities.createCompatibleTranslucentImage(w, h); } public static BufferedImage toCompatibleImage(BufferedImage src) { return GraphicsUtilities.toCompatibleImage(src); } /* * What Image suffixes does Vassal know about? * Used by the MassPieceLoader to identify candidate images. */ public static final String GIF_SUFFIX = ".gif"; public static final String PNG_SUFFIX = ".png"; public static final String SVG_SUFFIX = ".svg"; public static final String JPG_SUFFIX = ".jpg"; public static final String JPEG_SUFFIX = ".jpeg"; public static final String[] IMAGE_SUFFIXES = new String[] { GIF_SUFFIX, PNG_SUFFIX, SVG_SUFFIX, JPG_SUFFIX, JPEG_SUFFIX }; public static boolean hasImageSuffix(String name) { final String s = name.toLowerCase(); for (String suffix : IMAGE_SUFFIXES) { if (s.endsWith(suffix)) { return true; } } return false; } public static String stripImageSuffix(String name) { final String s = name.toLowerCase(); for (String suffix : IMAGE_SUFFIXES) { if (s.endsWith(suffix)) { return name.substring(0, name.length()-suffix.length()); } } return name; } }
true
true
public static BufferedImage transform(BufferedImage src, double scale, double angle, RenderingHints hints, int quality) { // bail on null source if (src == null) return null; // nothing to do, return source if (scale == 1.0 && angle == 0.0) { return src; } // return null image if scaling makes source vanish if (src.getWidth() * scale == 0 || src.getHeight() * scale == 0) { return NULL_IMAGE; } // use the default hints if we weren't given any if (hints == null) hints = getDefaultHints(); if (scale == 1.0 && angle % 90.0 == 0.0) { // this is an unscaled quadrant rotation, we can do this simply hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, src.getTransparency() != BufferedImage.OPAQUE ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } else if (hints.get(RenderingClues.KEY_EXT_INTERPOLATION) == RenderingClues.VALUE_INTERPOLATION_LANCZOS_MITCHELL) { // do high-quality scaling if (angle != 0.0) { final Rectangle ubox = getBounds(src); // FIXME: this duplicates the standard scaling case // FIXME: check whether AffineTransformOp is faster final Rectangle rbox = transform(ubox, 1.0, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage rot = new BufferedImage( rbox.width, rbox.height, src.getTransparency() == BufferedImage.OPAQUE && angle % 90.0 == 0.0 ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB ); // FIXME: rotation via bilinear interpolation probably decreases quality final AffineTransform tx = new AffineTransform(); tx.translate(-rbox.x, -rbox.y); tx.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); tx.translate(ubox.x, ubox.y); final Graphics2D g = rot.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, tx, null); g.dispose(); src = rot; } else { src = coerceToIntType(src); } final Rectangle sbox = transform(getBounds(src), scale, 0.0); return GeneralFilter.zoom(sbox, src, scale > 1.0 ? upscale : downscale); } else { // do standard scaling final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, src.getTransparency() == BufferedImage.OPAQUE && angle % 90.0 == 0.0 ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } }
public static BufferedImage transform(BufferedImage src, double scale, double angle, RenderingHints hints, int quality) { // bail on null source if (src == null) return null; // nothing to do, return source if (scale == 1.0 && angle == 0.0) { return src; } // return null image if scaling makes source vanish if (src.getWidth() * scale == 0 || src.getHeight() * scale == 0) { return NULL_IMAGE; } // use the default hints if we weren't given any if (hints == null) hints = getDefaultHints(); if (scale == 1.0 && angle % 90.0 == 0.0) { // this is an unscaled quadrant rotation, we can do this simply hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, src.getTransparency() != BufferedImage.OPAQUE ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } else if (hints.get(RenderingClues.KEY_EXT_INTERPOLATION) == RenderingClues.VALUE_INTERPOLATION_LANCZOS_MITCHELL) { // do high-quality scaling if (angle != 0.0) { final Rectangle ubox = getBounds(src); // FIXME: this duplicates the standard scaling case // FIXME: check whether AffineTransformOp is faster final Rectangle rbox = transform(ubox, 1.0, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage rot = new BufferedImage( rbox.width, rbox.height, src.getTransparency() == BufferedImage.OPAQUE && angle % 90.0 == 0.0 ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB ); // FIXME: rotation via bilinear interpolation probably decreases quality final AffineTransform tx = new AffineTransform(); tx.translate(-rbox.x, -rbox.y); tx.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); tx.translate(ubox.x, ubox.y); final Graphics2D g = rot.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, tx, null); g.dispose(); src = rot; } else { src = coerceToIntType(src); } final Rectangle sbox = transform(getBounds(src), scale, 0.0); return GeneralFilter.zoom(sbox, src, scale > 1.0 ? upscale : downscale); } else { // do standard scaling final Rectangle ubox = getBounds(src); final Rectangle tbox = transform(ubox, scale, angle); // keep opaque destination for orthogonal rotation of an opaque source final BufferedImage trans = createCompatibleImage( tbox.width, tbox.height, src.getTransparency() != BufferedImage.OPAQUE || angle % 90.0 != 0.0 ); final AffineTransform t = new AffineTransform(); t.translate(-tbox.x, -tbox.y); t.rotate(DEGTORAD*angle, ubox.getCenterX(), ubox.getCenterY()); t.scale(scale, scale); t.translate(ubox.x, ubox.y); final Graphics2D g = trans.createGraphics(); g.setRenderingHints(hints); g.drawImage(src, t, null); g.dispose(); return trans; } }
diff --git a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ListRidget.java b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ListRidget.java index e5f5125ed..b2093827c 100644 --- a/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ListRidget.java +++ b/org.eclipse.riena.ui.ridgets.swt/src/org/eclipse/riena/internal/ui/ridgets/swt/ListRidget.java @@ -1,189 +1,192 @@ /******************************************************************************* * Copyright (c) 2007, 2012 compeople AG and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * compeople AG - initial API and implementation *******************************************************************************/ package org.eclipse.riena.internal.ui.ridgets.swt; import org.eclipse.jface.viewers.AbstractListViewer; import org.eclipse.jface.viewers.ListViewer; import org.eclipse.jface.viewers.StructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.List; import org.eclipse.riena.ui.ridgets.ISelectableRidget; import org.eclipse.riena.ui.ridgets.swt.AbstractListRidget; import org.eclipse.riena.ui.ridgets.swt.MarkerSupport; /** * Ridget for SWT {@link List} widgets. */ public class ListRidget extends AbstractListRidget { private ListViewer viewer; private StructuredViewerFilterHolder filterHolder; public ListRidget() { selectionTypeEnforcer = new SelectionTypeEnforcer(); } @Override protected void checkUIControl(final Object uiControl) { checkType(uiControl, List.class); } @Override public List getUIControl() { return (List) super.getUIControl(); } @Override protected int getUIControlSelectionIndex() { return getUIControl().getSelectionIndex(); } @Override protected int[] getUIControlSelectionIndices() { return getUIControl().getSelectionIndices(); } @Override protected int getUIControlItemCount() { return getUIControl().getItemCount(); } @Override protected void bindUIControl() { final List control = getUIControl(); if (control != null) { viewer = new ListViewer(control); if (hasViewerModel()) { configureViewer(viewer); } updateComparator(); updateEnabled(isEnabled()); control.addSelectionListener(selectionTypeEnforcer); getFilterHolder().activate(viewer); } } @Override protected void unbindUIControl() { super.unbindUIControl(); getFilterHolder().deactivate(viewer); final List control = getUIControl(); if (control != null) { control.removeSelectionListener(selectionTypeEnforcer); } viewer = null; } @Override protected AbstractListViewer getViewer() { return viewer; } @Override protected void updateEnabled(final boolean isEnabled) { final String savedBackgroundKey = "oldbg"; //$NON-NLS-1$ if (isEnabled) { if (hasViewer()) { refreshViewer(); disposeSelectionBindings(); createSelectionBindings(); final List list = viewer.getList(); - list.setBackground((Color) list.getData(savedBackgroundKey)); - list.setData(savedBackgroundKey, null); + final Color oldBackground = (Color) list.getData(savedBackgroundKey); + if (oldBackground != null) { + list.setBackground(oldBackground); + list.setData(savedBackgroundKey, null); + } } } else { disposeSelectionBindings(); if (hasViewer()) { refreshViewer(); final List list = viewer.getList(); if (MarkerSupport.isHideDisabledRidgetContent()) { list.deselectAll(); } list.setData(savedBackgroundKey, list.getBackground()); } } updateMarkers(); } @Override protected StructuredViewerFilterHolder getFilterHolder() { if (filterHolder == null) { filterHolder = new StructuredViewerFilterHolder(); } return filterHolder; } // helping classes // //////////////// /** * Enforces selection in the control: * <ul> * <li>disallows selection changes when the ridget is "output only"</li> * <li>disallows multiple selection is the selection type of the ridget is {@link ISelectableRidget.SelectionType#SINGLE}</li> * </ul> */ private final class SelectionTypeEnforcer extends SelectionAdapter { @Override public void widgetSelected(final SelectionEvent e) { final List control = (List) e.widget; if (isOutputOnly()) { revertSelection(control); } else if (SelectionType.SINGLE.equals(getSelectionType())) { if (control.getSelectionCount() > 1) { // ignore this event e.doit = false; selectFirstItem(control); } } } private void selectFirstItem(final List control) { // set selection to most recent item control.setSelection(control.getSelectionIndex()); // fire event final Event event = new Event(); event.type = SWT.Selection; event.doit = true; control.notifyListeners(SWT.Selection, event); } private void revertSelection(final List control) { control.setRedraw(false); try { // undo user selection when "output only" viewer.setSelection(new StructuredSelection(getSelection())); } finally { // redraw control to remove "cheese" that is caused when // using the keyboard to select the next row control.setRedraw(true); } } } /** * {@inheritDoc} * <p> * This Ridget only supports native tool tips (SWT tool tips). Because of this the method has no effect. */ public void setNativeToolTip(final boolean nativeToolTip) { // do nothing } }
true
true
protected void updateEnabled(final boolean isEnabled) { final String savedBackgroundKey = "oldbg"; //$NON-NLS-1$ if (isEnabled) { if (hasViewer()) { refreshViewer(); disposeSelectionBindings(); createSelectionBindings(); final List list = viewer.getList(); list.setBackground((Color) list.getData(savedBackgroundKey)); list.setData(savedBackgroundKey, null); } } else { disposeSelectionBindings(); if (hasViewer()) { refreshViewer(); final List list = viewer.getList(); if (MarkerSupport.isHideDisabledRidgetContent()) { list.deselectAll(); } list.setData(savedBackgroundKey, list.getBackground()); } } updateMarkers(); }
protected void updateEnabled(final boolean isEnabled) { final String savedBackgroundKey = "oldbg"; //$NON-NLS-1$ if (isEnabled) { if (hasViewer()) { refreshViewer(); disposeSelectionBindings(); createSelectionBindings(); final List list = viewer.getList(); final Color oldBackground = (Color) list.getData(savedBackgroundKey); if (oldBackground != null) { list.setBackground(oldBackground); list.setData(savedBackgroundKey, null); } } } else { disposeSelectionBindings(); if (hasViewer()) { refreshViewer(); final List list = viewer.getList(); if (MarkerSupport.isHideDisabledRidgetContent()) { list.deselectAll(); } list.setData(savedBackgroundKey, list.getBackground()); } } updateMarkers(); }
diff --git a/dailyemail/src/main/java/com/natepaulus/dailyemail/web/controller/AccountController.java b/dailyemail/src/main/java/com/natepaulus/dailyemail/web/controller/AccountController.java index 3442ce5..065fe7e 100644 --- a/dailyemail/src/main/java/com/natepaulus/dailyemail/web/controller/AccountController.java +++ b/dailyemail/src/main/java/com/natepaulus/dailyemail/web/controller/AccountController.java @@ -1,169 +1,169 @@ package com.natepaulus.dailyemail.web.controller; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import com.natepaulus.dailyemail.repository.DeliverySchedule; import com.natepaulus.dailyemail.repository.User; import com.natepaulus.dailyemail.web.domain.DeliveryTimeEntryForm; import com.natepaulus.dailyemail.web.service.interfaces.AccountService; /** * @author Nate * */ @Controller public class AccountController { @Autowired AccountService accountService; @RequestMapping(value = "/account", method = RequestMethod.GET) public ModelAndView displayAccountPage(@ModelAttribute("user") User user, @ModelAttribute("delTimeEntry") DeliveryTimeEntryForm delTimeEntry, HttpSession session, HttpServletRequest request) { Map<String, ?> map = RequestContextUtils.getInputFlashMap(request); Map<String, Object> model = new HashMap<String, Object>(); if (map != null) { user = accountService.calculateUserDisplayTime(user); for (DeliverySchedule ds : user.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } session.setAttribute("user", user); session.setAttribute("deliveryTimeEntry", delTimeEntry); model.put("user", user); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } else { User loggedInUser = (User) session.getAttribute("user"); loggedInUser = accountService .calculateUserDisplayTime(loggedInUser); - for (DeliverySchedule ds : user.getDeliveryTimes()) { + for (DeliverySchedule ds : loggedInUser.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } model.put("user", loggedInUser); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } } @RequestMapping(value = "/account/addNews", method = RequestMethod.POST) public String addNewsLink(@RequestParam String name, @RequestParam String url, HttpSession session, RedirectAttributes redirect) { User user = (User) session.getAttribute("user"); user = accountService.addNewsLink(url, name, user); redirect.addFlashAttribute("user", user); return "redirect:/account"; } @RequestMapping(value = "/account/weather", method = RequestMethod.POST) public String updateWeatherDeliveryPreference( @RequestParam int deliver_pref, RedirectAttributes redirect, HttpSession session) { User user = (User) session.getAttribute("user"); accountService.updateWeatherDeliveryPreference(deliver_pref, user); redirect.addFlashAttribute("user", user); return "redirect:/account"; } @RequestMapping(value = "/account/changezip", method = RequestMethod.POST) public String updateWeatherZipCode(@RequestParam String zipCode, HttpSession session, RedirectAttributes redirect) { User user = (User) session.getAttribute("user"); accountService.updateUserZipCode(user, zipCode); redirect.addFlashAttribute("user", user); return "redirect:/account"; } @RequestMapping(value = "/account/news", method = RequestMethod.POST) public String setIncludedNewsInformation( @RequestParam(required = false) String[] news, HttpSession session, RedirectAttributes redirect) { User user = (User) session.getAttribute("user"); if (news == null) { news = new String[1]; news[0] = "0"; } user = accountService.setIncludedNewsInformation(news, user); redirect.addFlashAttribute("user", user); return "redirect:/account"; } @RequestMapping(value = "/account/deleteNewsLink/{id}", method = RequestMethod.GET) public String deleteNewsLink(@PathVariable int id, HttpSession session, RedirectAttributes redirect) { User user = (User) session.getAttribute("user"); user = accountService.deleteNewsLink(id, user); redirect.addFlashAttribute("user", user); return "redirect:/account"; } @RequestMapping(value = "/account/delivery", method = RequestMethod.POST) public String updateDeliverySchedule( @Valid @ModelAttribute("deliveryTimeEntry") DeliveryTimeEntryForm deliveryTimeEntry, BindingResult result, RedirectAttributes redirect, HttpSession session, Model model) { User user = (User) session.getAttribute("user"); if(result.hasErrors()){ session.setAttribute("user", user); model.addAttribute("user", user); return "account"; } user = accountService.updateDeliverySchedule(deliveryTimeEntry, user); redirect.addFlashAttribute("user", user); redirect.addFlashAttribute("deliveryTimeEntry", deliveryTimeEntry); return "redirect:/account"; } }
true
true
public ModelAndView displayAccountPage(@ModelAttribute("user") User user, @ModelAttribute("delTimeEntry") DeliveryTimeEntryForm delTimeEntry, HttpSession session, HttpServletRequest request) { Map<String, ?> map = RequestContextUtils.getInputFlashMap(request); Map<String, Object> model = new HashMap<String, Object>(); if (map != null) { user = accountService.calculateUserDisplayTime(user); for (DeliverySchedule ds : user.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } session.setAttribute("user", user); session.setAttribute("deliveryTimeEntry", delTimeEntry); model.put("user", user); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } else { User loggedInUser = (User) session.getAttribute("user"); loggedInUser = accountService .calculateUserDisplayTime(loggedInUser); for (DeliverySchedule ds : user.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } model.put("user", loggedInUser); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } }
public ModelAndView displayAccountPage(@ModelAttribute("user") User user, @ModelAttribute("delTimeEntry") DeliveryTimeEntryForm delTimeEntry, HttpSession session, HttpServletRequest request) { Map<String, ?> map = RequestContextUtils.getInputFlashMap(request); Map<String, Object> model = new HashMap<String, Object>(); if (map != null) { user = accountService.calculateUserDisplayTime(user); for (DeliverySchedule ds : user.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } session.setAttribute("user", user); session.setAttribute("deliveryTimeEntry", delTimeEntry); model.put("user", user); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } else { User loggedInUser = (User) session.getAttribute("user"); loggedInUser = accountService .calculateUserDisplayTime(loggedInUser); for (DeliverySchedule ds : loggedInUser.getDeliveryTimes()) { if (ds.getDeliveryDay() == 0) { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekDayDisabled(ds.isDisabled()); delTimeEntry.setWeekDayTime(ds.getDisplayTime()); } else { delTimeEntry.setTimezone(ds.getTz()); delTimeEntry.setWeekEndDisabled(ds.isDisabled()); delTimeEntry.setWeekEndTime(ds.getDisplayTime()); } } model.put("user", loggedInUser); model.put("deliveryTimeEntry", delTimeEntry); return new ModelAndView("account", model); } }