Java Code Examples for com.thoughtworks.xstream.XStream

The following examples show how to use com.thoughtworks.xstream.XStream. 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: olat   Source File: BlogArtefactHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void getContent(final AbstractArtefact artefact, final StringBuilder sb, final SearchResourceContext context, final EPFrontendManager ePFManager) {
    final String content = ePFManager.getArtefactFullTextContent(artefact);
    if (content != null) {
        try {
            final XStream xstream = XStreamHelper.createXStreamInstance();
            xstream.alias("item", Item.class);
            final Item item = (Item) xstream.fromXML(content);

            final String mapperBaseURL = "";
            final Filter mediaUrlFilter = FilterFactory.getBaseURLToMediaRelativeURLFilter(mapperBaseURL);
            sb.append(mediaUrlFilter.filter(item.getDescription())).append(" ").append(mediaUrlFilter.filter(item.getContent()));
        } catch (final Exception e) {
            log.warn("Cannot read an artefact of type blog while idnexing", e);
        }
    }
}
 
Example 2
Source Project: obridge   Source File: XStreamFactoryTest.java    License: MIT License 6 votes vote down vote up
/**
 * Test of createXStream method, of class XStreamFactory.
 */
@Test
public void testCreateXStream() throws IOException {
    XStream x = XStreamFactory.createXStream();

    OBridgeConfiguration obc = new OBridgeConfiguration();
    obc.setJdbcUrl(connectionString);
    obc.setSourceRoot(File.createTempFile("ObjectGenerator", Long.toString(System.nanoTime())).getParentFile().toString());
    obc.setRootPackageName("hu.obridge.test");
    obc.setPackages(new Packages());

    String s = x.toXML(obc);

    System.out.println(s);

    Assert.assertTrue("starts with <configuration>", s.startsWith("<configuration>"));

}
 
Example 3
Source Project: ignite   Source File: IgniteNodeRunner.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Stores {@link IgniteConfiguration} to file as xml.
 *
 * @param cfg Ignite Configuration.
 * @param fileName A name of file where the configuration was stored.
 * @param resetMarshaller Reset marshaller configuration to default.
 * @param resetDiscovery Reset discovery configuration to default.
 * @throws IOException If failed.
 * @see #readCfgFromFileAndDeleteFile(String)
 */
public static void storeToFile(IgniteConfiguration cfg, String fileName,
    boolean resetMarshaller,
    boolean resetDiscovery) throws IOException, IgniteCheckedException {
    try (OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) {
        IgniteConfiguration cfg0 = new IgniteConfiguration(cfg);

        if (resetMarshaller)
            cfg0.setMarshaller(null);

        if (resetDiscovery)
            cfg0.setDiscoverySpi(null);

        cfg0.setWorkDirectory(U.defaultWorkDirectory());
        cfg0.setMBeanServer(null);
        cfg0.setGridLogger(null);

        new XStream().toXML(cfg0, out);
    }
}
 
Example 4
Source Project: kogito-runtimes   Source File: ReteooBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
private void checkRuleBase(final String name) throws Exception {
    final KnowledgeBuilderImpl builder = new KnowledgeBuilderImpl();
    builder.addPackageFromDrl( new InputStreamReader( getClass().getResourceAsStream( "test_" + name + ".drl" ) ) );
    InternalKnowledgePackage pkg = builder.getPackage("org.drools.compiler.test");

    final InternalKnowledgeBase kBase = (InternalKnowledgeBase) getKnowledgeBase();
    kBase.addPackage( pkg );

    if ( this.writeTree ) {
        writeRuleBase( kBase,
                       name );
    }

    final XStream xstream = createTrustingXStream();

    final InternalKnowledgeBase goodKBase = (InternalKnowledgeBase) xstream.fromXML( getClass().getResourceAsStream( name ) );

    nodesEquals( goodKBase.getRete(),
                 kBase.getRete() );
}
 
