Java Code Examples for com.thoughtworks.xstream.converters.Converter

The following examples show how to use com.thoughtworks.xstream.converters.Converter. These examples are extracted from open source projects. 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 Project: lams   Author: lamsfoundation   File: FilePersistenceStrategy.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Given a key, the escape method returns the filename which shall be used.
 *
 * @param key the key
 * @return the desired and escaped filename
 */
protected String getName(final Object key) {
    if (key == null) {
        return "[email protected]";
    }
    final Class type = key.getClass();
    final Converter converter = getConverterLookup().lookupConverterForType(type);
    if (converter instanceof SingleValueConverter) {
        final SingleValueConverter svConverter = (SingleValueConverter)converter;
        return getMapper().serializedClass(type) + '@' + escape(svConverter.toString(key)) + ".xml";
    } else {
        final ConversionException exception = new ConversionException(
            "No SingleValueConverter available for key type");
        exception.add("key-type", type.getName());
        throw exception;
    }
}
 
Example #2
Source Project: gama   Author: gama-platform   File: Converters.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Converter[] loadConverter(ConverterScope cs)
{
	Converter[] converters= new Converter[14];
	converters[0]= new GamaBasicTypeConverter(cs);
	converters[1]=new GamaAgentConverter(cs);		
	converters[2]=new GamaListConverter(cs);
	converters[3]=new GamaMapConverter(cs);
	converters[4]=new GamaPairConverter();
	converters[5]=new GamaMatrixConverter(cs);
	converters[6]=new GamaGraphConverter(cs);		
	converters[7]=new GamaFileConverter(cs);

	converters[8]=new LogConverter();
	converters[9]=new SavedAgentConverter(cs);
	
	converters[10]= new GamaPopulationConverter(cs);
	converters[11]= new GamaSpeciesConverter(cs);	
	converters[12]= new ReferenceAgentConverter(cs);		
	converters[13]= new GamaPathConverter(cs);		
	
	//converters[12]= new ComplexMessageConverter(cs);		
	
	return converters;
}
 
Example #3
Source Project: gama   Author: gama-platform   File: Converters.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static Converter[] loadConverterNetwork(ConverterScope cs)
{
	Converter[] converters= new Converter[12];
	converters[0]= new GamaBasicTypeConverter(cs);
	converters[1]=new GamaAgentConverterNetwork(cs);
	converters[2]=new GamaListConverterNetwork(cs);
	converters[3]=new GamaMapConverter(cs);
	converters[4]=new GamaPairConverter();
	converters[5]=new GamaMatrixConverter(cs);
	converters[6]=new GamaGraphConverter(cs);		
	converters[7]=new GamaFileConverter(cs);

	converters[8]=new LogConverter();
	converters[9]=new SavedAgentConverter(cs);
	
	converters[10]= new GamaPopulationConverter(cs);
	converters[11]= new GamaSpeciesConverter(cs);		
	//converters[12]= new ComplexMessageConverter(cs);		
	
	return converters;
}
 
Example #4
Source Project: brooklyn-server   Author: apache   File: ObjectWithDefaultStringImplConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    String clazzName = reader.getAttribute("class");
    Class<?> clazz;
    if (clazzName == null) {
        clazz = defaultImpl;
    } else if (clazzName.equals("string")) {
        clazz = String.class;
    } else if (Boxing.getPrimitiveType(clazzName).isPresent()) {
        clazz = Boxing.getPrimitiveType(clazzName).get();
    } else {
        try {
            clazz = loader.getReference().loadClass(clazzName);
        } catch (ClassNotFoundException e) {
            throw Exceptions.propagate(e);
        }
    }
    Converter converter = lookup.lookupConverterForType(clazz);
    return converter.unmarshal(reader, context);
}
 
Example #5
Source Project: saros   Author: saros-project   File: XStreamExtensionProvider.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Register additional {@link Converter}s at runtime. This is useful if a converter cannot be used
 * isolatedly, e.g. because it requires a running Saros session.
 *
 * @param converter The {@link Converter} to be registered to XStream. There can only be one
 *     instance per converter class. If a new instance of an already registered class is
 *     registered, the old instance will be replaced.
 */
