com.thoughtworks.xstream.core.JVM Java Examples

The following examples show how to use com.thoughtworks.xstream.core.JVM. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ToAttributedValueConverter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Creates a new ToAttributedValueConverter instance.
 * 
 * @param type the type that is handled by this converter instance
 * @param mapper the mapper in use
 * @param reflectionProvider the reflection provider in use
 * @param lookup the converter lookup in use
 * @param valueFieldName the field defining the tag's value (may be null)
 * @param valueDefinedIn the type defining the field
 */
public ToAttributedValueConverter(
    final Class type, final Mapper mapper, final ReflectionProvider reflectionProvider,
    final ConverterLookup lookup, final String valueFieldName, Class valueDefinedIn) {
    this.type = type;
    this.mapper = mapper;
    this.reflectionProvider = reflectionProvider;
    this.lookup = lookup;

    if (valueFieldName == null) {
        valueField = null;
    } else {
        Field field = null;
        try {
            field = (valueDefinedIn != null ? valueDefinedIn : type)
                .getDeclaredField(valueFieldName);
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
        } catch (NoSuchFieldException e) {
            throw new IllegalArgumentException(e.getMessage() + ": " + valueFieldName);
        }
        this.valueField = field;
    }
    enumMapper = JVM.isVersion(5) ? UseAttributeForEnumMapper.createEnumMapper(mapper) : null;
}
 
Example #2
Source File: PureJavaReflectionProvider.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void validateFieldAccess(Field field) {
    if (Modifier.isFinal(field.getModifiers())) {
        if (JVM.isVersion(5)) {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
        } else {
            throw new ObjectAccessException("Invalid final field "
                    + field.getDeclaringClass().getName() + "." + field.getName());
        }
    }
}
 
Example #3
Source File: AnnotationMapper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    setupMappers();
    int max = in.readInt();
    arguments = new Object[max+2];
    for (int i = 0; i < max; i++ ) {
        arguments[i] = in.readObject();
        if (arguments[i] instanceof ClassLoaderReference) {
            arguments[max+1] = ((ClassLoaderReference)arguments[i]).getReference();
        }
    }
    arguments[max] = new JVM();
}
 
Example #4
Source File: TreeMapConverter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected void populateTreeMap(HierarchicalStreamReader reader, UnmarshallingContext context,
    TreeMap result, Comparator comparator) {
    boolean inFirstElement = comparator == NULL_MARKER;
    if (inFirstElement) {
        comparator = null;
    }
    SortedMap sortedMap = new PresortedMap(comparator != null && JVM.hasOptimizedTreeMapPutAll() ? comparator : null);
    if (inFirstElement) {
        // we are already within the first entry
        putCurrentEntryIntoMap(reader, context, result, sortedMap);
        reader.moveUp();
    }
    populateMap(reader, context, result, sortedMap);
    try {
        if (JVM.hasOptimizedTreeMapPutAll()) {
            if (comparator != null && comparatorField != null) {
                comparatorField.set(result, comparator); 
            }
            result.putAll(sortedMap); // internal optimization will not call comparator
        } else if (comparatorField != null) {
            comparatorField.set(result, sortedMap.comparator());
            result.putAll(sortedMap); // "sort" by index
            comparatorField.set(result, comparator); 
        } else {
            result.putAll(sortedMap); // will use comparator for already sorted map
        }
    } catch (final IllegalAccessException e) {
        throw new ObjectAccessException("Cannot set comparator of TreeMap", e);
    }
}
 
Example #5
Source File: AnnotationMapper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct an AnnotationMapper.
 * 
 * @param wrapped the next {@link Mapper} in the chain
 * @since 1.4.5
 */
public AnnotationMapper(
    final Mapper wrapped, final ConverterRegistry converterRegistry, final ConverterLookup converterLookup,
    final ClassLoaderReference classLoaderReference, final ReflectionProvider reflectionProvider) {
    super(wrapped);
    this.converterRegistry = converterRegistry;
    annotatedTypes.add(Object.class);
    setupMappers();
    locked = true;
    
    final ClassLoader classLoader = classLoaderReference.getReference();
    arguments = new Object[]{
        this, classLoaderReference, reflectionProvider, converterLookup, new JVM(),
        classLoader != null ? classLoader : new TypedNull(ClassLoader.class)};
}
 
