Java Code Examples for com.thoughtworks.xstream.XStream#setClassLoader()

The following examples show how to use com.thoughtworks.xstream.XStream#setClassLoader() . 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: BluetoothGattSpecificationReader.java    From bluetooth-gatt-parser with Apache License 2.0 6 votes vote down vote up
private <T> T getSpec(URL file) {
    try {
        XStream xstream = new XStream(new DomDriver());
        xstream.autodetectAnnotations(true);
        xstream.processAnnotations(Bit.class);
        xstream.processAnnotations(BitField.class);
        xstream.processAnnotations(Characteristic.class);
        xstream.processAnnotations(Enumeration.class);
        xstream.processAnnotations(Enumerations.class);
        xstream.processAnnotations(Field.class);
        xstream.processAnnotations(InformativeText.class);
        xstream.processAnnotations(Service.class);
        xstream.processAnnotations(Value.class);
        xstream.processAnnotations(Reserved.class);
        xstream.processAnnotations(Examples.class);
        xstream.processAnnotations(CharacteristicAccess.class);
        xstream.processAnnotations(Characteristics.class);
        xstream.processAnnotations(Properties.class);
        xstream.ignoreUnknownElements();
        xstream.setClassLoader(Characteristic.class.getClassLoader());
        return (T) xstream.fromXML(file);
    } catch (Exception e) {
        logger.error("Could not read file: " + file, e);
    }
    return null;
}
 
Example 2
Source File: Filter.java    From snap-desktop with GNU General Public License v3.0 6 votes vote down vote up
public static XStream createXStream() {
    final XStream xStream = new XStream();
    xStream.setClassLoader(Filter.class.getClassLoader());
    xStream.alias("filter", Filter.class);
    xStream.registerLocalConverter(Filter.class, "kernelElements", new SingleValueConverter() {
        @Override
        public String toString(Object o) {
            double[] o1 = (double[]) o;
            // todo - find out how to obtain width, height
            return Filter.formatKernelElements(o1, new Dimension(o1.length, 1), ",");
        }

        @Override
        public Object fromString(String s) {
            return Filter.parseKernelElementsFromText(s, null);
        }

        @Override
        public boolean canConvert(Class aClass) {
            return aClass.equals(double[].class);
        }
    });
    return xStream;
}
 
Example 3
Source File: KieModuleMarshaller.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
private KieModuleMarshaller() {
    xStream = new XStream(new DomDriver()) {
        @Override
        protected void setupConverters() {
            registerConverter(new NullConverter(), PRIORITY_VERY_HIGH);
            registerConverter(new IntConverter(), PRIORITY_NORMAL);
            registerConverter(new FloatConverter(), PRIORITY_NORMAL);
            registerConverter(new DoubleConverter(), PRIORITY_NORMAL);
            registerConverter(new LongConverter(), PRIORITY_NORMAL);
            registerConverter(new ShortConverter(), PRIORITY_NORMAL);
            registerConverter(new BooleanConverter(), PRIORITY_NORMAL);
            registerConverter(new ByteConverter(), PRIORITY_NORMAL);
            registerConverter(new StringConverter(), PRIORITY_NORMAL);
            registerConverter(new CollectionConverter(getMapper()), PRIORITY_NORMAL);
            registerConverter(new ReflectionConverter(getMapper(), getReflectionProvider()), PRIORITY_VERY_LOW);
            registerConverter(new KieModuleConverter());
            registerConverter(new KieBaseModelImpl.KBaseConverter());
            registerConverter(new KieSessionModelImpl.KSessionConverter());
            registerConverter(new ListenerModelImpl.ListenerConverter());
            registerConverter(new QualifierModelImpl.QualifierConverter());
            registerConverter(new WorkItemHandlerModelImpl.WorkItemHandelerConverter());
            registerConverter(new ChannelModelImpl.ChannelConverter());
            registerConverter(new RuleTemplateModelImpl.RuleTemplateConverter());
        }
    };
    XStream.setupDefaultSecurity(xStream);
    xStream.addPermission(new AnyTypePermission());
    xStream.alias("kmodule", KieModuleModelImpl.class);
    xStream.alias("kbase", KieBaseModelImpl.class);
    xStream.alias("ksession", KieSessionModelImpl.class);
    xStream.alias("listener", ListenerModelImpl.class);
    xStream.alias("qualifier", QualifierModelImpl.class);
    xStream.alias("workItemHandler", WorkItemHandlerModelImpl.class);
    xStream.alias("channel", ChannelModelImpl.class);
    xStream.alias("fileLogger", FileLoggerModelImpl.class);
    xStream.alias("ruleTemplate", RuleTemplateModelImpl.class);
    xStream.setClassLoader(KieModuleModelImpl.class.getClassLoader());
}
 