Example 5
Source Project: openhab-core   Source File: BindingInfoReader.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void registerAliases(XStream xstream) {
    xstream.alias("binding", BindingInfoXmlResult.class);
    xstream.alias("name", NodeValue.class);
    xstream.alias("description", NodeValue.class);
    xstream.alias("author", NodeValue.class);
    xstream.alias("service-id", NodeValue.class);
    xstream.alias("config-description", ConfigDescription.class);
    xstream.alias("config-description-ref", NodeAttributes.class);
    xstream.alias("parameter", ConfigDescriptionParameter.class);
    xstream.alias("parameter-group", ConfigDescriptionParameterGroup.class);
    xstream.alias("options", NodeList.class);
    xstream.alias("option", NodeValue.class);
    xstream.alias("filter", List.class);
    xstream.alias("criteria", FilterCriteria.class);
}
 
Example 6
Source Project: ET_Redux   Source File: ValueModelReferencedTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test of customizeXstream method, of class ValueModelReferenced.
 */
@Test
public void test_CustomizeXstream() {
   //This tests if the stream is customized.
    System.out.println("Testing ValueModelReferenced's customizeXstream(xstream xstream)");
    ValueModelReferenced instance = new ValueModelReferenced();
    XStream xstream = new XStream();
    instance.customizeXstream(xstream);
    boolean expResult = true;
    boolean result=false;
    String expResult2;
    String result2;
    if(xstream instanceof XStream){
        result=true;        
        expResult2="https://raw.githubusercontent.com/EARTHTIME/Schema/master/ValueModelXMLSchema.xsd";
        result2=instance.getValueModelXMLSchemaURL();
        assertEquals(expResult2,result2);            
                                 }
    assertEquals(expResult,result);
}
 
Example 7
private CSVInput createCSVInput(FileTab fileTab, String fileName) {
  boolean update = false;
  String searchCall = fileTab.getSearchCall();

  if (CollectionUtils.isNotEmpty(fileTab.getSearchFieldSet())
      || StringUtils.notBlank(searchCall)) {
    update = true;
  }

  XStream stream = XStreamUtils.createXStream();
  stream.processAnnotations(CSVInput.class);
  CSVInput input = (CSVInput) stream.fromXML("<input update=\"" + update + "\" />");
  input.setFileName(fileName);
  input.setSeparator(CSV_SEPRATOR);
  input.setTypeName(fileTab.getMetaModel().getFullName());
  input.setCallable(INPUT_CALLABLE);
  input.setSearch(null);
  input.setBindings(new ArrayList<>());
  input.setSearchCall(searchCall);

  return input;
}
 
Example 8
Source Project: openmeetings   Source File: LibraryChartLoader.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
public static List loadChart(File dir, String fileName) {
	try {
		File file = new File(dir, fileName + CHART_EXT);

		log.error("filepathComplete: {}", file);

		XStream xStream = new XStream(new XppDriver());
		xStream.setMode(XStream.NO_REFERENCES);

		try (InputStream is = new FileInputStream(file);
				BufferedReader reader = new BufferedReader(new InputStreamReader(is, UTF_8)))
		{
			return (List) xStream.fromXML(reader);
		}
	} catch (Exception err) {
		log.error("Unexpected error while loading chart", err);
	}
	return new ArrayList<>();
}
 
Example 9
Source Project: mamute   Source File: QuestionRssEntryFactory.java    License: Apache License 2.0 6 votes vote down vote up
public void writeEntry(RssContent rssContent, OutputStream output) {
	
	User author = rssContent.getAuthor();
	RssImageEntry imageEntry = new RssImageEntryBuilder()
		.withUrl(author.getSmallPhoto(gravatarUrl)).build();
	
	RssEntry entry = new RssEntryBuilder()
			.withAuthor(author.getName())
			.withTitle(rssContent.getTitle())
			.withLink(home + rssContent.getLinkPath())
			.withId(rssContent.getId().toString())
			.withDate(rssContent.getCreatedAt())
			.withImage(imageEntry).build();
	
	XStream xstream = buildXstream();

	xstream.processAnnotations(RssEntry.class);
	xstream.toXML(entry, output);
}
 