Example #6
Source File: FieldDictionary.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void init() {
    dictionaryEntries = new HashMap();
    if (JVM.is15())
        try {
            fieldUtil = (FieldUtil)JVM.loadClassForName("com.thoughtworks.xstream.converters.reflection.FieldUtil15", true).newInstance();
        } catch (Exception e) {
            ;
        }
    if (fieldUtil == null)
        fieldUtil = new FieldUtil14();
}
 
Example #7
Source File: XStream.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Mapper buildMapper() {
    Mapper mapper = new DefaultMapper(classLoaderReference);
    if (useXStream11XmlFriendlyMapper()) {
        mapper = new XStream11XmlFriendlyMapper(mapper);
    }
    mapper = new DynamicProxyMapper(mapper);
    mapper = new PackageAliasingMapper(mapper);
    mapper = new ClassAliasingMapper(mapper);
    mapper = new ElementIgnoringMapper(mapper);
    mapper = new FieldAliasingMapper(mapper);
    mapper = new AttributeAliasingMapper(mapper);
    mapper = new SystemAttributeAliasingMapper(mapper);
    mapper = new ImplicitCollectionMapper(mapper, reflectionProvider);
    mapper = new OuterClassMapper(mapper);
    mapper = new ArrayMapper(mapper);
    mapper = new DefaultImplementationsMapper(mapper);
    mapper = new AttributeMapper(mapper, converterLookup, reflectionProvider);
    if (JVM.isVersion(5)) {
        mapper = buildMapperDynamically(
            "com.thoughtworks.xstream.mapper.EnumMapper", new Class[]{Mapper.class},
            new Object[]{mapper});
    }
    mapper = new LocalConversionMapper(mapper);
    mapper = new ImmutableTypesMapper(mapper);
    if (JVM.isVersion(8)) {
        mapper = buildMapperDynamically("com.thoughtworks.xstream.mapper.LambdaMapper", new Class[]{Mapper.class},
            new Object[]{mapper});
    }
    mapper = new SecurityMapper(mapper);
    if (JVM.isVersion(5)) {
        mapper = buildMapperDynamically(ANNOTATION_MAPPER_TYPE, new Class[]{
            Mapper.class, ConverterRegistry.class, ConverterLookup.class,
            ClassLoaderReference.class, ReflectionProvider.class}, new Object[]{
            mapper, converterRegistry, converterLookup, classLoaderReference,
            reflectionProvider});
    }
    mapper = wrapMapper((MapperWrapper)mapper);
    mapper = new CachingMapper(mapper);
    return mapper;
}
 
Example #8
Source File: XStream.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs an XStream with a special {@link HierarchicalStreamDriver},
 * {@link ReflectionProvider}, a prepared {@link Mapper} chain, the
 * {@link ClassLoaderReference} and an own {@link ConverterLookup} and
 * {@link ConverterRegistry}.
 * <p>
 * The ClassLoaderReference should also be used for the Mapper chain. The ConverterLookup
 * should access the ConverterRegistry if you intent to register {@link Converter} instances
 * with XStream facade or you are using annotations.
 * </p>
 * 
 * @param reflectionProvider the reflection provider to use or <em>null</em> for best
 *            matching Provider
 * @param driver the driver instance
 * @param classLoaderReference the reference to the {@link ClassLoader} to use
 * @param mapper the instance with the {@link Mapper} chain or <em>null</em> for the default
 *            chain
 * @param converterLookup the instance that is used to lookup the converters
 * @param converterRegistry an instance to manage the converter instances or <em>null</em>
 *            to prevent any further registry (including annotations)
 * @throws InitializationException in case of an initialization problem
 * @since 1.4.5
 */
public XStream(
    ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver,
    ClassLoaderReference classLoaderReference, Mapper mapper, ConverterLookup converterLookup,
    ConverterRegistry converterRegistry) {
    if (reflectionProvider == null) {
        reflectionProvider = JVM.newReflectionProvider();
    }
    this.reflectionProvider = reflectionProvider;
    this.hierarchicalStreamDriver = driver;
    this.classLoaderReference = classLoaderReference;
    this.converterLookup = converterLookup;
    this.converterRegistry = converterRegistry;
    this.mapper = mapper == null ? buildMapper() : mapper;

    setupMappers();
    setupSecurity();
    setupAliases();
    setupDefaultImplementations();
    setupConverters();
    setupImmutableTypes();
    setMode(XPATH_RELATIVE_REFERENCES);
}
 
