com.thoughtworks.xstream.XStream Java Examples

The following examples show how to use com.thoughtworks.xstream.XStream. 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: BlogArtefactHandler.java    From olat with 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 File: ReteooBuilderTest.java    From kogito-runtimes with 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 #3
Source File: ChecklistCourseNode.java    From olat with 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 #4
Source File: IgniteNodeRunner.java    From ignite with 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 #5
Source File: XStreamFactoryTest.java    From obridge with 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 #6
Source File: BindingInfoReader.java    From openhab-core with 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 #7
Source File: ValueModelReferencedTest.java    From ET_Redux with 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 #8
Source File: DataImportServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #9
Source File: LibraryChartLoader.java    From openmeetings with 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 #10
Source File: QuestionRssEntryFactory.java    From mamute with 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 #11
Source File: PendingResultHandlerTest.java    From Cheddar with 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 #12
Source File: SesarSample.java    From ET_Redux with 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 #13
Source File: CompilerCompatibilityTest.java    From brooklyn-server with 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 #14
Source File: PendingResultHandlerTest.java    From Cheddar with 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 #15
Source File: ReportSettingsInterface.java    From ET_Redux with 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 File: ChangeEMailExecuteController.java    From olat with 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 #17
Source File: XMLTestCaseFinder.java    From gatf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<TestCase> resolveTestCases(File testCaseFile) throws Exception {
	XStream xstream = new XStream(new DomDriver("UTF-8"));
       XStream.setupDefaultSecurity(xstream);
       xstream.allowTypes(new Class[]{TestCase.class});
	xstream.processAnnotations(new Class[]{TestCase.class});
	xstream.alias("TestCases", List.class);
	List<TestCase> xmlTestCases = (List<TestCase>)xstream.fromXML(testCaseFile);
	return xmlTestCases;
}
 
Example #18
Source File: VersionedXmlDoc.java    From onedev with MIT License 5 votes vote down vote up
public static VersionedXmlDoc fromBean(@Nullable Object bean) {
	Document dom = DocumentHelper.createDocument();
	AppLoader.getInstance(XStream.class).marshal(bean, new Dom4JWriter(dom));
	VersionedXmlDoc versionedDom = new VersionedXmlDoc(dom);
	if (bean != null) {
		versionedDom.setVersion(MigrationHelper.getVersion(HibernateProxyHelper.getClassWithoutInitializingProxy(bean)));
	}
	return versionedDom;
}
 
Example #19
Source File: ResultSetController.java    From ZenQuery with Apache License 2.0 5 votes vote down vote up
@RequestMapping(
        value = "/{id}/size/{size}",
        method = RequestMethod.GET,
        produces = { "application/xml; charset=utf-8" })
public @ResponseBody
String currentQueryAsXML(
        @PathVariable Integer id,
        @PathVariable Integer size
) {
    List<Map<String, Object>> rows = getRows(id, null, size);

    XStream stream = getXMLStream();

    return stream.toXML(rows.toArray());
}
 
Example #20
Source File: OverrideMethodsTestCase.java    From Pydev with Eclipse Public License 1.0 5 votes vote down vote up
private MockupOverrideMethodsConfig initConfig() {
    MockupOverrideMethodsConfig config = null;
    XStream xstream = new XStream();
    xstream.alias("config", MockupOverrideMethodsConfig.class);

    if (data.config.length() > 0) {
        config = (MockupOverrideMethodsConfig) xstream.fromXML(data.getConfigContents());
    } else {
        fail("Could not unserialize configuration");
    }
    return config;
}
 
Example #21
Source File: UPbFraction.java    From ET_Redux with 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 #22
Source File: XStreamTransformer.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
/**
 * 会自动注册该类及其子类.
 *
 * @param clz 要注册的类
 */
private static void registerClass(Class<?> clz) {
  XStream xstream = XStreamInitializer.getInstance();

  xstream.processAnnotations(clz);
  xstream.processAnnotations(getInnerClasses(clz));
  if (clz.equals(WxMpXmlMessage.class)) {
    // 操蛋的微信,模板消息推送成功的消息是MsgID,其他消息推送过来是MsgId
    xstream.aliasField("MsgID", WxMpXmlMessage.class, "msgId");
  }

  register(clz, xstream);
}
 