Example 10
Source Project: Cheddar   Source File: PendingResultHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishEvent_onOfferValue() throws Exception {
    // Given
    final TestValue testValue = new TestValue(randomString(), randomInt(100));
    final String pendingResultId = randomId();

    // When
    pendingResultHandler.offerValue(pendingResultId, testValue);

    // Then
    final ArgumentCaptor<PendingResultOfferedEvent> captor = ArgumentCaptor.forClass(PendingResultOfferedEvent.class);
    verify(mockSystemEventPublisher).publishEvent(captor.capture());
    final PendingResultOfferedEvent event = captor.getValue();
    assertEquals(applicationName, event.getTargetApplicationName());
    assertNull(event.getTargetApplicationVersion());
    assertEquals(pendingResultId, event.getPendingResultId());
    final Object actualResult = new XStream().fromXML(event.getResultXml());
    assertTrue(actualResult instanceof Result);
    assertEquals(((Result) actualResult).getValue(), testValue);
}
 
Example 11
Source Project: ET_Redux   Source File: SesarSample.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * gets an <code>XStream</code> reader. Creates, customizes, and returns
 * <code>XStream</code> for XML serialization
 *
 * @pre <code>XStream</code> package is available @post <code>XStream</code>
 * for XML decoding is returned
 *
 * @return <code>XStream</code> - for XML serialization decoding
 */
public static XStream getXStreamReader() {

    XStream xstream = new XStream(new DomDriver());

    customizeXstream(xstream);

    // http://x-stream.github.io/security.html
    XStream.setupDefaultSecurity(xstream);
    // clear out existing permissions and set own ones
    xstream.addPermission(NoTypePermission.NONE);
    // allow some basics
    xstream.addPermission(NullPermission.NULL);
    xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
    xstream.allowTypeHierarchy(Collection.class);
    xstream.addPermission(AnyTypePermission.ANY);

    return xstream;
}
 
Example 12
Source Project: brooklyn-server   Source File: CompilerCompatibilityTest.java    License: Apache License 2.0 6 votes vote down vote up
private void deserialize(String inputUrl) throws Exception {
    XStream xstream = new XStream() {
        @Override
        protected MapperWrapper wrapMapper(MapperWrapper next) {
            return new CompilerIndependentOuterClassFieldMapper(super.wrapMapper(next));
        }
    };

    InputStream in = this.getClass().getResourceAsStream(inputUrl);
    try {
        Object obj = xstream.fromXML(in);
        assertNonNullOuterFields(obj);
    } catch (Exception e) {
    	System.out.println(e.getMessage());
    	throw e;
    } finally {
        in.close();
    }
}
 
Example 13
Source Project: Cheddar   Source File: PendingResultHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPublishEvent_onOfferNullValue() throws Exception {
    // Given
    final Object value = null;
    final String pendingResultId = randomId();

    // When
    pendingResultHandler.offerValue(pendingResultId, value);

    // Then
    final ArgumentCaptor<PendingResultOfferedEvent> captor = ArgumentCaptor.forClass(PendingResultOfferedEvent.class);
    verify(mockSystemEventPublisher).publishEvent(captor.capture());
    final PendingResultOfferedEvent event = captor.getValue();
    assertEquals(applicationName, event.getTargetApplicationName());
    assertNull(event.getTargetApplicationVersion());
    assertEquals(pendingResultId, event.getPendingResultId());
    final Object actualResult = new XStream().fromXML(event.getResultXml());
    assertTrue(actualResult instanceof Result);
    assertNull(((Result) actualResult).getValue());
}
 
Example 14
Source Project: olat   Source File: ChangeEMailExecuteController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * change email
 * 
 * @param wControl
 * @return
 */
