List of usage examples for javax.xml.bind Marshaller setProperty
public void setProperty(String name, Object value) throws PropertyException;
From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java
public static File saveConfiguration(File directory, Object configuration) throws Exception { String configurationPackage = configuration.getClass().getPackage().getName(); JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); File configurationFile = new File(directory, "configuration.xml"); marshaller.marshal(configuration, configurationFile); configurationCache.invalidate(configurationFile); return configurationFile; }
From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java
/** * Persists a page to the file system./* ww w .j a v a 2s .c o m*/ * @param directory the directory where to save the page.xml file. * @param page the page to save. * @return the file where the page was saved. * @throws Exception in case the save fails. */ public static File savePage(File directory, Page page) throws Exception { File pageFile = getPageFile(directory); Marshaller marshaller = pagesJaxbContext.createMarshaller(); marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); marshaller.marshal(page, pageFile); pageCache.invalidate(pageFile); return pageFile; }
From source file:carisma.ui.eclipse.CarismaGUI.java
public final static void saveXml(final AnalysisResult analysisResult) { IContainer container = analysisResult.getAnalysis().getIFile().getParent(); IFile file = null;//w ww . j a va 2 s . com if (container instanceof IFolder) { IFolder folder = (IFolder) container; file = folder.getFile( "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml"); } else if (container instanceof IProject) { IProject project = (IProject) container; file = project.getFile( "xml-output-" + analysisResult.getName() + "-" + analysisResult.getTimestamp() + ".xml"); } else { Logger.log(LogLevel.ERROR, "Analyzed file is not part of a project."); return; } if (!(file.exists())) { try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { JAXBContext context = JAXBContext.newInstance(carisma.core.analysis.result.AnalysisResult.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); m.marshal(analysisResult, out); String store = new String(out.toByteArray(), StandardCharsets.UTF_8); InputStream is = new ByteArrayInputStream(store.getBytes(StandardCharsets.UTF_8)); // file.create(Utils.createInputStreamFromString(store), true, // null); file.create(is, true, null); // JSONObject fromXml = XML.toJSONObject(store); // String jsonPrint = fromXml.toString(1); // System.out.println(jsonPrint); // carisma.core.analysis.result.exp.dbexport.exportXml(jsonPrint); out.close(); } catch (Exception e) { System.out.println(e.getMessage()); } } }
From source file:com.ikon.util.impexp.RepositoryExporter.java
/** * Export mail from openkm repository to filesystem. *//*from ww w.j a va 2 s . c o m*/ public static ImpExpStats exportMail(String token, String mailPath, String destPath, String metadata, Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException, IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException { MailModule mm = ModuleManager.getMailModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); Mail mailChild = mm.getProperties(token, mailPath); Gson gson = new Gson(); ImpExpStats stats = new ImpExpStats(); MimeMessage msg = MailUtils.create(token, mailChild); FileOutputStream fos = new FileOutputStream(destPath); msg.writeTo(fos); IOUtils.closeQuietly(fos); FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath()); // Metadata if (metadata.equals("JSON")) { MailMetadata mmd = ma.getMetadata(mailChild); String json = gson.toJson(mmd); fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT); IOUtils.write(json, fos); IOUtils.closeQuietly(fos); } else if (metadata.equals("XML")) { fos = new FileOutputStream(destPath + ".xml"); MailMetadata mmd = ma.getMetadata(mailChild); JAXBContext jaxbContext; try { jaxbContext = JAXBContext.newInstance(MailMetadata.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); // output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(mmd, fos); } catch (JAXBException e) { log.error(e.getMessage(), e); FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage()); } } if (out != null) { out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null)); out.flush(); } // Stats stats.setSize(stats.getSize() + mailChild.getSize()); stats.setMails(stats.getMails() + 1); return stats; }
From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java
/** * Standard test for XSD examples./*from w w w. j ava 2 s . c o m*/ * * @param testName * the prototype of XSD file name / package name * @param extraXewOptions * to be passed to plugin * @param generateEpisode * generate episode file and check the list of classes included into it * @param classesToCheck * expected classes/files in target directory; these files content is checked if it is present in * resources directory; {@code ObjectFactory.java} is automatically included */ static void assertXsd(String testName, String[] extraXewOptions, boolean generateEpisode, String... classesToCheck) throws Exception { String resourceXsd = testName + ".xsd"; String packageName = testName.replace('-', '_'); // Force plugin to reinitialize the logger: System.clearProperty(XmlElementWrapperPlugin.COMMONS_LOGGING_LOG_LEVEL_PROPERTY_KEY); URL xsdUrl = XmlElementWrapperPluginTest.class.getResource(resourceXsd); File targetDir = new File(GENERATED_SOURCES_PREFIX); targetDir.mkdirs(); PrintStream loggingPrintStream = new PrintStream( new LoggingOutputStream(logger, LoggingOutputStream.LogLevel.INFO, "[XJC] ")); String[] opts = ArrayUtils.addAll(extraXewOptions, "-no-header", "-extension", "-Xxew", "-d", targetDir.getPath(), xsdUrl.getFile()); String episodeFile = new File(targetDir, "episode.xml").getPath(); // Episode plugin should be triggered after Xew, see https://github.com/dmak/jaxb-xew-plugin/issues/6 if (generateEpisode) { opts = ArrayUtils.addAll(opts, "-episode", episodeFile); } assertTrue("XJC compilation failed. Checked console for more info.", Driver.run(opts, loggingPrintStream, loggingPrintStream) == 0); if (generateEpisode) { // FIXME: Episode file actually contains only value objects Set<String> classReferences = getClassReferencesFromEpisodeFile(episodeFile); if (Arrays.asList(classesToCheck).contains("package-info")) { classReferences.add(packageName + ".package-info"); } assertEquals("Wrong number of classes in episode file", classesToCheck.length, classReferences.size()); for (String className : classesToCheck) { assertTrue(className + " class is missing in episode file;", classReferences.contains(packageName + "." + className)); } } targetDir = new File(targetDir, packageName); Collection<String> generatedJavaSources = new HashSet<String>(); // *.properties files are ignored: for (File targetFile : FileUtils.listFiles(targetDir, new String[] { "java" }, true)) { // This is effectively the path of targetFile relative to targetDir: generatedJavaSources .add(targetFile.getPath().substring(targetDir.getPath().length() + 1).replace('\\', '/')); } // This class is added and checked by default: classesToCheck = ArrayUtils.add(classesToCheck, "ObjectFactory"); assertEquals("Wrong number of generated classes " + generatedJavaSources + ";", classesToCheck.length, generatedJavaSources.size()); for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; assertTrue(className + " is missing in target directory", generatedJavaSources.contains(className)); } // Check the contents for those files which exist in resources: for (String className : classesToCheck) { className = className.replace('.', '/') + ".java"; File sourceFile = new File(PREGENERATED_SOURCES_PREFIX + packageName, className); if (sourceFile.exists()) { // To avoid CR/LF conflicts: assertEquals("For " + className, FileUtils.readFileToString(sourceFile).replace("\r", ""), FileUtils.readFileToString(new File(targetDir, className)).replace("\r", "")); } } JAXBContext jaxbContext = compileAndLoad(packageName, targetDir, generatedJavaSources); URL xmlTestFile = XmlElementWrapperPluginTest.class.getResource(testName + ".xml"); if (xmlTestFile != null) { StringWriter writer = new StringWriter(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setSchema(schemaFactory.newSchema(xsdUrl)); Marshaller marshaller = jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); Object bean = unmarshaller.unmarshal(xmlTestFile); marshaller.marshal(bean, writer); XMLUnit.setIgnoreComments(true); XMLUnit.setIgnoreWhitespace(true); Diff xmlDiff = new Diff(IOUtils.toString(xmlTestFile), writer.toString()); assertXMLEqual("Generated XML is wrong: " + writer.toString(), xmlDiff, true); } }
From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java
/** * Marshall this object to a JDOM Document * /*w ww . java 2s. c o m*/ * @param context * @param object * @param prefixMapper an implementation of namespacePrefixMapper * @return * @throws JAXBException */ protected static Document marshallToDocument(JAXBContext context, Object object, NamespacePrefixMapper prefixMapper) throws JAXBException { JDOMResult result = new JDOMResult(); Marshaller m = context.createMarshaller(); // set a namespace prefix mapper if (prefixMapper != null) m.setProperty("com.sun.xml.bind.namespacePrefixMapper", prefixMapper); m.marshal(object, result); return result.getDocument(); }
From source file:edu.kit.dama.rest.util.RestClientUtils.java
/** * Deserializes an entity from a stream provided by a ClientResponse. * <b>Attention:</b>May throw a DeserializationException if the * deserialization fails for some reason. * * @param <C> entity class// w w w . j a v a 2 s .com * @param pEntityClass An array of classes needed to deserialize the entity. * @param pResponse The response which provides the entity input stream. * * @return The object. */ public static <C> C createObjectFromStream(final Class[] pEntityClass, final ClientResponse pResponse) { C returnValue = null; if (pEntityClass != null) { LOGGER.debug("createObjectFromStream"); try { Unmarshaller unmarshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass) .createUnmarshaller(); returnValue = (C) unmarshaller.unmarshal(getInputStream(pResponse.getEntityInputStream())); if (LOGGER.isDebugEnabled()) { Marshaller marshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass) .createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); marshaller.marshal(returnValue, sw); LOGGER.debug("createObjectFromStream: " + sw.toString()); } } catch (JAXBException ex) { throw new DeserializationException("Failed to deserialize object from response " + pResponse, ex); } } else { LOGGER.debug("No response expected!"); } return returnValue; }
From source file:org.apache.lens.regression.util.Util.java
public static Marshaller getMarshaller(Class clazz) { JAXBContext jaxbContext = null; try {//w w w .j a v a 2s. c o m jaxbContext = new LensJAXBContext(clazz); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); return jaxbMarshaller; } catch (JAXBException e) { log.error("Error : ", e); } return null; }
From source file:Main.java
public static Marshaller createMarshaller(String pack, Schema schema) { JAXBContext jaxbContext = null; try {/*w w w . ja va 2s . c o m*/ jaxbContext = JAXBContext.newInstance(pack); Marshaller marsh = jaxbContext.createMarshaller(); if (schema != null) { marsh.setSchema(schema); // marsh.setEventHandler( new DefaultValidationEventHandler() { // @Override // public boolean handleEvent( ValidationEvent event ) { // return super.handleEvent( event ); // } // }); } marsh.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); return marsh; } catch (JAXBException e) { e.printStackTrace(); } return null; }
From source file:com.hpe.application.automation.tools.octane.executor.UFTTestDetectionService.java
/** * Serialize detectionResult to file in XML format * * @param fileToWriteTo/* w w w .ja v a 2 s . c o m*/ * @param taskListenerLog * @param detectionResult */ public static void publishDetectionResults(File fileToWriteTo, TaskListener taskListenerLog, UFTTestDetectionResult detectionResult) { try { JAXBContext jaxbContext = JAXBContext.newInstance(UFTTestDetectionResult.class); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(detectionResult, fileToWriteTo); } catch (JAXBException e) { if (taskListenerLog != null) { taskListenerLog.error("Failed to persist detection results: " + e.getMessage()); } logger.error("Failed to persist detection results: " + e.getMessage()); } }