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

The following examples show how to use com.thoughtworks.xstream.XStream#fromXML() . 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: SocketController.java    From Tatala-RPC with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize socket server connections through xml configuration file.
 */
@SuppressWarnings("unchecked")
public static void initialize(){
	
	XStream xstream = new XStream();
	xstream.alias("connections", List.class);
	xstream.alias("connection", SocketConnection.class);
	
	InputStream is = SocketController.class.getClassLoader().getResourceAsStream("controller.xml");
	if(is == null){
		throw new RuntimeException("Can't find controller.xml");
	}
	connectionList = (List<SocketConnection>)xstream.fromXML(is);

	int poolSize = Configuration.getIntProperty("Client.Socket.poolSize", DEFAULT_CLIENT_POOL_SIZE);
	executorService = Executors.newFixedThreadPool(poolSize, new DaemonThreadFactory());
}
 
Example 3
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 4
Source File: EPSettingsManager.java    From olat with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Map<String, Boolean> getArtefactAttributeConfig(final Identity ident) {
    final PropertyManager pm = PropertyManager.getInstance();
    final PropertyImpl p = pm.findProperty(ident, null, null, EPORTFOLIO_CATEGORY, EPORTFOLIO_ARTEFACTS_ATTRIBUTES);
    TreeMap<String, Boolean> disConfig;
    if (p == null) {
        disConfig = new TreeMap<String, Boolean>();
        // TODO: epf: maybe there is a better way to get the default set of
        // attributes from an artefact ?!
        disConfig.put("artefact.author", true);
        disConfig.put("artefact.description", false);
        disConfig.put("artefact.reflexion", false);
        disConfig.put("artefact.source", true);
        disConfig.put("artefact.sourcelink", false);
        disConfig.put("artefact.title", true);
        disConfig.put("artefact.date", true);
        disConfig.put("artefact.tags", true);
        disConfig.put("artefact.used.in.maps", true);
        disConfig.put("artefact.handlerdetails", false);
    } else {
        final XStream xStream = XStreamHelper.createXStreamInstance();
        disConfig = (TreeMap<String, Boolean>) xStream.fromXML(p.getTextValue());
    }
    return disConfig;
}
 
Example 5
Source File: XmlBeanJsonConverUtil.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
/**
 * 把XML转成对象
 *
 * @param xmlStr
 * @return Object
 */
@SuppressWarnings("unchecked")
public static <T> T xmlStringToBean(String xmlStr, Class<T> cls) {
	XStream xstream = new XStream(new DomDriver());
	xstream.processAnnotations(cls);
	xstream.autodetectAnnotations(true);
	return (T) xstream.fromXML(xmlStr);
}
 
Example 6
Source File: EnviarLoteRpsResposta.java    From nfse with MIT License 5 votes vote down vote up
public static EnviarLoteRpsResposta toPojo(String xml) {
  XStream xstream = new XStream();
  xstream.setMode(XStream.NO_REFERENCES);
  xstream.autodetectAnnotations(true);
  xstream.ignoreUnknownElements();
  xstream.alias("EnviarLoteRpsResposta", EnviarLoteRpsResposta.class);
  EnviarLoteRpsResposta enviarLoteRpsResposta = (EnviarLoteRpsResposta) xstream.fromXML(xml);
  return enviarLoteRpsResposta;
}
 
Example 7
Source File: MessageUtils.java    From wechat-core with Apache License 2.0 5 votes vote down vote up
public static <T> T xml2Message(String xml, Class<T> clazz) {
    XStream xstream = newXStreamInstance();
    //先忽略未知的元素,防止从xml转换成对象时报错
    xstream.ignoreUnknownElements();
    xstream.processAnnotations(clazz);
    return (T) xstream.fromXML(xml);
}
 
Example 8
Source File: XmlBeanJsonConverUtil.java    From aaden-pay with Apache License 2.0 5 votes vote down vote up
/**
 * 把XML转成对象
 *
 * @param input
 *            InputStream
 * @return Object
 */