Example 4
Source File: XStreamInitializer.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
public static XStream getInstance() {
  XStream xstream = new XStream(new PureJavaReflectionProvider(), new XppDriver() {

    @Override
    public HierarchicalStreamWriter createWriter(Writer out) {
      return new PrettyPrintWriter(out, getNameCoder()) {
        protected String PREFIX_CDATA = "<![CDATA[";
        protected String SUFFIX_CDATA = "]]>";
        protected String PREFIX_MEDIA_ID = "<MediaId>";
        protected String SUFFIX_MEDIA_ID = "</MediaId>";

        @Override
        protected void writeText(QuickWriter writer, String text) {
          if (text.startsWith(this.PREFIX_CDATA) && text.endsWith(this.SUFFIX_CDATA)) {
            writer.write(text);
          } else if (text.startsWith(this.PREFIX_MEDIA_ID) && text.endsWith(this.SUFFIX_MEDIA_ID)) {
            writer.write(text);
          } else {
            super.writeText(writer, text);
          }

        }

        @Override
        public String encodeNode(String name) {
          //防止将_转换成__
          return name;
        }
      };
    }
  });

  xstream.ignoreUnknownElements();
  xstream.setMode(XStream.NO_REFERENCES);
  xstream.addPermission(NullPermission.NULL);
  xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
  xstream.setClassLoader(Thread.currentThread().getContextClassLoader());
  return xstream;
}
 
Example 5
Source File: XStreamDeepClone.java    From quarkus with Apache License 2.0 5 votes vote down vote up
public XStreamDeepClone(ClassLoader classLoader) {
    // avoid doing any work eagerly since the cloner is rarely used
    xStreamSupplier = () -> {
        XStream result = new XStream();
        XStream.setupDefaultSecurity(result);
        result.allowTypesByRegExp(new String[] { ".*" });
        result.setClassLoader(classLoader);
        return result;
    };
}
 
Example 6
Source File: XStreamFactory.java    From depan with Apache License 2.0 5 votes vote down vote up
/**
 * Factory method to configure underlying {@link XStream} properly for
 * a desired document type.
 * 
 * This method integrates the document supplied {@link XStreamConfig}
 * with the plugin contributions from {@link XStreamConfigRegistry}.
 * The document supplied {@link XStreamConfig} values have priority,
 * and can override both the {@code XStream} options and class path from
 * the  {@link XStreamConfigRegistry}.
 * It is appropriate to use care with this mechanism.
 */
public static ObjectXmlPersist build(
    boolean readable, XStreamConfig docConfig) {
  XStream xstream = XStreamFactory.newXStream(readable);
  XStreamFactory.configureXStream(xstream);
  docConfig.config(xstream);

  PluginClassLoader loader = buildLoader(docConfig);
  xstream.setClassLoader(loader);

  return new ObjectXmlPersist(xstream);
}
 
Example 7
Source File: StreamConverter.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static XStream loadAndBuild(final ConverterScope cs) {
	final XStream dataStreamer = new XStream(new DomDriver());
	dataStreamer.setClassLoader(GamaClassLoader.getInstance());

	final Converter[] cnv = Converters.converterFactory(cs);
	for (final Converter c : cnv) {
		StreamConverter.registerConverter(dataStreamer, c);
	}
	// dataStreamer.setMode(XStream.ID_REFERENCES);
	return dataStreamer;
}
 
Example 8
Source File: StreamConverter.java    From gama with GNU General Public License v3.0 5 votes vote down vote up
public static XStream loadAndBuildNetwork(final ConverterScope cs) {
	final XStream dataStreamer = new XStream(new DomDriver());
	dataStreamer.setClassLoader(GamaClassLoader.getInstance());

	final Converter[] cnv = Converters.converterNetworkFactory(cs);
	for (final Converter c : cnv) {
		StreamConverter.registerConverter(dataStreamer, c);
	}
	return dataStreamer;
}
 
Example 9
Source File: XStreamSessionIO.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
protected XStream createXStream() {
    XStream xStream = new XStream();
    xStream.setClassLoader(XStreamSessionIO.class.getClassLoader());
    xStream.autodetectAnnotations(true);
    xStream.alias("session", Session.class);
    xStream.alias("configuration", DomElement.class, DefaultDomElement.class);
    return xStream;
}
 