Example #9
Source File: MapConverter.java    From yes-cart with Apache License 2.0 4 votes vote down vote up
@Override
public boolean canConvert(Class type) {
    return type.equals(HashMap.class)
            || type.equals(Hashtable.class)
            || (JVM.is14() && type.getName().equals("java.util.LinkedHashMap"));
}
 
Example #10
Source File: XStreamValid.java    From Digital with GNU General Public License v3.0 4 votes vote down vote up
@Override
    protected void setupConverters() {
        this.registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), -20);
        this.registerConverter(new SerializableConverter(getMapper(), getReflectionProvider(), getClassLoaderReference()), -10);
        this.registerConverter(new ExternalizableConverter(getMapper(), getClassLoaderReference()), -10);
        this.registerConverter(new NullConverter(), 10000);
        this.registerConverter(new IntConverter(), 0);
        this.registerConverter(new FloatConverter(), 0);
        this.registerConverter(new DoubleConverter(), 0);
        this.registerConverter(new LongConverter(), 0);
        this.registerConverter(new ShortConverter(), 0);
        this.registerConverter((Converter) (new CharConverter()), 0);
        this.registerConverter(new BooleanConverter(), 0);
        this.registerConverter(new ByteConverter(), 0);
        this.registerConverter(new StringConverter(), 0);
        this.registerConverter(new StringBufferConverter(), 0);
        this.registerConverter(new DateConverter(), 0);
        this.registerConverter(new BitSetConverter(), 0);
        this.registerConverter(new URIConverter(), 0);
        this.registerConverter(new URLConverter(), 0);
        this.registerConverter(new BigIntegerConverter(), 0);
        this.registerConverter(new BigDecimalConverter(), 0);
        this.registerConverter(new ArrayConverter(getMapper()), 0);
        this.registerConverter(new CharArrayConverter(), 0);
        this.registerConverter(new CollectionConverter(getMapper()), 0);
        this.registerConverter(new MapConverter(getMapper()), 0);
//        this.registerConverter((Converter)(new TreeMapConverter(getMapper())), 0);
//        this.registerConverter((Converter)(new TreeSetConverter(getMapper())), 0);
        this.registerConverter(new SingletonCollectionConverter(getMapper()), 0);
        this.registerConverter(new SingletonMapConverter(getMapper()), 0);
//        this.registerConverter((Converter)(new PropertiesConverter()), 0);
        this.registerConverter((Converter) (new EncodedByteArrayConverter()), 0);
        this.registerConverter(new FileConverter(), 0);
        if (JVM.isSQLAvailable()) {
            this.registerConverter(new SqlTimestampConverter(), 0);
            this.registerConverter(new SqlTimeConverter(), 0);
            this.registerConverter(new SqlDateConverter(), 0);
        }

//        this.registerConverter((Converter)(new DynamicProxyConverter(getMapper(), getClassLoaderReference())), 0);
        this.registerConverter(new JavaClassConverter(getClassLoaderReference()), 0);
        this.registerConverter(new JavaMethodConverter(getClassLoaderReference()), 0);
        this.registerConverter(new JavaFieldConverter(getClassLoaderReference()), 0);
        if (JVM.isAWTAvailable()) {
//            this.registerConverter((Converter)(new FontConverter(getMapper())), 0);
            this.registerConverter(new ColorConverter(), 0);
//            this.registerConverter((SingleValueConverter)(new TextAttributeConverter()), 0);
        }

        if (JVM.isSwingAvailable()) {
            this.registerConverter(new LookAndFeelConverter(getMapper(), getReflectionProvider()), 0);
        }

        this.registerConverter(new LocaleConverter(), 0);
        this.registerConverter(new GregorianCalendarConverter(), 0);

        this.registerConverter(new EnumConverter(), 0);

        this.registerConverter(new SelfStreamingInstanceChecker(getConverterLookup(), this), 0);
    }
 
Example #11
Source File: XStream.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void addImmutableTypeDynamically(String className, boolean isReferenceable) {
    Class type = JVM.loadClassForName(className);
    if (type != null) {
        addImmutableType(type, isReferenceable);
    }
}
 
Example #12
Source File: XStream.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
private void aliasDynamically(String alias, String className) {
    Class type = JVM.loadClassForName(className);
    if (type != null) {
        alias(alias, type);
    }
}
 