@SuppressWarnings("unchecked")
public static <T> T xmlStringToBean(InputStream input, Class<T> cls) {
	XStream xstream = new XStream(new DomDriver());
	xstream.processAnnotations(cls);
	xstream.autodetectAnnotations(true);
	return (T) xstream.fromXML(input);
}
 
Example 9
Source File: XMLBeanUtils.java    From wish-pay with 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 10
Source File: DeserializeApprovalTest.java    From gerrit-events with 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"));
}
 
Example 11
Source File: ZWaveProductDatabase.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
private void loadDatabase() {
    URL entry = FrameworkUtil.getBundle(ZWaveProductDatabase.class).getEntry("database/products.xml");
    if (entry == null) {
        database = null;
        logger.error("Unable to load ZWave product database!");
        return;
    }

    XStream xstream = new XStream(new StaxDriver());
    xstream.alias("Manufacturers", ZWaveDbRoot.class);
    xstream.alias("Manufacturer", ZWaveDbManufacturer.class);
    xstream.alias("Product", ZWaveDbProduct.class);
    xstream.alias("Reference", ZWaveDbProductReference.class);

    xstream.processAnnotations(ZWaveDbRoot.class);

    try {
        // this.Manufacturer = (ZWaveDbManufacturer)
        InputStream x = entry.openStream();
        database = (ZWaveDbRoot) xstream.fromXML(x);
        if (database == null) {
            return;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 12
Source File: ZigBeeDataStore.java    From com.zsmartsystems.zigbee with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ZigBeeNodeDao readNode(IeeeAddress address) {
    XStream stream = openStream();
    File file = getFile(address);

    ZigBeeNodeDao node = null;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
        node = (ZigBeeNodeDao) stream.fromXML(reader);
        logger.info("{}: ZigBee reading network state complete.", address);
    } catch (IOException e) {
        logger.error("{}: Error reading network state: ", address, e);
    }

    return node;
}
 
Example 13
Source File: AbstractRatiosDataModel.java    From ET_Redux with Apache License 2.0 5 votes vote down vote up
/**
 * decodes <code>AbstractRatiosDataModel</code> from <code>file</code>
 * specified by argument <code>filename</code>
 *
 * @throws org.earthtime.exceptions.ETException
 * @pre <code>filename</code> references an XML <code>file</code>
 * @post <code>AbstractRatiosDataModel</code> stored in
 * <code>filename</code> is returned
 *
 * @param filename location to read data from
 * @param doValidate
 * @return <code>Object</code> - the <code>AbstractRatiosDataModel</code>
 * created from the specified XML <code>file</code>
 * @throws java.io.FileNotFoundException
 * @throws org.earthtime.XMLExceptions.BadOrMissingXMLSchemaException
 */
@Override
public AbstractRatiosDataModel readXMLObject(String filename, boolean doValidate)
        throws FileNotFoundException, ETException, BadOrMissingXMLSchemaException {
    AbstractRatiosDataModel myModelClassInstance = null;

    BufferedReader reader = URIHelper.getBufferedReader(filename);

    if (reader != null) {
        XStream xstream = getXStream();

        boolean isValidOrAirplaneMode = true;

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

        if (isValidOrAirplaneMode) {
            // re-create reader
            reader = URIHelper.getBufferedReader(filename);
            try {
                myModelClassInstance = (AbstractRatiosDataModel) xstream.fromXML(reader);
                myModelClassInstance.initializeModel();
            } 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 myModelClassInstance;
}
 
Example 14
Source File: TestConfig.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
public static TestConfig fromXml(InputStream is) {
  XStream xstream = XStreamInitializer.getInstance();
  xstream.processAnnotations(TestConfig.class);
  return (TestConfig) xstream.fromXML(is);
}
 
Example 15
Source File: XmlApiResponse.java    From engage-api-client with Apache License 2.0 4 votes vote down vote up
private XmlApiResponseEnvelope processRequest(Class<? extends ApiResult> resultClass) {
	XStream xStream = prepareXStream(resultClass);
	return (XmlApiResponseEnvelope) xStream.fromXML(new StringReader(responseText));
}
 
Example 16
Source File: ExperimentBackwardAgent.java    From gama with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean backward(final IScope scope) {
	final boolean result = true;
	GamaNode<String> previousNode;

	try {
		if (canStepBack()) {
			previousNode = currentNode.getParent();
			final String previousState = previousNode.getData();

			if (previousState != null) {
				final ConverterScope cScope = new ConverterScope(scope);
				final XStream xstream = StreamConverter.loadAndBuild(cScope);

				// get the previous state
				final SavedAgent agt = (SavedAgent) xstream.fromXML(previousState);

				// Update of the simulation
				final SimulationAgent currentSimAgt = getSimulation();

				currentSimAgt.updateWith(scope, agt);

				// useful to recreate the random generator
				final int rngUsage = currentSimAgt.getRandomGenerator().getUsage();
				final String rngName = currentSimAgt.getRandomGenerator().getRngName();
				final Double rngSeed = currentSimAgt.getRandomGenerator().getSeed();

				final IOutputManager outputs = getSimulation().getOutputManager();
				if (outputs != null) {
					outputs.step(scope);
				}

				// Recreate the random generator and set it to the same state as the saved one
				if (((ExperimentPlan) this.getSpecies()).keepsSeed()) {
					currentSimAgt.setRandomGenerator(new RandomUtils(rngSeed, rngName));
					currentSimAgt.getRandomGenerator().setUsage(rngUsage);
				} else {
					currentSimAgt.setRandomGenerator(new RandomUtils(super.random.next(), rngName));
				}

				currentNode = currentNode.getParent();
			}
		}
	} finally {
		informStatus();

		// TODO a remettre
		// final int nbThreads =
		// this.getSimulationPopulation().getNumberOfActiveThreads();

		// if (!getSpecies().isBatch() && getSimulation() != null) {
		// scope.getGui().informStatus(
		// getSimulation().getClock().getInfo() + (nbThreads > 1 ? " (" +
		// nbThreads + " threads)" : ""));
		// }
	}
	return result;
}
 
Example 17
Source File: XmlUtil.java    From EasyEE with MIT License 4 votes vote down vote up
public static Object fromXml(String xml, Class<?> objClass) {
	XStream xStream = new XStream();
	xStream.processAnnotations(objClass);
	return xStream.fromXML(xml);
}
 
Example 18
Source File: WxCpDemoInMemoryConfigStorage.java    From weixin-java-tools with Apache License 2.0 4 votes vote down vote up
public static WxCpDemoInMemoryConfigStorage fromXml(InputStream is) {
  XStream xstream = XStreamInitializer.getInstance();
  xstream.processAnnotations(WxCpDemoInMemoryConfigStorage.class);
  return (WxCpDemoInMemoryConfigStorage) xstream.fromXML(is);
}
 
Example 19
Source File: XmlUtils.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public static <T> T toBeanFrom(File file, Object...alias){
	XStream stream = createXStream(alias);
	String xml = FileUtils.readAsString(file);
	return (T)stream.fromXML(xml);
}
 
Example 20
Source File: XmlUtils.java    From aaden-pay with Apache License 2.0 3 votes vote down vote up
/**
 * 将XML转为对象
 * 
 * @param stream
 *            input输入流
 * @param obj
 *            需转换的对象
 * @return 转换对象
 */
public static Object simpleXmlToObject(InputStream stream, Object obj) {
	XStream xStream = new XStream(new DomDriver());
	toListGenericsAlias(xStream, obj);
	xStream.alias(obj.getClass().getSimpleName(), obj.getClass());
	Object reobj = xStream.fromXML(stream);
	return reobj;
}