List of usage examples for javax.xml.bind JAXBContext createUnmarshaller
public abstract Unmarshaller createUnmarshaller() throws JAXBException;
From source file:com.inamik.template.util.TemplateConfigUtil.java
/** * readTemplateEngineConfig w/InputStream - Read a template engine * xml configuration from an InputStream. * * @param stream The InputStream to read. * @return A template engine configuration suitable for instantiating * a TemplateEngine class.//from w w w . j a va 2s .c o m * @throws TemplateException This method uses JAXB to parse the xml * configuration. If JAXB throws an exception, this method catches * it and re-throws it as a wrapped TemplateException. * @throws NullPointerException if <code>stream == null</code> */ public static TemplateEngineConfig readTemplateEngineConfig(final InputStream stream) throws TemplateException { if (stream == null) { throw new NullPointerException("stream"); } TemplateEngineConfig engineConfig = new TemplateEngineConfig(); try { JAXBContext jc = JAXBContext.newInstance(JAXB_CONFIG_PACKAGE); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); TemplateConfig tc = (TemplateConfig) u.unmarshal(stream); if (tc.getApplicationRoot() != null) { engineConfig.setApplicationRoot(tc.getApplicationRoot()); } engineConfig.setTemplateRoot(tc.getTemplateRoot()); if (tc.getTagDelimeter() != null) { engineConfig.setTagDelimeter(tc.getTagDelimeter()); } engineConfig.setUseDefaultLib(tc.isUseDefaultLib()); engineConfig.setDebug(tc.isDebug()); Cache cache = tc.getCache(); if (cache != null) { TemplateCacheConfig cacheConfig = new TemplateCacheConfig(); // Name cacheConfig.setName(cache.getName()); // diskExpiryThreadIntervalSeconds if (cache.getDiskExpiryThreadIntervalSeconds() != null) { final int i = cache.getDiskExpiryThreadIntervalSeconds().intValue(); cacheConfig.setDiskExpiryThreadIntervalSeconds(i); } // diskPersistent cacheConfig.setDiskPersistent(cache.isDiskPersistent()); // diskRoot if (cache.getDiskRoot() != null) { cacheConfig.setDiskRoot(cache.getDiskRoot()); } // eternal (required) cacheConfig.setEternal(cache.isEternal()); // maxElementsInMemory if (cache.getMaxElementsInMemory() != null) { int i = cache.getMaxElementsInMemory().intValue(); cacheConfig.setMaxElementsInMemory(i); } // memoryEvictionPolicy if (cache.getMemoryStoreEvictionPolicy() != null) { EvictionPolicy ep = EvictionPolicy.valueOf(cache.getMemoryStoreEvictionPolicy()); cacheConfig.setMemoryStoreEvictionPolicy(ep); } // overflowToDisk (required) cacheConfig.setOverflowToDisk(cache.isOverflowToDisk()); // timeToIdleSeconds if (cache.getTimeToIdleSeconds() != null) { int i = cache.getTimeToIdleSeconds().intValue(); cacheConfig.setTimeToIdleSeconds(i); } // timeToLiveSeconds if (cache.getTimeToLiveSeconds() != null) { int i = cache.getTimeToLiveSeconds().intValue(); cacheConfig.setTimeToLiveSeconds(i); } engineConfig.setCacheConfig(cacheConfig); } List<TemplateConfig.UseLib> useLibs = tc.getUseLib(); // We can't resolve the use-libs now because the application-root // Has not been verified. So we store them to be resolved later // by the TemplateEngine for (TemplateConfig.UseLib lib : useLibs) { TemplateEngineConfig.UseLib useLib = new TemplateEngineConfig.UseLib(lib.getFile(), lib.getResource(), lib.getPrefix()); engineConfig.addUseLib(useLib); } } catch (JAXBException e) { throw new TemplateException(e); } return engineConfig; }
From source file:com.hello2morrow.sonarplugin.SonarJSensor.java
protected static ReportContext readSonarjReport(String fileName, String packaging) { ReportContext result = null;//from w ww. jav a 2 s . co m InputStream input = null; ClassLoader defaultClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(SonarJSensor.class.getClassLoader()); JAXBContext context = JAXBContext.newInstance("com.hello2morrow.sonarplugin.xsd"); Unmarshaller u = context.createUnmarshaller(); input = new FileInputStream(fileName); result = (ReportContext) u.unmarshal(input); } catch (JAXBException e) { LOG.error("JAXB Problem in " + fileName, e); } catch (FileNotFoundException e) { if (!packaging.equalsIgnoreCase("pom")) { LOG.warn("Cannot open SonarJ report: " + fileName + "."); LOG.warn( " Did you run the maven sonarj goal before with the POM option <prepareForSonar>true</prepareForSonar> " + "or with the commandline option -Dsonarj.prepareForSonar=true?"); LOG.warn(" Is the project part of the SonarJ architecture description?"); LOG.warn(" Did you set the 'aggregate' to true (must be false)?"); } } finally { Thread.currentThread().setContextClassLoader(defaultClassLoader); if (input != null) { try { input.close(); } catch (IOException e) { LOG.error("Cannot close " + fileName, e); } } } return result; }
From source file:org.apache.lens.regression.util.Util.java
@SuppressWarnings("unchecked") public static <T> Object extractObject(String queryString, Class<T> c) throws IllegalAccessException { JAXBContext jaxbContext = null; Unmarshaller unmarshaller = null; StringReader reader = new StringReader(queryString); try {//from w w w . j a va2 s. c o m jaxbContext = new LensJAXBContext(ObjectFactory.class) { }; unmarshaller = jaxbContext.createUnmarshaller(); return (T) ((JAXBElement<?>) unmarshaller.unmarshal(reader)).getValue(); } catch (JAXBException e) { System.out.println("Exception : " + e); return null; } }
From source file:com.netsteadfast.greenstep.util.SystemFtpClientUtils.java
private static void processXml(SystemFtpClientResultObj resultObj) throws Exception { SysFtpTranVO tran = resultObj.getSysFtpTran(); List<SystemFtpClientData> datas = new LinkedList<SystemFtpClientData>(); JAXBContext jaxbContext = null; Unmarshaller jaxbUnmarshaller = null; if (!StringUtils.isBlank(tran.getXmlClassName())) { Class<?> xmlBeanClazz = Class.forName(tran.getXmlClassName()); jaxbContext = JAXBContext.newInstance(xmlBeanClazz); jaxbUnmarshaller = jaxbContext.createUnmarshaller(); }/* w w w . ja v a 2 s .com*/ for (File file : resultObj.getFiles()) { SystemFtpClientData ftpData = new SystemFtpClientData(); logWarnFileSize(file); String content = FileUtils.readFileToString(file, Constants.BASE_ENCODING); // xml utf-8 ftpData.setContent(content); ftpData.setDatas(null); ftpData.setFile(file); if (jaxbUnmarshaller != null) { Object obj = jaxbUnmarshaller .unmarshal(new ByteArrayInputStream(content.getBytes(Constants.BASE_ENCODING))); // xml utf-8 ftpData.setXmlBean(obj); } datas.add(ftpData); } resultObj.setDatas(datas); }
From source file:gov.va.isaac.config.profiles.UserProfile.java
protected static UserProfile read(File path) throws IOException { try {// ww w . j a va2 s. c om JAXBContext jaxbContext = JAXBContext.newInstance(UserProfile.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (UserProfile) jaxbUnmarshaller.unmarshal(path); } catch (Exception e) { logger.error("Problem reading user profile from " + path.getAbsolutePath(), e); throw new IOException("Problem reading user profile", e); } }
From source file:com.cloudera.api.model.ApiModelTest.java
static <T> T xmlToObject(String text, Class<T> type) throws JAXBException, UnsupportedEncodingException, IllegalAccessException, InstantiationException { JAXBContext jc = JAXBContext.newInstance(type); Unmarshaller um = jc.createUnmarshaller(); ByteArrayInputStream bais = new ByteArrayInputStream(text.getBytes(TEXT_ENCODING)); Object res = um.unmarshal(bais); return type.cast(res); }
From source file:com.seer.datacruncher.utils.generic.CommonUtils.java
public static Object getJaxbObjectFromXML(long schemaId, String xmlString) throws JAXBException { JAXBContext jc = JAXBContext.newInstance(FileInfo.GENERATED_PACKAGE + schemaId); ByteArrayInputStream input = new ByteArrayInputStream(xmlString.getBytes()); Unmarshaller u = jc.createUnmarshaller(); return u.unmarshal(input); }
From source file:com.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java
/** * Standard test for XSD examples./*from ww w . j av a 2 s. co 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:com.jsmartframework.web.manager.WebContext.java
/** * Get request content from XML and convert it to class mapping the content. * * @param clazz - Class mapping the request content. * @param <T> - type of class to convert XML into class. * * @return content from XML to object/* w ww.jav a 2s .c o m*/ * @throws IOException */ public static <T> T getContentFromXml(Class<T> clazz) throws IOException, JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); return getContentFromXml(jaxbContext.createUnmarshaller()); }
From source file:com.ikon.util.impexp.RepositoryImporter.java
/** * Import documents from filesystem into document repository (recursive). *//*from w ww. j a v a 2 s . c o m*/ private static ImpExpStats importDocumentsHelper(String token, File fs, String fldPath, String metadata, boolean history, boolean uuid, Writer out, InfoDecorator deco) throws FileNotFoundException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException, ExtensionException, AutomationException { log.debug("importDocumentsHelper({}, {}, {}, {}, {}, {}, {}, {})", new Object[] { token, fs, fldPath, metadata, history, uuid, out, deco }); File[] files = fs.listFiles(new RepositoryImporter.NoVersionFilenameFilter()); ImpExpStats stats = new ImpExpStats(); FolderModule fm = ModuleManager.getFolderModule(); MetadataAdapter ma = MetadataAdapter.getInstance(token); ma.setRestoreUuid(uuid); Gson gson = new Gson(); for (int i = 0; i < files.length; i++) { String fileName = files[i].getName(); if (!fileName.endsWith(Config.EXPORT_METADATA_EXT) && !fileName.endsWith(".xml")) { if (files[i].isDirectory()) { Folder fld = new Folder(); boolean api = false; int importedFolder = 0; log.info("Directory: {}", files[i]); try { if (metadata.equals("JSON")) { // Read serialized folder metadata File jsFile = new File(files[i].getPath() + Config.EXPORT_METADATA_EXT); log.info("Folder Metadata: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); FolderMetadata fmd = gson.fromJson(fr, FolderMetadata.class); fr.close(); // Apply metadata fld.setPath(fldPath + "/" + fileName); fmd.setPath(fld.getPath()); ma.importWithMetadata(fmd); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else if (metadata.equals("XML")) { // Read serialized folder metadata File jsFile = new File(files[i].getPath() + ".xml"); log.info("Folder Metadata: {}", jsFile.getPath()); if (jsFile.exists() && jsFile.canRead()) { FileReader fr = new FileReader(jsFile); JAXBContext jaxbContext = JAXBContext.newInstance(FolderMetadata.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); FolderMetadata fmd = (FolderMetadata) jaxbUnmarshaller.unmarshal(fr); fr.close(); // Apply metadata fld.setPath(fldPath + "/" + fileName); fmd.setPath(fld.getPath()); ma.importWithMetadata(fmd); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } else { log.warn("Unable to read metadata file: {}", jsFile.getPath()); api = true; } } else { api = true; } if (api) { fld.setPath(fldPath + "/" + fileName); fm.create(token, fld); FileLogger.info(BASE_NAME, "Created folder ''{0}''", fld.getPath()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), null)); out.flush(); } } importedFolder = 1; } catch (ItemExistsException e) { log.warn("ItemExistsException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "ItemExists")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "ItemExistsException ''{0}''", fld.getPath()); } catch (JsonParseException e) { log.warn("JsonParseException: {}", e.getMessage()); if (out != null) { out.write(deco.print(files[i].getPath(), files[i].length(), "Json")); out.flush(); } stats.setOk(false); FileLogger.error(BASE_NAME, "JsonParseException ''{0}''", fld.getPath()); } catch (JAXBException e) { // TODO Auto-generated catch block e.printStackTrace(); } ImpExpStats tmp = importDocumentsHelper(token, files[i], fld.getPath(), metadata, history, uuid, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); stats.setFolders(stats.getFolders() + tmp.getFolders() + importedFolder); } else { log.info("File: {}", files[i]); if (fileName.endsWith(".eml")) { log.info("Mail: {}", files[i]); ImpExpStats tmp = importMail(token, fs, fldPath, fileName, files[i], metadata, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setMails(stats.getMails() + tmp.getMails()); } else { log.info("Document: {}", files[i]); ImpExpStats tmp = importDocument(token, fs, fldPath, fileName, files[i], metadata, history, out, deco); // Stats stats.setOk(stats.isOk() && tmp.isOk()); stats.setSize(stats.getSize() + tmp.getSize()); stats.setDocuments(stats.getDocuments() + tmp.getDocuments()); } } } } log.debug("importDocumentsHelper: {}", stats); return stats; }