List of usage examples for javax.xml.bind Unmarshaller setEventHandler
public void setEventHandler(ValidationEventHandler handler) throws JAXBException;
From source file:it.cnr.icar.eric.common.cms.AbstractService.java
protected Unmarshaller getUnmarshaller() throws JAXBException { Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); //unmarshaller.setValidating(true); unmarshaller.setEventHandler(new ValidationEventHandler() { public boolean handleEvent(ValidationEvent event) { boolean keepOn = false; return keepOn; }/*from w w w .java2s . com*/ }); return unmarshaller; }
From source file:org.ff4j.console.conf.XmlConfigurationParser.java
/** * Mthode permettant de crer le Unmarshaller pour le parsing du XML. * @param modelPackage/*from ww w. j a va 2 s . c om*/ * nom du package qui contient les beans utilises pour le parsing du fichier. * @param schemafile * le fichier XSD pour la validation du XML. * @return Unmarshaller * @throws JAXBException * @throws SAXException */ public Unmarshaller getUnmarshaller(String modelPackage, File schemafile) throws JAXBException, SAXException { JAXBContext jc = JAXBContext.newInstance(modelPackage); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(schemafile); Unmarshaller u = jc.createUnmarshaller(); u.setSchema(schema); u.setEventHandler(new XmlConfigurationErrorHandler()); return u; }
From source file:org.ff4j.console.conf.XmlConfigurationParser.java
/** * Mthode permettant de crer le Unmarshaller pour le parsing du XML. * @param modelPackage/*from w ww . j a va 2s . co m*/ * nom du package qui contient les beans utilises pour le parsing du fichier. * @param schemafile * le fichier XSD pour la validation du XML. * @return Unmarshaller * @throws JAXBException * @throws SAXException */ public Unmarshaller getUnmarshaller(String modelPackage, InputStream schemaStream) throws JAXBException, SAXException { JAXBContext jc = JAXBContext.newInstance(modelPackage); SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI); Schema schema = sf.newSchema(new StreamSource(schemaStream)); Unmarshaller u = jc.createUnmarshaller(); u.setSchema(schema); u.setEventHandler(new XmlConfigurationErrorHandler()); return u; }
From source file:org.cleverbus.core.common.asynch.TraceHeaderProcessor.java
private void setFromTraceHeader(Exchange exchange, Source traceHeaderElmSource, boolean headerInBody) throws JAXBException { // unmarshal// w ww . j a v a2 s. c o m Unmarshaller unmarshaller = jaxb2.createUnmarshaller(); if (!headerInBody) { // if there is trace header in the body then error events are thrown because there are other elements // in the body unmarshaller.setEventHandler(validationEventHandler); } TraceHeader traceHeader = unmarshaller.unmarshal(traceHeaderElmSource, TraceHeader.class).getValue(); if (traceHeader == null) { if (isMandatoryHeader()) { throw new ValidationIntegrationException(InternalErrorEnum.E105, "there is no trace header"); } } else { // validate header content TraceIdentifier traceId = traceHeader.getTraceIdentifier(); if (traceId == null) { if (isMandatoryHeader()) { throw new ValidationIntegrationException(InternalErrorEnum.E105, "there is no trace identifier"); } } else { if (traceId.getApplicationID() == null) { throw new ValidationIntegrationException(InternalErrorEnum.E105, "there is no application ID"); } else if (traceId.getCorrelationID() == null) { throw new ValidationIntegrationException(InternalErrorEnum.E105, "there is no correlation ID"); } else if (traceId.getTimestamp() == null) { throw new ValidationIntegrationException(InternalErrorEnum.E105, "there is no timestamp ID"); } validateTraceIdentifier(traceId); exchange.getIn().setHeader(TRACE_HEADER, traceHeader); Log.debug("traceHeader saved to exchange: " + ToStringBuilder.reflectionToString(traceId)); } } }
From source file:main.java.refinement_class.Useful.java
public static Object unmashal(String schema_file, String xml_file, Class c) { Object obj = null;/* w w w . j a v a 2s . c o 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 { // LOG.info("\n\n XX -->> Schema file: " + schema_file); // LOG.info("\n\n XX -->> xml_file file: " + xml_file); //++ javax.xml.validation.Schema schema; if (schema_file.contains("/tmp/")) { schema = sf.newSchema(new File(schema_file)); } else { URL urlSchema = getUrl(H2mserviceImpl.class, schema_file); // LOG.info("\n\n XX -->> urlSchema: " + urlSchema.getPath()); schema = sf.newSchema(urlSchema); } //-- //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("===>[1]ERROR Unmashaling \n\n" + se.toString()); LOG.error(Useful.getStackTrace(se)); } catch (Exception e) { LOG.error("===>[2]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (xml_file.contains("/tmp/")) { obj = u.unmarshal(new File(xml_file)); } else { URL url_xml_file = getUrl(H2mserviceImpl.class, xml_file); LOG.info("\n\n XX -->> url_xml_file: " + url_xml_file.getPath()); obj = u.unmarshal(url_xml_file); } //-- //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"); LOG.error("===>[3]ERROR Unmashaling \n\n" + ue.toString()); } catch (JAXBException je) { je.printStackTrace(); LOG.error("===>[4]ERROR Unmashaling \n\n" + je.toString()); LOG.error(Useful.getStackTrace(je)); } catch (Exception e) { LOG.error("===>[5]ERROR Unmashaling \n\n" + e.toString()); LOG.error(Useful.getStackTrace(e)); } if (obj == null) { LOG.error("===>[6]ERROR Unmashaling Object NULL"); } return obj; }
From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java
private <T> T unmarshal(HttpResponse response, Class<T> type) throws JAXBException, IOException { JAXBContext jaxbC = JAXBContext.newInstance(type); Unmarshaller um = jaxbC.createUnmarshaller(); um.setEventHandler(new DefaultValidationEventHandler()); return um.unmarshal(new StreamSource(response.getEntity().getContent()), type).getValue(); }
From source file:com.bitplan.jaxb.JaxbFactory.java
/** * get a fitting Unmarshaller/*from w w w .ja va 2 s.com*/ * * @return - the Unmarshaller for the classOfT set * @throws JAXBException */ public Unmarshaller getUnmarshaller() throws JAXBException { JAXBContext lcontext = getJAXBContext(); Unmarshaller u = lcontext.createUnmarshaller(); if (unmarshalListener != null) { u.setListener(unmarshalListener); } if (novalidate) { u.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { return true; } }); } return u; }
From source file:at.gv.egiz.slbinding.SLUnmarshaller.java
/** * @param source a StreamSource wrapping a Reader (!) for the marshalled Object * @return the unmarshalled Object/*w ww . java2 s .co m*/ * @throws XMLStreamException * @throws JAXBException */ public Object unmarshal(StreamSource source) throws XMLStreamException, JAXBException { Reader inputReader = source.getReader(); /* Validate XML against XXE, XEE, and SSRF * * This pre-validation step is required because com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library does not * support all XML parser features to prevent these types of attacks */ if (inputReader instanceof InputStreamReader) { try { //create copy of input stream InputStreamReader isReader = (InputStreamReader) inputReader; String encoding = isReader.getEncoding(); byte[] backup = IOUtils.toByteArray(isReader, encoding); //validate input stream DOMUtils.validateXMLAgainstXXEAndSSRFAttacks(new ByteArrayInputStream(backup)); //create new inputStreamReader for reak processing inputReader = new InputStreamReader(new ByteArrayInputStream(backup), encoding); } catch (XMLStreamException e) { log.error("XML data validation FAILED with msg: " + e.getMessage(), e); throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e); } catch (IOException e) { log.error("XML data validation FAILED with msg: " + e.getMessage(), e); throw new XMLStreamException("XML data validation FAILED with msg: " + e.getMessage(), e); } } else { log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); log.error( "Reader is not of type InputStreamReader -> can not make a copy of the InputStream --> extended XML validation is not possible!!! "); log.error("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); } /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * parse XML with original functionality * * This code implements the the original mocca XML processing by using * com.sun.xml.stream.sjsxp-1.0.2 XML stream parser library. Currently, this library is required to get full * security-layer specific XML processing. However, this lib does not fully support XXE, XEE and SSRF * prevention mechanisms (e.g.: XMLInputFactory.SUPPORT_DTD flag is not used) * * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! */ XMLInputFactory inputFactory = XMLInputFactory.newInstance(); //disallow DTD and external entities inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); inputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false); XMLEventReader eventReader = inputFactory.createXMLEventReader(inputReader); RedirectEventFilter redirectEventFilter = new RedirectEventFilter(); XMLEventReader filteredReader = inputFactory.createFilteredReader(eventReader, redirectEventFilter); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); ReportingValidationEventHandler validationEventHandler = new ReportingValidationEventHandler(); unmarshaller.setEventHandler(validationEventHandler); unmarshaller.setListener(new RedirectUnmarshallerListener(redirectEventFilter)); unmarshaller.setSchema(slSchema); Object object; try { log.trace("Before unmarshal()."); object = unmarshaller.unmarshal(filteredReader); log.trace("After unmarshal()."); } catch (UnmarshalException e) { if (log.isDebugEnabled()) { log.debug("Failed to unmarshal security layer message.", e); } else { log.info("Failed to unmarshal security layer message." + (e.getMessage() != null ? " " + e.getMessage() : "")); } if (validationEventHandler.getErrorEvent() != null) { ValidationEvent errorEvent = validationEventHandler.getErrorEvent(); if (e.getLinkedException() == null) { e.setLinkedException(errorEvent.getLinkedException()); } } throw e; } return object; }
From source file:org.tellervo.desktop.wsi.JaxbResponseHandler.java
public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); }/*from ww w .j av a 2 s. co m*/ InputStream instream = entity.getContent(); if (instream == null) { return null; } String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } /** * Methodology * 1) Save XML to disk temporarily (it can be big, * we might want to look at it as a raw file) * 2) If we can't write to disk, throw IOException * 3) Try to parse * 4) Throw error with the raw document (it's malformed XML) */ File tempFile = null; OutputStreamWriter fileOut = null; boolean usefulFile = false; // preserve this file outside this local context? try { tempFile = File.createTempFile("tellervo", ".xml"); fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset); // ok, dump the webservice xml to a file BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset)); char indata[] = new char[8192]; int inlen; // write the file out while ((inlen = webIn.read(indata)) >= 0) fileOut.write(indata, 0, inlen); fileOut.close(); } catch (IOException ioe) { // File I/O failed (?!) Clean up and re-throw the IOE. if (fileOut != null) fileOut.close(); if (tempFile != null) tempFile.delete(); throw ioe; } try { Unmarshaller um = context.createUnmarshaller(); ValidationEventCollector vec = new ValidationEventCollector(); // validate against this schema um.setSchema(validateSchema); // collect events instead of throwing exceptions um.setEventHandler(vec); // do the magic! Object ret = um.unmarshal(tempFile); // typesafe way of checking if this is the right type! return returnClass.cast(ret); } catch (UnmarshalException ume) { usefulFile = true; throw new ResponseProcessingException(ume, tempFile); } catch (JAXBException jaxbe) { usefulFile = true; throw new ResponseProcessingException(jaxbe, tempFile); } catch (ClassCastException cce) { usefulFile = true; throw new ResponseProcessingException(cce, tempFile); } finally { // clean up and delete if (tempFile != null) { if (!usefulFile) tempFile.delete(); else tempFile.deleteOnExit(); } } /* try { um.un } catch (JDOMException jdome) { // this document must be malformed usefulFile = true; throw new XMLParsingException(jdome, tempFile); } } catch (IOException ioe) { // well, something there failed and it was lower level than just bad XML... if(tempFile != null) { usefulFile = true; throw new XMLParsingException(ioe, tempFile); } throw new XMLParsingException(ioe); } finally { // make sure we closed our file if(fileOut != null) fileOut.close(); // make sure we delete it, too if(tempFile != null) { if (!usefulFile) tempFile.delete(); else tempFile.deleteOnExit(); } } */ }
From source file:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java
private Object parseXML(String xmlStr) throws JAXBException { // if (log.isDebugEnabled()) { // Logger.debug("Workset Response: \n" + xmlStr); // }// w ww . j av a 2 s. c o m JAXBContext jaxbContext = JAXBContext.newInstance("edu.illinois.i3.htrc.registry.entities.workset"); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); unmarshaller.setEventHandler(new RSLValidationEventHandler()); JAXBElement<Object> worksets = (JAXBElement<Object>) unmarshaller .unmarshal(new ByteArrayInputStream(xmlStr.getBytes())); return worksets.getValue(); }