/** * @param systemcode 要查询的系统别 房贷/消费信贷(1/2) 数据 * @return */ public List<T100101ResponseRecord> start(String systemcode) { XStream xstream = new XStream(new DomDriver()); xstream.processAnnotations(T100101Request.class); xstream.processAnnotations(T100101Response.class); T100101Request request = new T100101Request(); request.initHeader("0100", "100101", "3"); // 查询 房贷/消费信贷(1/2) 数据 request.setStdcxlx(systemcode); int pkgcnt = 100; int startnum = 1; request.setStdymjls(String.valueOf(pkgcnt)); // request.setStdqsjls("1"); NewCmsManager ncm = new NewCmsManager(); List<T100101ResponseRecord> responseList = new ArrayList(); int totalcount = processTxn(responseList, ncm, xstream, request, pkgcnt, startnum); logger.info("received list zise:" + responseList.size()); if (totalcount != responseList.size()) { logger.error("获取还款数据笔数有误!应收笔数:" + responseList.size() + "实收笔数:" + totalcount); throw new RuntimeException("获取还款数据笔数有误."); } return responseList; }
private Set<String> getResourceNames( String namespaceName, Configuration config, String resourceType) throws MalformedURLException { Map<String, String> valueMap = new HashMap<String, String>(); Azure azure = config.getAzure(); valueMap.put("SubscriptionId", azure.getSubscriptionId()); valueMap.put("NameSpace", namespaceName); valueMap.put("ResourceType", resourceType); StrSubstitutor strSubstitutor = new StrSubstitutor(valueMap); String resourceNamesUrlString = strSubstitutor.replace(RESOURCE_NAMES_URL); URL resourceNamesUrl = new URL(resourceNamesUrlString); if (logger.isDebugEnabled()) { logger.debug("Request resource from URL [ " + resourceNamesUrl + " ]"); } InputStream inputStream = processGetRequest( resourceNamesUrl, azure.getKeyStoreLocation(), azure.getKeyStorePassword()); XStream xstream = new XStream(); xstream.ignoreUnknownElements(); xstream.processAnnotations(Feed.class); xstream.processAnnotations(Entry.class); Feed feed = (Feed) xstream.fromXML(inputStream); Set<String> topicNames = new HashSet<String>(); List<Entry> entries = feed.getEntries(); if (entries != null && !entries.isEmpty()) { for (Entry entry : entries) { topicNames.add(entry.getTitle()); } } return topicNames; }
private void getRecords( final int maxRecords, final int startPosition, final int totalResults, final int expectedNext, final int expectedReturn) throws JAXBException, UnsupportedEncodingException { XStream xstream = createXStream(CswConstants.GET_RECORDS_RESPONSE); GetRecordsType query = new GetRecordsType(); query.setMaxRecords(BigInteger.valueOf(maxRecords)); query.setStartPosition(BigInteger.valueOf(startPosition)); CswRecordCollection collection = createCswRecordCollection(query, totalResults); collection.setStartPosition(startPosition); String xml = xstream.toXML(collection); JAXBElement<GetRecordsResponseType> jaxb = (JAXBElement<GetRecordsResponseType>) getJaxBContext() .createUnmarshaller() .unmarshal(new ByteArrayInputStream(xml.getBytes("UTF-8"))); GetRecordsResponseType response = jaxb.getValue(); assertThat( response.getSearchResults().getNumberOfRecordsMatched().intValue(), equalTo(totalResults)); assertThat( response.getSearchResults().getNumberOfRecordsReturned().intValue(), equalTo(expectedReturn)); // assertThat(response.getSearchResults().getAbstractRecord().size(), // equalTo(expectedReturn)); assertThat(response.getSearchResults().getNextRecord().intValue(), equalTo(expectedNext)); }
public static Object getObjectFromXML(String xml, Class tClass) { // 将从API返回的XML数据映射到Java对象 XStream xStreamForResponseData = new XStream(); xStreamForResponseData.alias("xml", tClass); xStreamForResponseData.ignoreUnknownElements(); // 暂时忽略掉一些新增的字段 return xStreamForResponseData.fromXML(xml); }
private static XStream config_WxCpXmlOutVideoMessage() { XStream xstream = XStreamInitializer.getInstance(); xstream.processAnnotations(WxCpXmlOutMessage.class); xstream.processAnnotations(WxCpXmlOutVideoMessage.class); xstream.processAnnotations(WxCpXmlOutVideoMessage.Video.class); return xstream; }
private void readMigrations( SortedMap<Long, List<ConfigMigrationStategy>> configMigrations, URL url) throws IOException { InputStreamReader r = null; try { r = new InputStreamReader(url.openStream(), ConfigUtilConstants.DEFAULT_TEXT_ENCODING); XStream x = createXStream(); ConfigManagerMigrations migrations = (ConfigManagerMigrations) x.fromXML(r); for (Migration m : migrations.getMigrationList()) { long versionTarget = m.getTargetVersion(); String className = m.getMigrationClass(); String[] constructorArguments = m.getArguments(); List<ConfigMigrationStategy> configMigrationForVersionTarget = configMigrations.get(versionTarget); if (configMigrationForVersionTarget == null) { configMigrationForVersionTarget = new ArrayList(); configMigrations.put(versionTarget, configMigrationForVersionTarget); } ConfigMigrationStategy configMigration = createMigrationStrategy(versionTarget, className, constructorArguments); configMigrationForVersionTarget.add(configMigration); } } finally { try { if (r != null) r.close(); } catch (IOException e) { ConfigLogImplementation.logMethods.error( "Failed to close ConfigMigration InputStream from URL " + url, e); } } }
public List<SequenciaDidatica> listaDeSequenciaDidatica(String filtro) { XStream x = new XStream(new DomDriver()); int indice = Integer.parseInt(IGEDProperties.getInstance().getPropety("indicesSequencia")); String path = IGEDProperties.getInstance().getPropety("sequenciaPath"); sequenciasDidatica = new ArrayList<SequenciaDidatica>(); if (filtro.equals("") || filtro == null) { try { for (int i = 1; i < indice; i++) { FileInputStream input = new FileInputStream(path + "/sequencia-" + i + ".xml"); x.alias("sequenciaDidatica", SequenciaDidatica.class); SequenciaDidatica sequencia = (SequenciaDidatica) x.fromXML(input); sequenciasDidatica.add(sequencia); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } return sequenciasDidatica; }
/** * Tests {@link * TriggerContextConverter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext)}. With "matrix_build.xml" as input. * * @throws Exception if so. */ @Test public void testUnmarshalOldMatrixBuild() throws Exception { XStream xStream = new XStream2(); xStream.registerConverter(new TriggerContextConverter()); xStream.alias("matrix-run", MatrixRun.class); Object obj = xStream.fromXML(getClass().getResourceAsStream("matrix_build.xml")); assertTrue(obj instanceof MatrixRun); MatrixRun run = (MatrixRun) obj; Cause.UpstreamCause upCause = run.getCause(Cause.UpstreamCause.class); List upstreamCauses = Whitebox.getInternalState(upCause, "upstreamCauses"); GerritCause cause = (GerritCause) upstreamCauses.get(0); assertNotNull(cause.getEvent()); assertEquals("platform/project", cause.getEvent().getChange().getProject()); assertNotNull(cause.getContext()); assertNotNull(cause.getContext().getThisBuild()); assertEquals("Gerrit_master-theme_matrix", cause.getContext().getThisBuild().getProjectId()); assertEquals(102, cause.getContext().getThisBuild().getBuildNumber().intValue()); assertNotNull(cause.getContext().getOthers()); assertEquals(1, cause.getContext().getOthers().size()); TriggeredItemEntity entity = cause.getContext().getOthers().get(0); assertEquals("master-theme", entity.getProjectId()); assertNull(entity.getBuildNumber()); }
/** * Tests {@link TriggerContextConverter#marshal(Object, * com.thoughtworks.xstream.io.HierarchicalStreamWriter, * com.thoughtworks.xstream.converters.MarshallingContext)}. With an empty list of "others". * * @throws Exception if so. */ @Test public void testMarshalNoOthers() throws Exception { TriggeredItemEntity entity = new TriggeredItemEntity(100, "projectX"); PatchsetCreated event = Setup.createPatchsetCreated(); TriggerContext context = new TriggerContext(event); context.setThisBuild(entity); context.setOthers(new LinkedList<TriggeredItemEntity>()); TestMarshalClass t = new TestMarshalClass(context, "Bobby", new TestMarshalClass(context, "SomeoneElse")); XStream xStream = new XStream2(); xStream.registerConverter(new TriggerContextConverter()); String xml = xStream.toXML(t); TestMarshalClass readT = (TestMarshalClass) xStream.fromXML(xml); assertNotNull(readT.getEntity()); assertNotNull(readT.getEntity().getEvent()); assertNotNull(readT.getEntity().getThisBuild()); assertEquals("project", readT.getEntity().getEvent().getChange().getProject()); assertEquals(100, readT.getEntity().getThisBuild().getBuildNumber().intValue()); assertEquals("projectX", readT.getEntity().getThisBuild().getProjectId()); assertSame(readT.getEntity(), readT.getTestClass().getEntity()); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { action = request.getParameter("action"); jspPage = "/Home.jsp"; boolean dispacher = true; if ((action == null) || action.length() < 1) { jspPage = "/Home.jsp"; super.dispatch(jspPage, request, response); } if ("default".equals(action)) { jspPage = "/Home.jsp"; } else if ("restricciones".equals(action)) { String idCliente = request.getParameter("cliente"); RestriccionVOList list = sistema.getRestriccionesCliente(idCliente); XStream xstream = new XStream(new DomDriver()); xstream.alias("restriccion", RestriccionVO.class); xstream.alias("restricciones", RestriccionVOList.class); xstream.addImplicitCollection(RestriccionVOList.class, "restricciones"); String xml = xstream.toXML(list); response.setContentType("text/plain"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(xml); dispacher = false; } if (dispacher) super.dispatch(jspPage, request, response); }
/** * Tests {@link * TriggerContextConverter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, * com.thoughtworks.xstream.converters.UnmarshallingContext)}. With "retriggerAction_oldData2.xml" * as input. * * @throws Exception if so. */ @Test public void testUnmarshalOldData2() throws Exception { XStream xStream = new XStream2(); xStream.registerConverter(new TriggerContextConverter()); Object obj = xStream.fromXML(getClass().getResourceAsStream("retriggerAction_oldData2.xml")); assertTrue(obj instanceof RetriggerAction); RetriggerAction action = (RetriggerAction) obj; TriggerContext context = Whitebox.getInternalState(action, "context"); assertNotNull(context.getEvent()); assertEquals( "semctools/hudson/plugins/gerrit-trigger-plugin", context.getEvent().getChange().getProject()); assertEquals("1", context.getEvent().getPatchSet().getNumber()); assertNotNull(context.getThisBuild()); assertEquals(6, context.getThisBuild().getBuildNumber().intValue()); assertEquals("EXPERIMENTAL_Gerrit_Trigger_1", context.getThisBuild().getProjectId()); assertNotNull(context.getOthers()); assertEquals(2, context.getOthers().size()); TriggeredItemEntity entity = context.getOthers().get(0); assertEquals(16, entity.getBuildNumber().intValue()); assertEquals("EXPERIMENTAL_Gerrit_Trigger_2", entity.getProjectId()); entity = context.getOthers().get(1); assertEquals(15, entity.getBuildNumber().intValue()); assertEquals("EXPERIMENTAL_Gerrit_Trigger_3", entity.getProjectId()); }
/** * @param xstreamObject not null * @param jarFile not null * @param packageFilter a package name to filter. */ private void addAlias(XStream xstreamObject, File jarFile, String packageFilter) { JarInputStream jarStream = null; try { jarStream = new JarInputStream(new FileInputStream(jarFile)); JarEntry jarEntry = jarStream.getNextJarEntry(); while (jarEntry != null) { if (jarEntry.getName().toLowerCase(Locale.ENGLISH).endsWith(".class")) { String name = jarEntry.getName().substring(0, jarEntry.getName().indexOf(".")); name = name.replaceAll("/", "\\."); if (name.indexOf(packageFilter) != -1) { try { Class<?> clazz = ClassUtils.getClass(name); String alias = StringUtils.lowercaseFirstLetter(ClassUtils.getShortClassName(clazz)); xstreamObject.alias(alias, clazz); if (!clazz.equals(Model.class)) { xstreamObject.omitField(clazz, "modelEncoding"); // unnecessary field } } catch (ClassNotFoundException e) { e.printStackTrace(); } } } jarStream.closeEntry(); jarEntry = jarStream.getNextJarEntry(); } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug("IOException: " + e.getMessage(), e); } } finally { IOUtil.close(jarStream); } }
@Override public Set<Currency> getCurrencies() throws AmountMoneyCurrencyStorageException { if (!file.exists()) { LOGGER.info( String.format( "Currency storage file '%s' doesn't exist, creating it " + "with default currencies", file)); if (!file.getParentFile().exists()) { if (!file.getParentFile().mkdirs()) { throw new AmountMoneyCurrencyStorageException( String.format( "Currency " + "storage file's parent directory '%s' couldn't " + "be created", file.getParentFile())); } } saveCurrencies(AmountMoneyComponent.DEFAULT_CURRENCIES); } try { InputStream inputStream = new FileInputStream(file); XStream xStream = new XStream(); xStream.registerConverter(CURRENCY_CONVERTER); Set<Currency> currencies = (Set<Currency>) xStream.fromXML(inputStream); if (currencies.isEmpty()) { LOGGER.info( String.format( "Currency storage file '%s' contains " + "0 currency, using default currencies", file)); saveCurrencies(AmountMoneyComponent.DEFAULT_CURRENCIES); return AmountMoneyComponent.DEFAULT_CURRENCIES; } return currencies; } catch (IOException ex) { throw new AmountMoneyCurrencyStorageException(ex); } }
/** * Loads the settings from the given directories (Windows: "APPDATA", Unix: ".user.home") The * settings loaded from the .xml format and has the name "fmsettings". If there is no "fmsettings" * file a new one with the following default values will be created fontsize: 12, max loop count: * 3, Z3 timeout: 20000 and a empty Z3 Path and Default Path */ private Settings loadSettings() { Settings tempSettings = null; XStream xstream = new XStream(); String settingsPath; // Windows settingsPath = System.getenv("APPDATA"); // Unix if (settingsPath == null) { settingsPath = System.getProperty("user.home"); } File file = new File(settingsPath + File.separatorChar + ".fmsettings"); if (file.isFile()) { // load from settings from "fmsettings" file try { tempSettings = (Settings) xstream.fromXML(file); } catch (CannotResolveClassException e) { tempSettings = defaultSettings(); } catch (StreamException e) { tempSettings = defaultSettings(); } } else { tempSettings = defaultSettings(); } return tempSettings; }
/** Loads the list of commands from one game */ @Override public List<Object> getAll(int gameID) { try { db.start(); DBCollection collection = db.getDB().getCollection("moves"); XStream xStream = new XStream(); DBCursor cursor = collection.find(); if (cursor == null) return null; List<Object> commands = new ArrayList<Object>(); while (cursor.hasNext()) { DBObject obj = cursor.next(); String xml = (String) obj.get(Integer.toString(gameID)); if (xml != null) commands.add((Object) xStream.fromXML(xml)); } db.stop(true); return commands; } catch (Exception e) { e.printStackTrace(); return null; } }
public static void marshal(APIRequest request, Object responseRoot, Writer writer) throws FatalException, IOException { // get the javascript callback, if present String jsCallback = null; if (request != null) { try { jsCallback = request.getParameter(Constants.Request.JSCALLBACK, false); } catch (InvalidParameterException e) { // it's okay to not have one } } // get an xstream using a json dirver XStream xstream = new XStream(new JsonHierarchicalStreamDriver()); xstream.setMode(XStream.NO_REFERENCES); // alias top-level types xstream.alias("response", ResponseType.class); // first write out the jscallback method name if (!StringUtil.isNullOrEmpty(jsCallback)) { writer.write(jsCallback + "("); } // write the json to our writer // NOTE: all element names will be camel case and not cased as in JAXB xstream.marshal(responseRoot, new JsonWriter(writer)); // close off the method if jscallback was given if (!StringUtil.isNullOrEmpty(jsCallback)) { writer.write(")"); } }
// TODO Carregar campos a partir do XML de um .ktr @SuppressWarnings("unchecked") @Override public void loadXML( Node stepDomNode, List<DatabaseMeta> databases, Map<String, Counter> sequenceCounters) throws KettleXMLException { try { XStream xs = new XStream(new DomDriver()); StringWriter sw = new StringWriter(); Transformer t = TransformerFactory.newInstance().newTransformer(); // IPC: se algum colocar um caracter, seja qual for, no getXML() o // getFirstChild() para de funcionar aqui! t.transform( new DOMSource( XMLHandler.getSubNode(stepDomNode, Field.DATA_ROOT_NODE.name()).getFirstChild()), new StreamResult(sw)); Map<String, Object> data = (Map<String, Object>) xs.fromXML(sw.toString()); endpointUri = (String) data.get(Field.ENDPOINT_URI.name()); defaultGraph = (String) data.get(Field.DEFAULT_GRAPH.name()); queryString = (String) data.get(Field.QUERY_STRING.name()); prefixes = (List<List<String>>) data.get(Field.PREFIXES.name()); varResult = (String) data.get(Field.VAR_RESULT.name()); } catch (Throwable e) { e.printStackTrace(); } }
private static void addPermissions(XStream xstream, String permissions) { for (String pterm : permissions.split(",")) { boolean aod; pterm = pterm.trim(); if (pterm.startsWith("-")) { aod = false; pterm = pterm.substring(1); } else { aod = true; if (pterm.startsWith("+")) { pterm = pterm.substring(1); } } TypePermission typePermission = null; if ("*".equals(pterm)) { // accept or deny any typePermission = AnyTypePermission.ANY; } else if (pterm.indexOf('*') < 0) { // exact type typePermission = new ExplicitTypePermission(new String[] {pterm}); } else if (pterm.length() > 0) { // wildcard type typePermission = new WildcardTypePermission(new String[] {pterm}); } if (typePermission != null) { if (aod) { xstream.addPermission(typePermission); } else { xstream.denyPermission(typePermission); } } } }
@Override public void transform(Object object) { Code code = (Code) object; if (code != null) { if (deepSerialize) { try { code = (Code) xStream.fromXML(xStream.toXML(code)); } catch (Exception ex) { deepSerialize = false; } } if (code != null) { CodeTransModel codeModel = new CodeTransModel(); codeModel.setCode(code.getCode()); codeModel.setCodeId(code.getCodeId()); codeModel.setCodeType(code.getCodeType()); codeModel.setLabel(code.getLabel()); getContext().transform(codeModel); } else { LOGGER.error("Serialization failed for user group transformer"); getContext().write(null); } } }
@Override public String toXML() { XStream xstream = getXstream(); xstream.alias("xml", this.getClass()); // 将生成的XML文件的根节点替换成XML,默认为类的全路径类名 xstream.alias("item", News.class); return xstream.toXML(this); }
@Test public void testXMLTest1Len() { Test1 test1 = new Test1(); Test2 test2 = new Test2(); Test3 test3 = new Test3(); test2.setTest1(test1); test1.setTest2(test2); test1.setTest3(test3); test3.setTest2(test2); try { String bigcontent = FileUtil.getFileContent( new File( "F:\\workspace\\bbossgroups-3.5\\bboss-core\\test\\org\\frameworkset\\soa\\testxstream.xml"), "UTF-8"); // 预热bboss和xstream test1.setXmlvalue(bigcontent); String xml = ObjectSerializable.toXML(test1); System.out.println("bboss:" + xml.getBytes().length); Test1 test1_ = (Test1) ObjectSerializable.toBean(xml, Test1.class); String xmlXstream = xStream.toXML(test1); Test1 p = (Test1) xStream.fromXML(xmlXstream); System.out.println("xmlXstream:" + xmlXstream.getBytes().length); // 测试用例结束 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
static { xs = new XStream(new DomDriver()); xs.alias("pipe", FilterPipeInfo.class); xs.alias("svr", String.class); // xs.alias("dfas", (new String[0]).getClass()); // xs.alias("name", null); }
public void doExecute(PageParameters parameters) { final String login = parameters.getString("login"); final String clearPassword = parameters.getString("password"); WicketSession session = WicketSession.get(); // GameService gameService = WicketApplication.get().getGameService(); UserService userService = WicketApplication.get().getUserService(); // GameTO gTO = null; UserTO uTO = null; if (session.signIn(login, clearPassword)) { System.out.println("session.signIn"); session.bind(); LoginResultTO loginResultTO = session.getLoginResultTO(); try { // gTO = // gameService.findGameById(userService.findUserById(loginResultTO.getUserId()).getGameId()); uTO = userService.findUserById(loginResultTO.getUserId()); } catch (InstanceNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } XStream xf = xStreamFactory.createXStream(); this.selement = xf.toXML(uTO); // this.element = TOToXMLConversor.toXML(uTO); // this.element = TOToXMLConversor.toXML(loginResultTO); // if( gTO!= null ) // this.element.addContent(TOToXMLConversor.toXML(gTO)); } else { System.out.println("not session.signIn"); } }
public void setInput(Input input) throws IOException { super.setInput(input); Object stuff; XStream xstr = XStreamFactory.forVersion(0.2); try { stuff = xstr.fromXML(input.getReader()); } catch (Exception e) { xstr = XStreamFactory.forVersion(0.1); try { System.out.println("trying to read JRS v0.1"); stuff = xstr.fromXML(input.copy().getReader()); System.out.println("JRS v0.1 success."); } catch (Exception e2) { throw new IOException("illegal JRS file"); } } if (stuff instanceof JrScene) { read = (JrScene) stuff; root = read.getSceneRoot(); } else { if (stuff instanceof SceneGraphComponent) root = (SceneGraphComponent) stuff; else { root = new SceneGraphComponent(); root.setName("jrs"); SceneGraphUtility.addChildNode(root, (SceneGraphNode) stuff); } } }
private void test(HierarchicalStreamDriver driver) { XStream xstream = new XStream(driver); xstream.registerConverter( new CollectionConverter(xstream.getMapper()) { public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { ExtendedHierarchicalStreamReader exReader = (ExtendedHierarchicalStreamReader) reader; if (exReader.peekNextChild() == null) { return new ArrayList(); } return super.unmarshal(reader, context); } }); SampleLists in = new SampleLists(); in.good.add("one"); in.good.add("two"); in.good.add("three"); in.bad.add(Boolean.TRUE); in.bad.add(Boolean.FALSE); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); xstream.toXML(in, buffer); Object out = xstream.fromXML(new ByteArrayInputStream(buffer.toByteArray())); Assert.assertEquals(in, out); }
public FTPConfig load() { InputStream in = null; try { File configFile = findConfigFile(); if (!configFile.exists()) { FTPConfig ftpConfig = new FTPConfig(); save(ftpConfig); return ftpConfig; } in = new FileInputStream(configFile); XStream xs = getPersister(); FTPConfig config = (FTPConfig) xs.fromXML(in); return config; } catch (IOException e) { throw new RuntimeException(e); } finally { if (in != null) { try { in.close(); } catch (IOException ignore) { // ignore } } } }
@Ignore public void testMarshalRecordCollectionById() throws UnsupportedEncodingException, JAXBException { final int totalResults = 2; XStream xstream = createXStream(CswConstants.GET_RECORD_BY_ID_RESPONSE); CswRecordCollection collection = createCswRecordCollection(null, totalResults); collection.setById(true); ArgumentCaptor<MarshallingContext> captor = ArgumentCaptor.forClass(MarshallingContext.class); String xml = xstream.toXML(collection); // Verify the context arguments were set correctly verify(mockProvider, times(totalResults)) .marshal(any(Object.class), any(HierarchicalStreamWriter.class), captor.capture()); MarshallingContext context = captor.getValue(); assertThat(context, not(nullValue())); assertThat( (String) context.get(CswConstants.OUTPUT_SCHEMA_PARAMETER), is(CswConstants.CSW_OUTPUT_SCHEMA)); assertThat((ElementSetType) context.get(CswConstants.ELEMENT_SET_TYPE), is(nullValue())); assertThat(context.get(CswConstants.ELEMENT_NAMES), is(nullValue())); JAXBElement<GetRecordByIdResponseType> jaxb = (JAXBElement<GetRecordByIdResponseType>) getJaxBContext() .createUnmarshaller() .unmarshal(new ByteArrayInputStream(xml.getBytes("UTF-8"))); GetRecordByIdResponseType response = jaxb.getValue(); // Assert the GetRecordsResponse elements and attributes assertThat(response, not(nullValue())); }
public CswRecordConverter() { xstream = new XStream(new Xpp3Driver()); xstream.setClassLoader(this.getClass().getClassLoader()); xstream.registerConverter(this); xstream.alias(CswConstants.CSW_RECORD_LOCAL_NAME, Metacard.class); xstream.alias(CswConstants.CSW_RECORD, Metacard.class); }
@Test public void testPersonListFormEmptyElement() { // XStream xstream = new XStream(new DomDriver()); XStream xstream = new XStream(); xstream.processAnnotations(TestPersonAnnotationList.class); xstream.processAnnotations(TestPersonAnnotation.class); xstream.processAnnotations(TestPerson.class); // xstream.registerConverter(new EmptyTestPersonAnnotationConverter()); TestPersonAnnotation hh = new TestPersonAnnotation(); hh.setUserName("hanhan"); hh.setAge(30); TestPerson parent = new TestPerson(); // parent.setAge(11); hh.setParent(null); TestPersonAnnotationList list = new TestPersonAnnotationList(); list.list.add(hh); String xmlStr = xstream.toXML(list); /*StringWriter sw = new StringWriter(); PrettyPrintWriter writer = new CompactWriter(sw); xstream.marshal(list, writer); String xmlStr = sw.toString();*/ System.out.println("testPersonListFormEmptyElement xml:\n " + xmlStr); xmlStr = XmlUtils.toXML( Lists.newArrayList(hh), "list", ArrayList.class, "person", TestPersonAnnotation.class); System.out.println("testPersonListFormEmptyElement xml22:\n " + xmlStr); }
@Override public File save(File file) throws IOException { XStream xstream = new XStream(new StaxDriver()); try { Writer out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream( "styles" + File.separatorChar + this.getName() + "_style.xml"), "UTF-8")); try { out.write(xstream.toXML(this)); } finally { out.close(); } } catch (IOException e) { e.printStackTrace(); } return new File("styles" + File.separatorChar + this.getName() + "_style.xml"); /* * // Write to disk with FileOutputStream FileOutputStream f_out = new FileOutputStream(file); // Write object with ObjectOutputStream ObjectOutputStream obj_out = new ObjectOutputStream (f_out); // Write object out to disk obj_out.writeObject ( this ); obj_out.close(); return file; */ }