public void registerConverter(Converter converter) {
  Class<? extends Converter> clazz = converter.getClass();

  if (replaceables.containsKey(clazz)) {
    log.debug("Renewing existing converter of " + clazz);
    replaceables.get(clazz).replace(converter);
    return;
  }

  log.debug("Registering new converter of " + clazz);

  ReplaceableConverter replaceable = new ReplaceableConverter(converter);
  xstream.registerConverter(replaceable);
  replaceables.put(clazz, replaceable);
}
 
Example #6
Source Project: vraptor4   Author: caelum   File: XStreamSerializerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setup() throws Exception {
	stream = new ByteArrayOutputStream();
	environment = mock(Environment.class);

	HttpServletResponse response = mock(HttpServletResponse.class);
	when(response.getWriter()).thenReturn(new PrintWriter(stream));

	List<Converter> converters = new ArrayList<>();
	converters.add(new CalendarConverter());

	final DefaultTypeNameExtractor extractor = new DefaultTypeNameExtractor();

	Instance<Converter> convertersInst = new MockInstanceImpl<>(converters);
	Instance<SingleValueConverter> singleValueConverters = new MockInstanceImpl<>();
	XStreamConverters xStreamConverters = new XStreamConverters(convertersInst, singleValueConverters);
	serialization = new XStreamXMLSerialization(response, new XStreamBuilderImpl(xStreamConverters, extractor, 
			new Serializee(new DefaultReflectionProvider()), new DefaultReflectionProvider()), environment);
}
 
Example #7
Source Project: lams   Author: lamsfoundation   File: XStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
private XStream(
        ReflectionProvider reflectionProvider, HierarchicalStreamDriver driver, ClassLoaderReference classLoader,
        Mapper mapper, final DefaultConverterLookup defaultConverterLookup) {
    this(reflectionProvider, driver, classLoader, mapper, new ConverterLookup() {
        public Converter lookupConverterForType(Class type) {
            return defaultConverterLookup.lookupConverterForType(type);
        }
    }, new ConverterRegistry() {
        public void registerConverter(Converter converter, int priority) {
            defaultConverterLookup.registerConverter(converter, priority);
        }
    });
}
 
Example #8
Source Project: lams   Author: lamsfoundation   File: XStream.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Register a local {@link Converter} for a field.
 *
 * @param definedIn the class type the field is defined in
 * @param fieldName the field name
 * @param converter the converter to use
 * @since 1.3
 */
public void registerLocalConverter(Class definedIn, String fieldName, Converter converter) {
    if (localConversionMapper == null) {
        throw new com.thoughtworks.xstream.InitializationException("No "
            + LocalConversionMapper.class.getName()
            + " available");
    }
    localConversionMapper.registerLocalConverter(definedIn, fieldName, converter);
}
 
Example #9
Source Project: lams   Author: lamsfoundation   File: AnnotationReflectionConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Deprecated
public AnnotationReflectionConverter(
                                     Mapper mapper, ReflectionProvider reflectionProvider,
                                     AnnotationProvider annotationProvider) {
    super(mapper, reflectionProvider);
    this.annotationProvider = annotationProvider;
    this.cachedConverters = new HashMap<Class<? extends ConverterMatcher>, Converter>();
}
 
Example #10
Source Project: lams   Author: lamsfoundation   File: AnnotationReflectionConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected Object unmarshallField(
                                 final UnmarshallingContext context, final Object result,
                                 Class type, Field field) {
    XStreamConverter annotation = annotationProvider.getAnnotation(
        field, XStreamConverter.class);
    if (annotation != null) {
        Class<? extends Converter> converterType = (Class<? extends Converter>)annotation.value();
        ensureCache(converterType);
        return context.convertAnother(result, type, cachedConverters.get(converterType));
    } else {
        return context.convertAnother(result, type);
    }
}
 
Example #11
Source Project: lams   Author: lamsfoundation   File: AttributeMapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private SingleValueConverter getLocalConverterFromItemType(Class type) {
    Converter converter = converterLookup.lookupConverterForType(type);
    if (converter != null && converter instanceof SingleValueConverter) {
        return (SingleValueConverter)converter;
    } else {
        return null;
    }
}
 