public boolean changeEMail(final WindowControl wControl) {
    final XStream xml = new XStream();
    final HashMap<String, String> mails = (HashMap<String, String>) xml.fromXML(tempKey.getEmailAddress());
    final Identity ident = getUserService().findIdentityByEmail(mails.get("currentEMail"));
    if (ident != null) {
        // change mail address
        getUserService().setUserProperty(ident.getUser(), UserConstants.EMAIL, mails.get("changedEMail"));
        // if old mail address closed then set the new mail address
        // unclosed
        final String value = getUserService().getUserProperty(ident.getUser(), UserConstants.EMAILDISABLED);
        if (value != null && value.equals("true")) {
            getUserService().setUserProperty(ident.getUser(), UserConstants.EMAILDISABLED, "false");
        }
        // success info message
        wControl.setInfo(pT.translate("success.change.email", new String[] { mails.get("currentEMail"), mails.get("changedEMail") }));
        // remove keys
        getUserService().setUserProperty(ident.getUser(), UserConstants.EMAILCHANGE, null);
        userRequest.getUserSession().removeEntryFromNonClearedStore(ChangeEMailController.CHANGE_EMAIL_ENTRY);
    }
    // delete registration key
    getRegistrationService().deleteTemporaryKeyWithId(tempKey.getRegistrationKey());

    return true;
}
 
Example 15
Source Project: ET_Redux   Source File: ReportSettingsInterface.java    License: Apache License 2.0 6 votes vote down vote up
/**
 *
 * @return
 */
public default XStream getXStreamReader() {

    XStream xstream = new XStream(new DomDriver());

    customizeXstream(xstream);

    // http://x-stream.github.io/security.html
    XStream.setupDefaultSecurity(xstream);
    // clear out existing permissions and set own ones
    xstream.addPermission(NoTypePermission.NONE);
    // allow some basics
    xstream.addPermission(NullPermission.NULL);
    xstream.addPermission(PrimitiveTypePermission.PRIMITIVES);
    xstream.allowTypeHierarchy(Collection.class);
    xstream.addPermission(AnyTypePermission.ANY);

    return xstream;
}
 
Example 16
Source Project: olat   Source File: ChecklistCourseNode.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Controller importNode(final File importDirectory, final ICourse course, final boolean unattendedImport, final UserRequest ureq, final WindowControl wControl) {
	final CoursePropertyManager cpm = course.getCourseEnvironment().getCoursePropertyManager();
	if (getChecklistKey(cpm) != null) {
		deleteChecklistKeyConf(cpm);
	}

	final File importFile = new File(importDirectory, getExportFilename());
	final String importContent = FileUtils.load(importFile, WebappHelper.getDefaultCharset());
	if (importContent == null || importContent.isEmpty()) { return null; }

	final XStream xstream = new XStream();
	Checklist checklist = (Checklist) xstream.fromXML(importContent);
	if (checklist != null) {
		checklist = ChecklistManager.getInstance().copyChecklist(checklist);
		setChecklistKey(cpm, checklist.getKey());
	}

	return null;
}
 
Example 17
Source Project: ET_Redux   Source File: UPbFraction.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param filename
 * @param doValidate
 * @return
 * @throws FileNotFoundException
 * @throws ETException
 * @throws BadOrMissingXMLSchemaException
 */
@Override
public Object readXMLObject(String filename, boolean doValidate)
        throws FileNotFoundException,
        ETException,
        FileNotFoundException,
        BadOrMissingXMLSchemaException {

    FractionI myUPbReduxFraction = null;

    BufferedReader reader = URIHelper.getBufferedReader(filename);

    if (reader != null) {
        boolean isValidOrAirplaneMode = true;

        XStream xstream = getXStreamReader();

        if (doValidate) {
            isValidOrAirplaneMode = URIHelper.validateXML(reader, filename, XMLSchemaURL);
        }

        if (isValidOrAirplaneMode) {
            // re-create reader
            reader = URIHelper.getBufferedReader(filename);
            try {
                myUPbReduxFraction = (FractionI) xstream.fromXML(reader);
            } catch (ConversionException e) {
                throw new ETException(null, e.getMessage());
            }
        } else {
            throw new ETException(null, "XML data file does not conform to schema.");
        }
    } else {
        throw new FileNotFoundException("Missing XML data file.");
    }

    return myUPbReduxFraction;

}
 