Example 10
Source File: XmlSerializer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public XmlSerializer(ClassLoader loader, Map<String, String> deserializingClassRenames) {
    this.deserializingClassRenames = deserializingClassRenames;
    xstream = new XStream() {
        @Override
        protected MapperWrapper wrapMapper(MapperWrapper next) {
            return XmlSerializer.this.wrapMapperForNormalUsage( super.wrapMapper(next) );
        }
    };

    XStream.setupDefaultSecurity(xstream);
    xstream.allowTypesByWildcard(new String[] {
           "**"
    });

    if (loader!=null) {
        xstream.setClassLoader(loader);
    }
    
    xstream.registerConverter(newCustomJavaClassConverter(), XStream.PRIORITY_NORMAL);
    
    // list as array list is default
    xstream.alias("map", Map.class, LinkedHashMap.class);
    xstream.alias("set", Set.class, LinkedHashSet.class);
    
    xstream.registerConverter(new StringKeyMapConverter(xstream.getMapper()), /* priority */ 10);
    xstream.alias("MutableMap", MutableMap.class);
    xstream.alias("MutableSet", MutableSet.class);
    xstream.alias("MutableList", MutableList.class);
    
    // Needs an explicit MutableSet converter!
    // Without it, the alias for "set" seems to interfere with the MutableSet.map field, so it gets
    // a null field on deserialization.
    xstream.registerConverter(new MutableSetConverter(xstream.getMapper()));
    
    xstream.aliasType("ImmutableList", ImmutableList.class);
    xstream.registerConverter(new ImmutableListConverter(xstream.getMapper()));
    xstream.registerConverter(new ImmutableSetConverter(xstream.getMapper()));
    xstream.registerConverter(new ImmutableMapConverter(xstream.getMapper()));

    xstream.registerConverter(new EnumCaseForgivingConverter());
    xstream.registerConverter(new Inet4AddressConverter());
    
    // See ObjectWithDefaultStringImplConverter (and its usage) for why we want to auto-detect 
    // annotations (usages of this is in the camp project, so we can't just list it statically
    // here unfortunately).
    xstream.autodetectAnnotations(true);
}
 
Example 11
Source File: MagicWandForm.java    From snap-desktop with GNU General Public License v3.0 4 votes vote down vote up
private XStream createXStream() {
    XStream xStream = new XStream();
    xStream.setClassLoader(MagicWandModel.class.getClassLoader());
    xStream.alias("magicWandSettings", MagicWandModel.class);
    return xStream;
}
 
Example 12
Source File: XmlUtils.java    From weblaf with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Initializes global XStream instance.
 */
private static void initializeXStream ()
{
    try
    {
        // Custom ReflectionProvider to provide pure-java objects instantiation
        // Unlike default SunUnsafeReflectionProvider it has limited objects instantiation options
        // Also it properly initializes object field values specified directly near the fields
        final PureJavaReflectionProvider reflectionProvider = new PureJavaReflectionProvider ();

        // Custom HierarchicalStreamDriver implementation based on StaxDriver
        // It provides us HierarchicalStreamReader to allow XStreamContext usage
        hierarchicalStreamDriver = new XmlDriver ();

        // XStream instance initialization
        xStream = new XStream ( reflectionProvider, hierarchicalStreamDriver );

        // Make sure that XStream ClassLoader finds WebLaF classes in cases where multiple ClassLoaders are used
        // E.g. IntelliJ IDEA uses different ClassLoaders for plugins (e.g. JFormDesigner) and its core (which includes XStream)
        if ( XmlUtils.class.getClassLoader () != xStream.getClass ().getClassLoader () )
        {
            final ClassLoader classLoader = xStream.getClassLoader ();
            if ( classLoader instanceof CompositeClassLoader )
            {
                ( ( CompositeClassLoader ) classLoader ).add ( XmlUtils.class.getClassLoader () );
            }
            else
            {
                final CompositeClassLoader compositeClassLoader = new CompositeClassLoader ();
                compositeClassLoader.add ( XmlUtils.class.getClassLoader () );
                xStream.setClassLoader ( compositeClassLoader );
            }
        }

        // Standard Java-classes aliases
        if ( aliasJdkClasses )
        {
            // Custom {@link java.awt.Point} mapping
            xStream.alias ( "Point", Point.class );
            xStream.useAttributeFor ( Point.class, "x" );
            xStream.useAttributeFor ( Point.class, "y" );

            // Custom {@link java.awt.geom.Point2D} mapping
            xStream.alias ( "Point2D", Point2D.class );
            xStream.registerConverter ( new Point2DConverter () );

            // Custom {@link java.awt.Dimension} mapping
            xStream.alias ( "Dimension", Dimension.class );
            xStream.registerConverter ( new DimensionConverter () );

            // Custom {@link java.awt.Rectangle} mapping
            xStream.alias ( "Rectangle", Rectangle.class );
            xStream.useAttributeFor ( Rectangle.class, "x" );
            xStream.useAttributeFor ( Rectangle.class, "y" );
            xStream.useAttributeFor ( Rectangle.class, "width" );
            xStream.useAttributeFor ( Rectangle.class, "height" );

            // Custom {@link java.awt.Font} mapping
            xStream.alias ( "Font", Font.class );

            // Custom {@link java.awt.Color} mapping
            xStream.alias ( "Color", Color.class );
            xStream.registerConverter ( new ColorConverter () );

            // Custom {@link java.awt.Insets} mapping
            xStream.alias ( "Insets", Insets.class );
            xStream.registerConverter ( new InsetsConverter () );

            // Custom {@link java.awt.Stroke} mapping
            xStream.alias ( "Stroke", Stroke.class );
            xStream.registerConverter ( new StrokeConverter () );
        }

        // Additional WebLaF data classes aliases
        xStream.processAnnotations ( Pair.class );
        xStream.processAnnotations ( Scale.class );
    }
    catch ( final Exception e )
    {
        // It is a pretty fatal for library if something goes wrong here
        throw new UtilityException ( "Unable to initialize XStream instance", e );
    }
}