Example #13
Source File: XStream.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Setup the security framework of a XStream instance.
 * <p>
 * This method is a pure helper method for XStream 1.4.x. It initializes an XStream instance with a white list of
 * well-known and simply types of the Java runtime as it is done in XStream 1.5.x by default. This method will do
 * therefore nothing in XStream 1.5.
 * </p>
 * 
 * @param xstream
 * @since 1.4.10
 */
public static void setupDefaultSecurity(final XStream xstream) {
    if (!xstream.securityInitialized) {
        xstream.addPermission(NoTypePermission.NONE);
        xstream.addPermission(NullPermission.NULL);
        xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
        xstream.addPermission(ArrayTypePermission.ARRAYS);
        xstream.addPermission(InterfaceTypePermission.INTERFACES);
        xstream.allowTypeHierarchy(Calendar.class);
        xstream.allowTypeHierarchy(Collection.class);
        xstream.allowTypeHierarchy(Map.class);
        xstream.allowTypeHierarchy(Map.Entry.class);
        xstream.allowTypeHierarchy(Member.class);
        xstream.allowTypeHierarchy(Number.class);
        xstream.allowTypeHierarchy(Throwable.class);
        xstream.allowTypeHierarchy(TimeZone.class);

        Class type = JVM.loadClassForName("java.lang.Enum");
        if (type != null) {
            xstream.allowTypeHierarchy(type);
        }
        type = JVM.loadClassForName("java.nio.file.Path");
        if (type != null) {
            xstream.allowTypeHierarchy(type);
        }

        final Set types = new HashSet();
        types.add(BitSet.class);
        types.add(Charset.class);
        types.add(Class.class);
        types.add(Currency.class);
        types.add(Date.class);
        types.add(DecimalFormatSymbols.class);
        types.add(File.class);
        types.add(Locale.class);
        types.add(Object.class);
        types.add(Pattern.class);
        types.add(StackTraceElement.class);
        types.add(String.class);
        types.add(StringBuffer.class);
        types.add(JVM.loadClassForName("java.lang.StringBuilder"));
        types.add(URL.class);
        types.add(URI.class);
        types.add(JVM.loadClassForName("java.util.UUID"));
        if (JVM.isSQLAvailable()) {
            types.add(JVM.loadClassForName("java.sql.Timestamp"));
            types.add(JVM.loadClassForName("java.sql.Time"));
            types.add(JVM.loadClassForName("java.sql.Date"));
        }
        if (JVM.isVersion(8)) {
            xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.Clock"));
            types.add(JVM.loadClassForName("java.time.Duration"));
            types.add(JVM.loadClassForName("java.time.Instant"));
            types.add(JVM.loadClassForName("java.time.LocalDate"));
            types.add(JVM.loadClassForName("java.time.LocalDateTime"));
            types.add(JVM.loadClassForName("java.time.LocalTime"));
            types.add(JVM.loadClassForName("java.time.MonthDay"));
            types.add(JVM.loadClassForName("java.time.OffsetDateTime"));
            types.add(JVM.loadClassForName("java.time.OffsetTime"));
            types.add(JVM.loadClassForName("java.time.Period"));
            types.add(JVM.loadClassForName("java.time.Ser"));
            types.add(JVM.loadClassForName("java.time.Year"));
            types.add(JVM.loadClassForName("java.time.YearMonth"));
            types.add(JVM.loadClassForName("java.time.ZonedDateTime"));
            xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.ZoneId"));
            types.add(JVM.loadClassForName("java.time.chrono.HijrahDate"));
            types.add(JVM.loadClassForName("java.time.chrono.JapaneseDate"));
            types.add(JVM.loadClassForName("java.time.chrono.JapaneseEra"));
            types.add(JVM.loadClassForName("java.time.chrono.MinguoDate"));
            types.add(JVM.loadClassForName("java.time.chrono.ThaiBuddhistDate"));
            types.add(JVM.loadClassForName("java.time.chrono.Ser"));
            xstream.allowTypeHierarchy(JVM.loadClassForName("java.time.chrono.Chronology"));
            types.add(JVM.loadClassForName("java.time.temporal.ValueRange"));
            types.add(JVM.loadClassForName("java.time.temporal.WeekFields"));
        }
        types.remove(null);

        final Iterator iter = types.iterator();
        final Class[] classes = new Class[types.size()];
        for (int i = 0; i < classes.length; ++i) {
            classes[i] = (Class)iter.next();
        }
        xstream.allowTypes(classes);
    } else {
        throw new IllegalArgumentException("Security framework of XStream instance already initialized");
    }
}
 