Example 18
Source Project: weixin-java-tools   Source File: XStreamTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private static XStream config_WxMpXmlOutVideoMessage() {
  XStream xstream = XStreamInitializer.getInstance();
  xstream.processAnnotations(WxMpXmlOutMessage.class);
  xstream.processAnnotations(WxMpXmlOutVideoMessage.class);
  xstream.processAnnotations(WxMpXmlOutVideoMessage.Video.class);
  return xstream;
}
 
Example 19
Source Project: depan   Source File: XStreamFactory.java    License: 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 20
Source Project: wish-pay   Source File: XMLBeanUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将XML转换为Bean
 *
 * @param clazzMap 别名-类名映射Map
 * @param xml      要转换为bean对象的xml字符串
 * @return Java Bean对象
 */
public static Object xml2Bean(Map<String, Class> clazzMap, String xml) {
    XStream xstream = new XStream();
    for (Iterator it = clazzMap.entrySet().iterator(); it.hasNext(); ) {
        Map.Entry<String, Class> m = (Map.Entry<String, Class>) it.next();
        xstream.alias(m.getKey(), m.getValue());
    }
    Object bean = xstream.fromXML(xml);
    return bean;
}
 
Example 21
@Override
public void registerConverters(XStream xstream) {
    xstream.registerConverter(new NodeValueConverter());
    xstream.registerConverter(new NodeListConverter());
    xstream.registerConverter(new NodeAttributesConverter());
    xstream.registerConverter(new ConfigDescriptionConverter());
    xstream.registerConverter(new ConfigDescriptionParameterConverter());
    xstream.registerConverter(new ConfigDescriptionParameterGroupConverter());
    xstream.registerConverter(new FilterCriteriaConverter());
}
 
Example 22
Source Project: olat   Source File: FeedManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * spring only
 */
protected FeedManagerImpl() {
    INSTANCE = this;
    xstream = new XStream();
    xstream.alias("feed", Feed.class);
    xstream.alias("item", Item.class);
}
 