Example #12
Source Project: lams   Author: lamsfoundation   File: AnnotationMapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Converter getLocalConverter(final Class definedIn, final String fieldName) {
    if (!locked) {
        processAnnotations(definedIn);
    }
    return super.getLocalConverter(definedIn, fieldName);
}
 
Example #13
Source Project: lams   Author: lamsfoundation   File: AnnotationMapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void processConverterAnnotations(final Class<?> type) {
    if (converterRegistry != null) {
        final XStreamConverters convertersAnnotation = type
            .getAnnotation(XStreamConverters.class);
        final XStreamConverter converterAnnotation = type
            .getAnnotation(XStreamConverter.class);
        final List<XStreamConverter> annotations = convertersAnnotation != null
            ? new ArrayList<XStreamConverter>(Arrays.asList(convertersAnnotation.value()))
            : new ArrayList<XStreamConverter>();
        if (converterAnnotation != null) {
            annotations.add(converterAnnotation);
        }
        for (final XStreamConverter annotation : annotations) {
            final Converter converter = cacheConverter(
                annotation, converterAnnotation != null ? type : null);
            if (converter != null) {
                if (converterAnnotation != null || converter.canConvert(type)) {
                    converterRegistry.registerConverter(converter, annotation.priority());
                } else {
                    throw new InitializationException("Converter "
                        + annotation.value().getName()
                        + " cannot handle annotated class "
                        + type.getName());
                }
            }
        }
    }
}
 
Example #14
Source Project: lams   Author: lamsfoundation   File: AnnotationMapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void processLocalConverterAnnotation(final Field field) {
    final XStreamConverter annotation = field.getAnnotation(XStreamConverter.class);
    if (annotation != null) {
        final Converter converter = cacheConverter(annotation, field.getType());
        if (converter != null) {
            if (localConversionMapper == null) {
                throw new InitializationException("No "
                    + LocalConversionMapper.class.getName()
                    + " available");
            }
            localConversionMapper.registerLocalConverter(
                field.getDeclaringClass(), field.getName(), converter);
        }
    }
}
 
Example #15
Source Project: lams   Author: lamsfoundation   File: LocalConversionMapper.java    License: GNU General Public License v2.0 5 votes vote down vote up
private SingleValueConverter getLocalSingleValueConverter(Class definedIn,
    String fieldName, Class type) {
    if (attributeMapper != null
        && attributeMapper.shouldLookForSingleValueConverter(fieldName, type, definedIn)) {
        Converter converter = getLocalConverter(definedIn, fieldName);
        if (converter != null && converter instanceof SingleValueConverter) {
            return (SingleValueConverter)converter;
        }
    }
    return null;
}
 
Example #16
Source Project: lams   Author: lamsfoundation   File: DefaultConverterLookup.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void flushCache() {
    typeToConverterMap.clear();
    Iterator iterator = converters.iterator();
    while (iterator.hasNext()) {
        Converter converter = (Converter)iterator.next();
        if (converter instanceof Caching) {
            ((Caching)converter).flushCache();
        }
    }
}
 