Example #14
Source File: NamedMapConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs a NamedMapConverter with attribute support handling an explicit Map type.
 * 
 * @param type the Map type this instance will handle
 * @param mapper the mapper
 * @param entryName the name of the entry elements
 * @param keyName the name of the key elements
 * @param keyType the base type of key elements
 * @param valueName the name of the value elements
 * @param valueType the base type of value elements
 * @param keyAsAttribute flag to write key as attribute of entry element
 * @param valueAsAttribute flag to write value as attribute of entry element
 * @param lookup used to lookup SingleValueConverter for attributes
 * @since 1.4.5
 */
public NamedMapConverter(
    Class type, Mapper mapper, String entryName, String keyName, Class keyType,
    String valueName, Class valueType, boolean keyAsAttribute, boolean valueAsAttribute,
    ConverterLookup lookup) {
    super(mapper, type);
    this.entryName = entryName != null && entryName.length() == 0 ? null : entryName;
    this.keyName = keyName != null && keyName.length() == 0 ? null : keyName;
    this.keyType = keyType;
    this.valueName = valueName != null && valueName.length() == 0 ? null : valueName;
    this.valueType = valueType;
    this.keyAsAttribute = keyAsAttribute;
    this.valueAsAttribute = valueAsAttribute;
    this.lookup = lookup;
    enumMapper = JVM.isVersion(5) ? UseAttributeForEnumMapper.createEnumMapper(mapper) : null;

    if (keyType == null || valueType == null) {
        throw new IllegalArgumentException("Class types of key and value are mandatory");
    }
    if (entryName == null) {
        if (keyAsAttribute || valueAsAttribute) {
            throw new IllegalArgumentException(
                "Cannot write attributes to map entry, if map entry must be omitted");
        }
        if (valueName == null) {
            throw new IllegalArgumentException(
                "Cannot write value as text of entry, if entry must be omitted");
        }
    }
    if (keyName == null) {
        throw new IllegalArgumentException("Cannot write key without name");
    }
    if (valueName == null) {
        if (valueAsAttribute) {
            throw new IllegalArgumentException(
                "Cannot write value as attribute without name");
        } else if (!keyAsAttribute) {
            throw new IllegalArgumentException(
                "Cannot write value as text of entry, if key is also child element");
        }
    }
    if (keyAsAttribute && valueAsAttribute && keyName.equals(valueName)) {
        throw new IllegalArgumentException(
            "Cannot write key and value with same attribute name");
    }
}
 
Example #15
Source File: EncodedByteArrayConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Constructs an EncodedByteArrayConverter. Initializes the converter with a Base64 codec.
 */
public EncodedByteArrayConverter() {
    this(JVM.getBase64Codec());
}
 
Example #16
Source File: ExternalizableConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public boolean canConvert(Class type) {
    return type != null && JVM.canCreateDerivedObjectOutputStream() && Externalizable.class.isAssignableFrom(type);
}
 
Example #17
Source File: LambdaConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public boolean canConvert(final Class type) {
    return Types.isLambdaType(type)
        && (JVM.canCreateDerivedObjectOutputStream() || !Serializable.class.isAssignableFrom(type));
}
 
Example #18
Source File: SerializableConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
public boolean canConvert(Class type) {
    return JVM.canCreateDerivedObjectOutputStream() && isSerializable(type);
}
 
Example #19
Source File: AnnotationMapper.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Construct an AnnotationMapper.
 * 
 * @param wrapped the next {@link Mapper} in the chain
 * @since 1.3
 * @deprecated As of 1.4.5 use {@link #AnnotationMapper(Mapper, ConverterRegistry, ConverterLookup, ClassLoaderReference, ReflectionProvider)}
 */
public AnnotationMapper(
    final Mapper wrapped, final ConverterRegistry converterRegistry, final ConverterLookup converterLookup,
    final ClassLoader classLoader, final ReflectionProvider reflectionProvider,
    final JVM jvm) {
    this(wrapped, converterRegistry, converterLookup, new ClassLoaderReference(classLoader), reflectionProvider);
}