List of usage examples for javax.xml.bind JAXBContext createUnmarshaller
public abstract Unmarshaller createUnmarshaller() throws JAXBException;
From source file:com.ibm.watson.developer_cloud.professor_languo.model.stack_exchange.CorpusBuilder.java
/** * Unmarshalls (deserializes) a single XML file using JAXB * * @param xmlFile - The XML file to be unmarshalled * @param clazz - The class of object that <code>xmlFile</code> should be unmarshalled to * @return An object of class <code>clazz</code>, populated from <code>xmlFile</code> * @throws JAXBException/* ww w . j a v a 2 s . c om*/ */ @SuppressWarnings("unchecked") public static <T> T unmarshallFile(File xmlFile, Class<T> clazz) throws JAXBException { JAXBContext jaxbContext = JAXBContext.newInstance(clazz); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); return (T) jaxbUnmarshaller.unmarshal(xmlFile); }
From source file:com.bitplan.w3ccheck.W3CValidator.java
/** * create a W3CValidator result for the given url with the given html * /* w w w . ja v a 2 s . c o m*/ * @param url - the url of the validator e.g. "http://validator.w3.org/check" * @param html - the html code to be checked * @return - a W3CValidator response according to the SOAP response format or null if the * http response status of the Validation service is other than 200 * explained at response http://validator.w3.org/docs/api.html#requestformat * @throws JAXBException if there is something wrong with the response message so that it * can not be unmarshalled */ public static W3CValidator check(String url, String html) throws JAXBException { // initialize the return value W3CValidator result = null; // create a WebResource to access the given url WebResource resource = Client.create().resource(url); // prepare form data for posting FormDataMultiPart form = new FormDataMultiPart(); // set the output format to soap12 // triggers the various outputs formats of the validator. If unset, the usual Web format will be sent. // If set to soap12, // the SOAP1.2 interface will be triggered. See the SOAP 1.2 response format description at // http://validator.w3.org/docs/api.html#requestformat form.field("output", "soap12"); // make sure Unicode 0x0 chars are removed from html (if any) // see https://github.com/WolfgangFahl/w3cValidator/issues/1 Pattern pattern = Pattern.compile("[\\000]*"); Matcher matcher = pattern.matcher(html); if (matcher.find()) { html = matcher.replaceAll(""); } // The document to validate, POSTed as multipart/form-data FormDataBodyPart fdp = new FormDataBodyPart("uploaded_file", IOUtils.toInputStream(html), // new FileInputStream(tmpHtml), MediaType.APPLICATION_OCTET_STREAM_TYPE); // attach the inputstream as upload info to the form form.bodyPart(fdp); // now post the form via the Internet/Intranet ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); // in debug mode show the response status if (debug) LOGGER.log(Level.INFO, "response status for '" + url + "'=" + response.getStatus()); // if the http Status is ok if (response.getStatus() == 200) { // get the XML encoded SOAP 1.2 response format String responseXml = response.getEntity(String.class); // in debug mode show the full xml if (debug) LOGGER.log(Level.INFO, responseXml); // unmarshal the xml message to the format to a W3CValidator Java object JAXBContext context = JAXBContext.newInstance(W3CValidator.class); Unmarshaller u = context.createUnmarshaller(); StringReader xmlReader = new StringReader(responseXml); // this step will convert from xml text to Java Object result = (W3CValidator) u.unmarshal(xmlReader); } // return the result which might be null if the response status was other than 200 return result; }
From source file:com.bluexml.side.build.tools.reader.MavenProjectReader.java
/** * @return/*from www .j a va2 s .c o m*/ * @throws JAXBException * @throws PropertyException */ private static Unmarshaller getUnmarshaller(String packageName) throws JAXBException, PropertyException { JAXBContext jaxbContext = JAXBContext.newInstance(packageName); Marshaller alfrescoMarshaller = jaxbContext.createMarshaller(); alfrescoMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); alfrescoMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); Unmarshaller alfrescoUnmarshaller = jaxbContext.createUnmarshaller(); return alfrescoUnmarshaller; }
From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.java
private static Dependency parseOldVersionsWithoutSchema(File f) throws JAXBException { final JAXBContext context = JAXBContext .newInstance(com.sap.prd.mobile.ios.mios.versioninfo.v_1_2_0.Versions.class); final Unmarshaller unmarshaller = context.createUnmarshaller(); final com.sap.prd.mobile.ios.mios.versioninfo.v_1_2_0.Versions versions = (com.sap.prd.mobile.ios.mios.versioninfo.v_1_2_0.Versions) unmarshaller .unmarshal(f);/* w w w . j av a 2 s. com*/ final Coordinates coordinates = new Coordinates(); coordinates.setGroupId(versions.getCoordinates().getGroupId()); coordinates.setArtifactId(versions.getCoordinates().getArtifactId()); coordinates.setVersion(versions.getCoordinates().getVersion()); final SCM scm = new SCM(); scm.setConnection(versions.getScm().getConnection()); scm.setRevision(versions.getScm().getRevision()); final Dependency dependency = new Dependency(); dependency.setCoordinates(coordinates); dependency.setScm(scm); if (versions.getDependencies() != null) { for (com.sap.prd.mobile.ios.mios.versioninfo.v_1_2_0.Dependency d : versions.getDependencies()) { marshalDependenciesVersionsWithoutSchema(dependency, d); } } return dependency; }
From source file:com.sap.prd.mobile.ios.mios.VersionInfoManager.java
private static Dependency parseOldDependency(File f) throws JAXBException { final JAXBContext context = JAXBContext .newInstance(com.sap.prd.mobile.ios.mios.versioninfo.v_0_0_0.Versions.class); final Unmarshaller unmarshaller = context.createUnmarshaller(); final com.sap.prd.mobile.ios.mios.versioninfo.v_0_0_0.Versions versions = (com.sap.prd.mobile.ios.mios.versioninfo.v_0_0_0.Versions) unmarshaller .unmarshal(f);// w ww .j ava2 s . c o m final Coordinates coordinates = new Coordinates(); coordinates.setGroupId(versions.getCoordinates().getGroupId()); coordinates.setArtifactId(versions.getCoordinates().getArtifactId()); coordinates.setVersion(versions.getCoordinates().getVersion()); final SCM scm = new SCM(); scm.setConnection("scm:perforce:" + versions.getScm().getRepository() + ":" + getDepotPath(versions.getScm().getPath())); scm.setRevision(versions.getScm().getSnapshotId()); final Dependency dependency = new Dependency(); dependency.setCoordinates(coordinates); dependency.setScm(scm); if (versions.getDependencies() != null) { for (com.sap.prd.mobile.ios.mios.versioninfo.v_0_0_0.Dependency d : versions.getDependencies()) { marshalOldDependencies(dependency, d); } } return dependency; }
From source file:main.java.refinement_class.Useful.java
public static Object unmashal2(String schema_file, String xml_file, Class c) { Object obj = null;/*from www . j a va2 s . co m*/ try { // create a JAXBContext capable of handling classes generated into // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class ); JAXBContext jc = JAXBContext.newInstance(c); // create an Unmarshaller Unmarshaller u = jc.createUnmarshaller(); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); try { javax.xml.validation.Schema schema = sf.newSchema(new File(schema_file)); u.setSchema((javax.xml.validation.Schema) schema); u.setEventHandler(new ValidationEventHandler() { // allow unmarshalling to continue even if there are errors public boolean handleEvent(ValidationEvent ve) { // ignore warnings if (ve.getSeverity() != ValidationEvent.WARNING) { ValidationEventLocator vel = ve.getLocator(); System.out.println("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:" + ve.getMessage()); } return true; } }); } catch (org.xml.sax.SAXException se) { System.out.println("Unable to validate due to following error."); se.printStackTrace(); LOG.error(se.toString()); } obj = u.unmarshal(new File(xml_file)); // even though document was determined to be invalid unmarshalling, // marshal out result. // System.out.println(""); // System.out.println("Still able to marshal invalid document"); // javax.xml.bind.Marshaller m = jc.createMarshaller(); // m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE ); // m.marshal(poe, System.out); } catch (UnmarshalException ue) { // The JAXB specification does not mandate how the JAXB provider // must behave when attempting to unmarshal invalid XML data. // those cases, the JAXB provider is allowed to terminate the // call to unmarshal with an UnmarshalException. System.out.println("Caught UnmarshalException"); } catch (JAXBException je) { je.printStackTrace(); LOG.error(je.toString()); } return obj; }
From source file:com.googlesource.gerrit.plugins.supermanifest.JiriManifestParser.java
private static JiriManifest parseManifest(Repository repo, String ref, String file) throws JAXBException, IOException, XMLStreamException { byte[] b = Utils.readBlob(repo, ref + ":" + file); JAXBContext jc = JAXBContext.newInstance(JiriManifest.class); XMLInputFactory inf = XMLInputFactory.newFactory(); inf.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); inf.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader sr = inf.createXMLStreamReader(new StreamSource(new ByteArrayInputStream(b))); return (JiriManifest) jc.createUnmarshaller().unmarshal(sr); }
From source file:com.indivica.olis.Driver.java
public static void readResponseFromXML(HttpServletRequest request, String olisResponse) { olisResponse = olisResponse.replaceAll("<Content", "<Content xmlns=\"\" "); olisResponse = olisResponse.replaceAll("<Errors", "<Errors xmlns=\"\" "); try {//from w w w. jav a 2s.c o m DocumentBuilderFactory.newInstance().newDocumentBuilder(); SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); Source schemaFile = new StreamSource( new File(OscarProperties.getInstance().getProperty("olis_response_schema"))); factory.newSchema(schemaFile); JAXBContext jc = JAXBContext.newInstance("ca.ssha._2005.hial"); Unmarshaller u = jc.createUnmarshaller(); @SuppressWarnings("unchecked") Response root = ((JAXBElement<Response>) u.unmarshal(new InputSource(new StringReader(olisResponse)))) .getValue(); if (root.getErrors() != null) { List<String> errorStringList = new LinkedList<String>(); // Read all the errors ArrayOfError errors = root.getErrors(); List<ca.ssha._2005.hial.Error> errorList = errors.getError(); for (ca.ssha._2005.hial.Error error : errorList) { String errorString = ""; errorString += "ERROR " + error.getNumber() + " (" + error.getSeverity() + ") : " + error.getMessage(); MiscUtils.getLogger().debug(errorString); ArrayOfString details = error.getDetails(); if (details != null) { List<String> detailList = details.getString(); for (String detail : detailList) { errorString += "\n" + detail; } } errorStringList.add(errorString); } if (request != null) request.setAttribute("errors", errorStringList); } else if (root.getContent() != null) { if (request != null) request.setAttribute("olisResponseContent", root.getContent()); } } catch (Exception e) { MiscUtils.getLogger().error("Couldn't read XML from OLIS response.", e); LoggedInInfo loggedInInfo = LoggedInInfo.getLoggedInInfoFromSession(request); notifyOlisError(loggedInInfo.getLoggedInProvider(), "Couldn't read XML from OLIS response." + "\n" + e); } }
From source file:Main.java
/** * Helper method to unmarshall a xml doc * @see http://docs.oracle.com/javase/tutorial/jaxb/intro/basic.html * http://jaxb.java.net/nonav/2.2.6/docs/ch03.html#unmarshalling * this uses <T> JAXBElement<T> unmarshal(Source source, Class<T> declaredType) throws JAXBException//from w ww . j a va 2s. co m * */ /* public static <T> T unmarshall(Class<T> docClass, InputStream inputStream) throws JAXBException{ String packageName = docClass.getPackage().getName(); JAXBContext jc = JAXBContext.newInstance( packageName ); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> root = u.unmarshal(new StreamSource(inputStream),docClass); return root.getValue(); }*/ public static <T> T unmarshall(Class<T> docClass, InputStream inputStream) throws JAXBException, ParserConfigurationException, SAXException { String packageName = docClass.getPackage().getName(); JAXBContext jc = JAXBContext.newInstance(packageName); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/validation/schema", false); spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); XMLReader xmlReader = spf.newSAXParser().getXMLReader(); InputSource inputSource = new InputSource(inputStream); SAXSource source = new SAXSource(xmlReader, inputSource); Unmarshaller u = jc.createUnmarshaller(); JAXBElement<T> root = u.unmarshal(source, docClass); return root.getValue(); }
From source file:com.manydesigns.portofino.dispatcher.DispatcherLogic.java
public static <T> T loadConfiguration(InputStream inputStream, Class<? extends T> configurationClass) throws Exception { if (configurationClass == null) { return null; }/*from w w w . ja v a 2s.com*/ Object configuration; String configurationPackage = configurationClass.getPackage().getName(); JAXBContext jaxbContext = JAXBContext.newInstance(configurationPackage); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); configuration = unmarshaller.unmarshal(inputStream); if (!configurationClass.isInstance(configuration)) { logger.error("Invalid configuration: expected " + configurationClass + ", got " + configuration); return null; } Injections.inject(configuration, ElementsThreadLocals.getServletContext(), ElementsThreadLocals.getHttpServletRequest()); if (configuration instanceof PageActionConfiguration) { ((PageActionConfiguration) configuration).init(); } return (T) configuration; }