Example 23
Source Project: Digital   Source File: SettingsBase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void attributeChanged() {
    XStream xStream = Circuit.getxStream();
    try (Writer out = new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8)) {
        out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xStream.marshal(attributes, new PrettyPrintWriter(out));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 24
Source Project: openmrs-module-initializer   Source File: InitializerSerializer.java    License: MIT License 5 votes vote down vote up
/**
 * @return Deserializer for {@link GlobalPropertiesConfig}
 */
public static XStream getGlobalPropertiesConfigSerializer() {
	final XStream xs = new InitializerSerializer();
	xs.alias("config", GlobalPropertiesConfig.class);
	xs.alias("globalProperty", GlobalProperty.class);
	xs.aliasField("value", GlobalProperty.class, "propertyValue");
	return xs;
}
 
Example 25
Source Project: weixin-java-tools   Source File: XStreamTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private static XStream config_WxCpXmlOutVideoMessage() {
  XStream xstream = XStreamInitializer.getInstance();
  xstream.processAnnotations(WxCpXmlOutMessage.class);
  xstream.processAnnotations(WxCpXmlOutVideoMessage.class);
  xstream.processAnnotations(WxCpXmlOutVideoMessage.Video.class);
  return xstream;
}
 
Example 26
Source Project: Digital   Source File: Configuration.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Loads a configuration
 *
 * @param in the file to load
 * @return the configuration
 * @throws IOException IOException
 */
public static Configuration load(InputStream in) throws IOException {
    try {
        XStream xStream = getxStream();
        return (Configuration) xStream.fromXML(in);
    } catch (RuntimeException e) {
        throw new IOException("error reading XML", e);
    }
}
 
Example 27
Source Project: amforeas   Source File: XmlXstreamTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static SuccessResponse successFromXML (final String xml) {
    XStream xStreamInstance = new XStream();
    xStreamInstance.setMode(XStream.NO_REFERENCES);
    xStreamInstance.autodetectAnnotations(false);
    xStreamInstance.alias("response", SuccessResponse.class);
    xStreamInstance.alias("row", Row.class);
    xStreamInstance.alias("cells", HashMap.class);
    xStreamInstance.alias("roi", Integer.class);
    xStreamInstance.registerConverter(new AmforeasMapConverter());
    xStreamInstance.addImplicitCollection(SuccessResponse.class, "rows", Row.class);
    return (SuccessResponse) xStreamInstance.fromXML(xml);
}
 
Example 28
Source Project: ET_Redux   Source File: MeasuredRatioModel.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * decodes <code>MeasuredRatioModel</code> from <code>file</code> specified
     * by argument <code>filename</code>
     *
     * @param filename location to read data from
     * @param doValidate the value of doValidate
     * @return <code>Object</code> - the <code>MeasuredRatioModel</code> created
     * from the specified XML <code>file</code>
     * @throws java.io.FileNotFoundException
     * @throws org.earthtime.XMLExceptions.BadOrMissingXMLSchemaException
     * @pre <code>filename</code> references an XML <code>file</code>
     * @post <code>MeasuredRatioModel</code> stored in <code>filename</code> is
     * returned
     */
    @Override
    public Object readXMLObject(String filename, boolean doValidate)
            throws FileNotFoundException, ETException, FileNotFoundException, BadOrMissingXMLSchemaException {
        ValueModel myValueModel = null;

        BufferedReader reader = URIHelper.getBufferedReader(filename);

        if (reader != null) {
            boolean isValidOrAirplaneMode = true;
            XStream xstream = getXStreamReader();

            if (doValidate) {
                isValidOrAirplaneMode = URIHelper.validateXML(reader, filename, getValueModelXMLSchemaURL());
            }

            if (isValidOrAirplaneMode) {
                // re-create reader
                reader = URIHelper.getBufferedReader(filename);
                try {
                    myValueModel = (MeasuredRatioModel) xstream.fromXML(reader);
                } catch (ConversionException e) {
                    throw new ETException(null, e.getMessage());
                }

////                System.out.println( "\nThis is your MeasuredRatioModel that was just read successfully:\n" );
//                String xml2 = getXStreamWriter().toXML( myValueModel );
//
//                System.out.println( xml2 );
//                System.out.flush();
            } else {
                throw new ETException(null, "XML data file does not conform to schema.");
            }
        } else {
            throw new FileNotFoundException("Missing XML data file.");
        }

        return myValueModel;
    }
 
Example 29
Source Project: engage-api-client   Source File: XmlApiResponse.java    License: Apache License 2.0 5 votes vote down vote up
private XStream prepareXStream(Class<? extends ApiResult> resultClass) {
	XmlApiReflectionProvider reflectionProvider = new XmlApiReflectionProvider(resultClass);
	XStream xStream = xStreamFactory.createXStream(reflectionProvider);
	
	xStream.processAnnotations(XmlApiResponseEnvelope.class);		
	xStream.addDefaultImplementation(resultClass, ApiResponse.class);
	xStream.processAnnotations(resultClass);

	return xStream;
}
 
Example 30
Source Project: gerrit-events   Source File: DeserializeApprovalTest.java    License: MIT License 5 votes vote down vote up
/**
 * Verifies old Approval gets deserialized correctly
 * (Approval::username String was replaced by Approval::by Account).
 *
 * @throws IOException if so.
 */
@SuppressWarnings("deprecation")
@Test
public void testApprovalUsernameMigration() throws IOException {
    XStream x = new XStream();
    Approval approval = (Approval)x.fromXML(getClass().getResourceAsStream("DeserializeApprovalTest.xml"));
    assertNotNull(approval.getBy());
    assertEquals("uname", approval.getBy().getUsername());
    assertEquals("uname", approval.getUsername());
    assertNull(Whitebox.getInternalState(approval, "username"));
}