Example #23
Source File: XStreamTransformer.java    From weixin-java-tools with 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 #24
Source File: SerializationService.java    From pentaho-aggdesigner with GNU General Public License v2.0 5 votes vote down vote up
public void deserializeConnection(Schema schema, String rdbmsXml, String schemaXml) {
  XStream xstream = getXStream(schema);
  DatabaseMeta databaseMeta = (DatabaseMeta)xstream.fromXML(rdbmsXml);
  SchemaModel schemaModel = (SchemaModel)xstream.fromXML(schemaXml);
  
  //save off cubeName since setSelectedSchemaModel will clear it out
  String cubeName = schemaModel.getCubeName();
  
  connectionModel.setDatabaseMeta(databaseMeta);
  connectionModel.setSelectedSchemaModel(schemaModel);
  
  connectionModel.setCubeName(cubeName);
}
 
Example #25
Source File: ConfigDescriptionReader.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void registerAliases(XStream xstream) {
    xstream.alias("config-descriptions", List.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 #26
Source File: XStreamDeepClone.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Object doClone(Object objectToClone) {
    XStream xStream = xStreamSupplier.get();
    final String serialized = xStream.toXML(objectToClone);
    final Object result = xStream.fromXML(serialized);
    if (result == null) {
        throw new IllegalStateException("Unable to deep clone object of type '" + objectToClone.getClass().getName()
                + "'. Please report the issue on the Quarkus issue tracker.");
    }
    return result;
}
 
Example #27
Source File: ConverterTestFixture.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
protected Object assertX(Object obj, String fmt) {
    XStream xstream = new XStream();
    registerConverters(xstream);
    String s1 = xstream.toXML(obj);
    Assert.assertEquals(s1, fmt);
    Object out = xstream.fromXML(s1);
    Assert.assertEquals(out, obj);
    return out;
}
 
Example #28
Source File: XStreamHelper.java    From olat with Apache License 2.0 5 votes vote down vote up
/**
 * Write a an object to an output stream. UTF-8 is used as encoding in the XML declaration. It is useful to set attribute and field mappers to allow later refactoring
 * of the class!
 * 
 * @param xStream
 *            The (configured) xStream.
 * @param os
 * @param obj
 *            the object to be serialized
 */
public static void writeObject(XStream xStream, OutputStream os, Object obj) {
    try {
        OutputStreamWriter osw = new OutputStreamWriter(os, ENCODING);
        String data = xStream.toXML(obj);
        data = "<?xml version=\"1.0\" encoding=\"" + ENCODING + "\"?>\n" + data; // give a decent header with the encoding used
        osw.write(data);
        osw.close();
    } catch (Exception e) {
        throw new OLATRuntimeException(XStreamHelper.class, "Could not write object to stream.", e);
    } finally {
        FileUtils.closeSafely(os);
    }
}
 
Example #29
Source File: MorphologicalServiceLocalImpl.java    From olat with Apache License 2.0 5 votes vote down vote up
@Override
public ArrayList<String> getFlexions(String partOfSpeech, String word) {
    XStream xstream = XStreamHelper.createXStreamInstance();
    File replyFile = new File(PATH_TO_MS_REPLY_XML);
    xstream.alias("msreply", FlexionReply.class);
    xstream.alias("wordform", String.class);
    Object msReply = XStreamHelper.readObject(xstream, replyFile);
    FlexionReply flexionReply = (FlexionReply) msReply;
    ArrayList<String> stemWithWordforms = flexionReply.getStem();
    return stemWithWordforms;
}
 
Example #30
Source File: BindingInfoReader.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void registerConverters(XStream xstream) {
    xstream.registerConverter(new NodeAttributesConverter());
    xstream.registerConverter(new NodeValueConverter());
    xstream.registerConverter(new BindingInfoConverter());
    xstream.registerConverter(new ConfigDescriptionConverter());
    xstream.registerConverter(new ConfigDescriptionParameterConverter());
    xstream.registerConverter(new ConfigDescriptionParameterGroupConverter());
    xstream.registerConverter(new FilterCriteriaConverter());
}