List of usage examples for javax.xml.bind Unmarshaller unmarshal
public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;
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:gov.va.isaac.config.profiles.UserProfile.java
protected static UserProfile read(File path) throws IOException { try {/*from w w w. ja va 2s. com*/ 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.hello2morrow.sonarplugin.SonargraphSensor.java
protected static ReportContext readSonargraphReport(String fileName, String packaging) { ReportContext result = null;//from w w w. jav a2s . c o m InputStream input = null; ClassLoader defaultClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(SonargraphSensor.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 Sonargraph report: " + fileName + "."); LOG.warn( " Did you run the maven sonargraph goal before with the POM option <prepareForSonar>true</prepareForSonar> " + "or with the commandline option -Dsonargraph.prepareForSonar=true?"); LOG.warn(" Is the project part of the Sonargraph 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.psikeds.knowledgebase.xml.impl.XMLParser.java
/** * Helper for parsing big XML files using JAXB in combination with StAX.<br> * All classes in the specified package can be parsed.<br> * <b>Note:</b> The XML reader will not be closed. This must be invoked by * the caller afterwards!<br>//from ww w .ja v a 2 s . co m * * @param xml * Reader for XML-Data * @param packageName * Name of the package containing the JAXB-Classes, * e.g. org.psikeds.knowledgebase.jaxb * @param handler * Callback handler used to process every single found * XML-Element (@see * org.psikeds.knowledgebase.xml.KBParserCallback#handleElement * (java.lang.Object)) * @param filter * EventFilter used for StAX-Parsing * @param numSkipped * Number of Elements to be skipped, * e.g. numSkipped = 1 for skipping the XML-Root-Element. * @return Total number of unmarshalled XML-Elements * @throws XMLStreamException * @throws JAXBException */ public static long parseXmlElements(final Reader xml, final String packageName, final KBParserCallback handler, final EventFilter filter, final int numSkipped) throws XMLStreamException, JAXBException { // init stream reader final XMLInputFactory staxFactory = XMLInputFactory.newInstance(); final XMLEventReader staxReader = staxFactory.createXMLEventReader(xml); final XMLEventReader filteredReader = filter == null ? staxReader : staxFactory.createFilteredReader(staxReader, filter); skipXmlElements(filteredReader, numSkipped); // JAXB with specific package final JAXBContext jaxbCtx = JAXBContext.newInstance(packageName); final Unmarshaller unmarshaller = jaxbCtx.createUnmarshaller(); // parsing und unmarshalling long counter = 0; while (filteredReader.peek() != null) { final Object element = unmarshaller.unmarshal(staxReader); handleElement(handler, element); counter++; } return counter; }
From source file:com.evolveum.midpoint.model.client.ModelClientUtil.java
public static <O> O unmarshallFile(File file) throws JAXBException, FileNotFoundException { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); InputStream is = null;/*from w w w. ja v a 2 s.com*/ JAXBElement<O> element = null; try { is = new FileInputStream(file); element = (JAXBElement<O>) unmarshaller.unmarshal(is); } finally { if (is != null) { IOUtils.closeQuietly(is); } } if (element == null) { return null; } return element.getValue(); }
From source file:com.hello2morrow.sonarplugin.SonarJSensor.java
protected static ReportContext readSonarjReport(String fileName, String packaging) { ReportContext result = null;// w ww.j a v a2 s.com 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 {//w w w . j ava 2s. 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.sun.tools.xjc.addon.xew.XmlElementWrapperPluginTest.java
/** * Standard test for XSD examples.// ww w .jav a2 s . com * * @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.tera.common.vcontext.service.ContextConfigurationParser.java
/** * @param bundle com.tera.common.vcontext bundle * @param directory top directory with filesystem data *///w ww .j av a 2s .c o m public static final void parseConfigurationDirectory(Bundle bundle, String directory) { Unmarshaller un = JaxbUtil.create(VContextTemplate.class, bundle.getResource("vcontext.xsd")); File file = new File(directory); if (file.isDirectory()) { File[] contextDirs = file.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); log.info("Found {} filesystem directories", contextDirs.length); for (File dir : contextDirs) { Collection<File> contextFiles = FileUtils.listFiles(dir, new NameFileFilter("vcontext.xml"), null); for (File contextFile : contextFiles) { try { VContextTemplate context = (VContextTemplate) un .unmarshal(contextFile.toURI().toURL().openStream()); parseRealConfiguration(dir.getAbsolutePath(), context); } catch (Exception e) { log.error("Exception when parsing context resource {}", contextFile.getName(), e); } } } } else { log.warn("Specified context directory doesn't exists {}", directory); } }
From source file:com.evolveum.midpoint.pwdfilter.opendj.PasswordPusher.java
@SuppressWarnings("unchecked") private static <T> T unmarshallResouce(String path) throws JAXBException, FileNotFoundException { JAXBContext jc = ModelClientUtil.instantiateJaxbContext(); Unmarshaller unmarshaller = jc.createUnmarshaller(); InputStream is = null;// w ww .j av a2 s . c o m JAXBElement<T> element = null; try { is = PasswordPusher.class.getClassLoader().getResourceAsStream(path); if (is == null) { throw new FileNotFoundException("System resource " + path + " was not found"); } element = (JAXBElement<T>) unmarshaller.unmarshal(is); } finally { if (is != null) { IOUtils.closeQuietly(is); } } if (element == null) { return null; } return element.getValue(); }