Example #17
Source Project: lams   Author: lamsfoundation   File: TreeUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
public Object convertAnother(Object parent, Class type, Converter converter) {
    type = mapper.defaultImplementationOf(type);
    if (converter == null) {
        converter = converterLookup.lookupConverterForType(type);
    } else {
        if (!converter.canConvert(type)) {
            ConversionException e = new ConversionException(
                "Explicit selected converter cannot handle type");
            e.add("item-type", type.getName());
            e.add("converter-type", converter.getClass().getName());
            throw e;
        }
    }
    return convert(parent, type, converter);
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: TreeUnmarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void addInformationTo(ErrorWriter errorWriter, Class type, Converter converter, Object parent) {
    errorWriter.add("class", type.getName());
    errorWriter.add("required-type", getRequiredType().getName());
    errorWriter.add("converter-type", converter.getClass().getName());
    if (converter instanceof ErrorReporter) {
        ((ErrorReporter)converter).appendErrors(errorWriter);
    }
    if (parent instanceof ErrorReporter) {
        ((ErrorReporter)parent).appendErrors(errorWriter);
    }
    reader.appendErrors(errorWriter);
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: TreeMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void convertAnother(Object item, Converter converter) {
    if (converter == null) {
        converter = converterLookup.lookupConverterForType(item.getClass());
    } else {
        if (!converter.canConvert(item.getClass())) {
            ConversionException e = new ConversionException(
                "Explicit selected converter cannot handle item");
            e.add("item-type", item.getClass().getName());
            e.add("converter-type", converter.getClass().getName());
            throw e;
        }
    }
    convert(item, converter);
}
 
Example #20
Source Project: lams   Author: lamsfoundation   File: TreeMarshaller.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected void convert(Object item, Converter converter) {
    if (parentObjects.containsId(item)) {
        ConversionException e = new CircularReferenceException(
            "Recursive reference to parent object");
        e.add("item-type", item.getClass().getName());
        e.add("converter-type", converter.getClass().getName());
        throw e;
    }
    parentObjects.associateId(item, "");
    converter.marshal(item, writer, this);
    parentObjects.removeId(item);
}
 
Example #21
Source Project: spring4-understanding   Author: langtianya   File: XStreamMarshallerTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void converters() throws Exception {
	marshaller.setConverters(new Converter[]{new EncodedByteArrayConverter()});
	byte[] buf = new byte[]{0x1, 0x2};
	Writer writer = new StringWriter();
	marshaller.marshal(buf, new StreamResult(writer));
	assertXMLEqual("<byte-array>AQI=</byte-array>", writer.toString());
	Reader reader = new StringReader(writer.toString());
	byte[] bufResult = (byte[]) marshaller.unmarshal(new StreamSource(reader));
	assertTrue("Invalid result", Arrays.equals(buf, bufResult));
}
 
Example #22
Source Project: cuba   Author: cuba-platform   File: CubaXStream.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void registerConverter(Converter converter, int priority) {
    if (converter != null && excluded.contains(converter.getClass())) {
        return;
    }
    super.registerConverter(converter, priority);
}
 
Example #23
Source Project: yes-cart   Author: inspire-software   File: ReportObjectStreamFactoryImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Spring IoC.
 *
 * @param converters converter
 */
public void setConverterMap(final Map<String, Converter> converters) {

    for (final Map.Entry<String, Converter> entry : converters.entrySet()) {
        this.xStream.registerConverter(entry.getValue());
    }

}
 
Example #24
Source Project: gama   Author: gama-platform   File: StreamConverter.java    License: 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 #25
Source Project: gama   Author: gama-platform   File: StreamConverter.java    License: 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 #26
Source Project: Chronicle-Map   Author: OpenHFT   File: JsonSerializer.java    License: Apache License 2.0 5 votes vote down vote up
private static <K, V> XStream xStream(Map<K, V> map, List jsonConverters) {
    try {
        final XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("cmap", map.getClass());

        registerChronicleMapConverter(map, xstream);
        xstream.registerConverter(new ByteBufferConverter());
        xstream.registerConverter(new ValueConverter());
        xstream.registerConverter(new StringBuilderConverter());
        xstream.registerConverter(new CharSequenceConverter());

        for (Object c : jsonConverters) {
            if (c instanceof Converter) {
                xstream.registerConverter((Converter) c);
            } else {
                LOG.warn("Skipping Converter of type class=" + c.getClass().getName() + " as " +
                        " expecting an object of type com.thoughtworks.xstream.converters" +
                        ".Converter");
            }
        }

        return xstream;
    } catch (NoClassDefFoundError e) {
        throw new RuntimeException(logErrorSuggestXStreem, e);
    }
}
 
Example #27
Source Project: saros   Author: saros-project   File: XStreamExtensionProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new XStreamExtensionProvider using the given element name as the XML root element with
 * the given namespace. The Provider is able to understand the given classes, which should be
 * annotated using XStream annotations.
 *
 * <p><b>Important</b>: use valid XML element names and namespaces or the receiving side will be
 * unable to decode the extension !
 */
public XStreamExtensionProvider(String namespace, String elementName, Class<?>... classes) {

  if (namespace == null) throw new NullPointerException("namespace is null");

  ClassLoader classLoader = currentClassloader;

  this.elementName = elementName;
  this.namespace = namespace;

  xstream = XStreamFactory.getSecureXStream();

  if (classLoader != null) xstream.setClassLoader(classLoader);
  else xstream.setClassLoader(getClass().getClassLoader());

  xstream.registerConverter(BooleanConverter.BINARY);
  xstream.registerConverter(new UrlEncodingStringConverter());
  xstream.processAnnotations(XStreamPacketExtension.class);
  xstream.processAnnotations(classes);
  xstream.alias(elementName, XStreamPacketExtension.class);

  ProviderManager providerManager = ProviderManager.getInstance();
  providerManager.addExtensionProvider(getElementName(), getNamespace(), this);
  providerManager.addIQProvider(getElementName(), getNamespace(), this);

  // TODO Validate that elementName is a valid XML identifier

  replaceables = new HashMap<Class<? extends Converter>, ReplaceableConverter>();
  replaceableSingles =
      new HashMap<Class<? extends SingleValueConverter>, ReplaceableSingleValueConverter>();
}
 
Example #28
Source Project: saros   Author: saros-project   File: XStreamExtensionProvider.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Unregisters a previously registered {@link Converter} from XStream.
 *
 * @param converter If this converter (more precisely: one of the same class) was registered
 *     through {@link #registerConverter(Converter)}, it will no longer be called by XStream.
 *     Otherwise, nothing happens.
 */
public void unregisterConverter(Converter converter) {
  Class<? extends Converter> clazz = converter.getClass();

  if (replaceables.containsKey(clazz)) {
    log.debug("Unregistering (resetting) converter of " + clazz);
    replaceables.get(clazz).reset();
  }
}
 
Example #29
Source Project: saros   Author: saros-project   File: ReplaceableConverterTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void reset() {
  /* Mocks */
  Converter c1 = EasyMock.createMock(Converter.class);
  expect(c1.canConvert(Dummy.class)).andStubReturn(true);

  c1.marshal(
      isA(Object.class), isA(HierarchicalStreamWriter.class), isA(MarshallingContext.class));
  EasyMock.expectLastCall().once();

  EasyMock.replay(c1);

  /* XStream config */
  XStream xstream = XStreamFactory.getSecureXStream(new DomDriver());
  ReplaceableConverter resetable = new ReplaceableConverter(c1);
  xstream.registerConverter(resetable);

  /* Test it */
  assertFalse("ReplaceableConverter was not properly set up", resetable.isReset());

  assertNotNull("Converter cannot convert", xstream.toXML(new Dummy()));

  resetable.reset();
  assertTrue("ReplaceableConverter was not properly reset", resetable.isReset());

  /*
   * This call should not reach the converter.
   */
  xstream.toXML(new Dummy());

  /*
   * Verify that the converter was used exactly once, i.e. it was not
   * called while it was inactive.
   */
  EasyMock.verify(c1);
}
 
Example #30
Source Project: saros   Author: saros-project   File: ReplaceableConverterTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void replace() {
  /* Mocks */
  Converter c1 = EasyMock.createMock(Converter.class);
  expect(c1.canConvert(Dummy.class)).andStubReturn(true);

  Converter c2 = EasyMock.createMock(Converter.class);
  expect(c2.canConvert(Dummy.class)).andStubReturn(true);

  c2.marshal(
      isA(Object.class), isA(HierarchicalStreamWriter.class), isA(MarshallingContext.class));
  EasyMock.expectLastCall().once();

  EasyMock.replay(c1, c2);

  /* XStream config */
  XStream xstream = XStreamFactory.getSecureXStream(new DomDriver());
  ReplaceableConverter resetable = new ReplaceableConverter(c1);
  xstream.registerConverter(resetable);

  /* Test it */
  resetable.reset();
  assertTrue("ReplaceableConverter was not properly reset", resetable.isReset());

  /*
   * This call should not reach any of the converters.
   */
  xstream.toXML(new Dummy());

  resetable.replace(c2);
  assertNotNull("Converter was not reactivated", xstream.toXML(new Dummy()));

  /*
   * Verify that the first converter is not called, and the second exactly
   * once
   */
  EasyMock.verify(c1, c2);
}