protected org.kuali.rice.core.impl.config.property.Config unmarshal(Unmarshaller unmarshaller, InputStream in) throws SAXException, ParserConfigurationException, IOException, IllegalStateException, JAXBException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setNamespaceAware(true); XMLFilter filter = new ConfigNamespaceURIFilter(); filter.setParent(spf.newSAXParser().getXMLReader()); UnmarshallerHandler handler = unmarshaller.getUnmarshallerHandler(); filter.setContentHandler(handler); filter.parse(new InputSource(in)); return (org.kuali.rice.core.impl.config.property.Config) handler.getResult(); }
public static <T> T getPersistence(final Class<T> clazz, final InputStream persistenceDescriptor) throws Exception { final JAXBContext jc = clazz.getClassLoader() == JaxbPersistenceFactory.class.getClassLoader() ? JaxbJavaee.getContext(clazz) : JAXBContextFactory.newInstance(clazz); final Unmarshaller u = jc.createUnmarshaller(); final UnmarshallerHandler uh = u.getUnmarshallerHandler(); // create a new XML parser final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); factory.setValidating(true); final SAXParser parser = factory.newSAXParser(); final XMLReader xmlReader = parser.getXMLReader(); // Create a filter to intercept events final PersistenceFilter xmlFilter = new PersistenceFilter(xmlReader); // Be sure the filter has the JAXB content handler set (or it wont work) xmlFilter.setContentHandler(uh); final SAXSource source = new SAXSource(xmlFilter, new InputSource(persistenceDescriptor)); return (T) u.unmarshal(source); }
public final Object unmarshal( Node node ) throws JAXBException { try { DOMScanner scanner = new DOMScanner(); UnmarshallerHandler handler = new InterningUnmarshallerHandler( createUnmarshallerHandler(new DOMLocator(scanner))); if(node instanceof Element) scanner.parse((Element)node,handler); else if(node instanceof Document) scanner.parse(((Document)node).getDocumentElement(),handler); else // no other type of input is supported throw new IllegalArgumentException(); return handler.getResult(); } catch( SAXException e ) { throw createUnmarshalException(e); } }
@SuppressWarnings({ "unchecked", "resource" }) public T unmarshall(final InputStream inputStream) throws JAXBException, TransformerException { final Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller(); final UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); final Transformer transformer = this.inputTransformerTemplate.newTransformer(); final SAXResult saxResult = new SAXResult(unmarshallerHandler); final StreamSource streamSource = new StreamSource(new NoneClosingInputStream(inputStream)); transformer.transform(streamSource, saxResult); final Object result = unmarshallerHandler.getResult(); return (T) result; }
public static Object unmarshal(String path, String contextPath, String namespace) throws JAXBException, SAXException, ParserConfigurationException, IOException { UnmarshallerHandler unmarshallerHandler = JAXBContext .newInstance(contextPath).createUnmarshaller() .getUnmarshallerHandler(); XMLFilter xmlFilter = new NamespaceFilter(namespace); xmlFilter.setParent( SAXParserFactory.newInstance().newSAXParser().getXMLReader()); xmlFilter.setContentHandler(unmarshallerHandler); xmlFilter.parse(new InputSource(Thread.currentThread() .getContextClassLoader().getResource(path).getPath())); return unmarshallerHandler.getResult(); }
public static Object unmarshal(InputSource inputSource, String contextPath, String namespace) throws JAXBException, SAXException, ParserConfigurationException, IOException { UnmarshallerHandler unmarshallerHandler = JAXBContext .newInstance(contextPath).createUnmarshaller() .getUnmarshallerHandler(); XMLFilter xmlFilter = new NamespaceFilter(namespace); xmlFilter.setParent( SAXParserFactory.newInstance().newSAXParser().getXMLReader()); xmlFilter.setContentHandler(unmarshallerHandler); xmlFilter.parse(inputSource); return unmarshallerHandler.getResult(); }
/** * Parses the given XML to a Java model (JAXB unmarshalling). * Performs XSD validation. * * @param xml an input XML content * @param xmlPath a path to the input xml * @param xsds a full path to all XSDs corresponding to the given XML * @param pkg a package containing the corresponding Java model classes. * @param resultClass a corresponding Java model class. * @param <T> a corresponding Java model class. * @return a corresponding Java model instance. * @throws XmlParsingException if input is not a valid XML or it doesn't pass XSD validation */ public static <T> T parse(InputStream xml, String xmlPath, String[] xsds, String pkg, Class<T> resultClass) throws XmlParsingException { try { // 1. create JAXB unmarshaller JAXBContext jaxbContext = JAXBContext.newInstance(pkg); Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); // 2. create a an error and content handler (which is also a bridge between a sax parser and unmarshaller) XmlParsingHandler contentErrorHandler = new XmlParsingHandlerWrapper(unmarshallerHandler, xmlPath); // 3. do parse doParse(xml, xsds, contentErrorHandler); // 4. get unmarshall result Object result = JAXBIntrospector.getValue(unmarshallerHandler.getResult()); if (!resultClass.isInstance(result)) { throw new RuntimeException(String.format("A root element in '%s' must be an instance of %s type.", xmlPath, resultClass.getSimpleName())); } //noinspection unchecked return (T) result; } catch (JAXBException e) { throw new RuntimeException(e); } }
@Override protected void parsingCompleted(Exchange exchange, Message msg, AsyncXMLReader xmlReader){ UnmarshallerHandler handler = (UnmarshallerHandler)xmlReader.getContentHandler(); try{ String contentType = msg.getPayload().getMediaType().withCharset(IOUtil.UTF_8.name()).toString(); msg.setPayload(new JAXBPayload(contentType, handler.getResult(), jaxbContext)); }catch(Throwable thr){ exchange.resume(thr); return; } super.parsingCompleted(exchange, msg, xmlReader); }
public static Model unmarshal(InputSource inputSource){ try { JAXBContext jc = JAXBContext.newInstance(Model.class); XMLFilter filter = new NamespaceFilter(); filter.setParent(SAXParserFactory.newInstance().newSAXParser().getXMLReader()); UnmarshallerHandler unmarshallerHandler = jc.createUnmarshaller().getUnmarshallerHandler(); filter.setContentHandler(unmarshallerHandler); filter.parse(inputSource); return (Model) ((JAXBElement)unmarshallerHandler.getResult()).getValue(); } catch (Exception e) { throw new RuntimeException(e); } }
public UnmarshallerHandler getUnmarshallerHandler() { // use InterningUnmarshallerHandler since we don't know // if the caller will intern Strings before firing SAX events. // we don't know the Locator to be used, // but SAXLocator would always be a good default, // as the source of SAX2 events can always set org.xml.sax.Locator. return new InterningUnmarshallerHandler( createUnmarshallerHandler(new SAXLocator())); }
public UnmarshallerHandler getUnmarshallerHandler() { return getUnmarshallerHandler(true,null); }
@SuppressWarnings("unchecked") public static synchronized void init(URI uri, Class<?> callingClass) throws XMLSecurityException { if (initialized == null || uri != null && !uri.equals(initialized)) { try { JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class); final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = schemaFactory.newSchema( ClassLoaderUtils.getResource("schemas/security-config.xsd", Init.class)); unmarshaller.setSchema(schema); final UnmarshallerHandler unmarshallerHandler = unmarshaller.getUnmarshallerHandler(); SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setXIncludeAware(false); saxParserFactory.setNamespaceAware(true); SAXParser saxParser = saxParserFactory.newSAXParser(); if (uri == null) { URL resource = ClassLoaderUtils.getResource("security-config.xml", Init.class); if (resource == null) { //kind of chicken-egg problem here I18n.init("en", "US"); throw new XMLSecurityConfigurationException("empty", "security-config.xml not found in classpath"); } uri = resource.toURI(); } saxParser.parse(uri.toURL().toExternalForm(), new XIncludeHandler(unmarshallerHandler)); JAXBElement<ConfigurationType> configurationTypeJAXBElement = (JAXBElement<ConfigurationType>) unmarshallerHandler.getResult(); ConfigurationProperties.init(configurationTypeJAXBElement.getValue().getProperties(), callingClass); SecurityHeaderHandlerMapper.init(configurationTypeJAXBElement.getValue().getSecurityHeaderHandlers(), callingClass); JCEAlgorithmMapper.init(configurationTypeJAXBElement.getValue().getJCEAlgorithmMappings()); TransformerAlgorithmMapper.init(configurationTypeJAXBElement.getValue().getTransformAlgorithms(), callingClass); ResourceResolverMapper.init(configurationTypeJAXBElement.getValue().getResourceResolvers(), callingClass); I18n.init(ConfigurationProperties.getProperty("DefaultLanguageCode"), ConfigurationProperties.getProperty("DefaultCountryCode")); } catch (Exception e) { //kind of chicken-egg problem here I18n.init("en", "US"); throw new XMLSecurityConfigurationException(e); } initialized = uri; } }
public Unmarshaller initializeUnmarshaller(MzMLIndexer index, MzMLNamespaceFilter xmlFilter, MzMLObjectCache cache, boolean useCacheForSpectra) { try { // Lazy caching of the JAXB Context. if(jc == null) { jc = JAXBContext.newInstance(ModelConstants.PACKAGE); } //create unmarshaller Unmarshaller unmarshaller = jc.createUnmarshaller(); /* Sometimes it's convenient to maintain application states inside adapters; for example, if you have an adapter that converts string on XML into a java.lang.Class object, you might want to have a ClassLoader in an adapter. In JAXB, this is done by allowing applications to set configured instances of XmlAdapters to the unmarshaller/marshaller. This is also an opportunity to pass in a sub-class of the declared adapter, if you so wish. If the application doesn't provide a configured instance, JAXB will create one by calling the default constructor. */ //it is not possible to concurrently reuse a common unmarshaller //across all the Adapters because of internal state conflicts //when trying to unmarshall a referenced object from within a //parent object. //create a cache object that will be common to all adapters in this unmarshaller // unmarshaller.setAdapter(new CVAdapter(index, cache)); // unmarshaller.setAdapter(new DataProcessingAdapter(index, cache)); // unmarshaller.setAdapter(new InstrumentConfigurationAdapter(index, cache)); // unmarshaller.setAdapter(new ReferenceableParamGroupAdapter(index, cache)); // unmarshaller.setAdapter(new SampleAdapter(index, cache)); // unmarshaller.setAdapter(new SoftwareAdapter(index, cache)); // unmarshaller.setAdapter(new SourceFileAdapter(index, cache)); // unmarshaller.setAdapter(new SpectrumAdapter(index, cache, useCacheForSpectra)); // unmarshaller.setAdapter(new ScanSettingsAdapter(index, cache)); // unmarshaller.setEventHandler(new DefaultValidationEventHandler()); unmarshaller.setListener(new RawXMLListener(index,cache)); UnmarshallerHandler uh = unmarshaller.getUnmarshallerHandler(); // Create a new XML parser SAXParserFactory factory = SAXParserFactory.newInstance(); // WstxInputFactory inputFactory = new WstxInputFactory(); // inputFactory.configureForSpeed(); // SAXParserFactory factory = new WstxSAXParserFactory(inputFactory); // SAXParserFactory factory = new WstxSAXParserFactory(); factory.setNamespaceAware(true); SAXParser parser = factory.newSAXParser(); XMLReader xmlReader = parser.getXMLReader(); // Create a filter to intercept events -- and patch the missing namespace xmlFilter.setParent(xmlReader); xmlFilter.setContentHandler(uh); logger.debug("Unmarshaller Initialized"); return unmarshaller; } catch (JAXBException | SAXException | ParserConfigurationException e) { logger.error("UnmarshallerFactory.initializeUnmarshaller", e); throw new IllegalStateException("Could not initialize unmarshaller"); } }
protected T unmarshall(File filename, InputSource xml, HashMap<String,String> extra_overrides) throws Exception { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setXIncludeAware(true); spf.setNamespaceAware(true); spf.setFeature("http://apache.org/xml/features/xinclude/fixup-base-uris", false); StreamSource schemaSource = new StreamSource(this.getClass().getResourceAsStream("/sdrun.xsd")); SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); Schema schema = factory.newSchema(schemaSource); spf.setSchema(schema); NamespaceFiller filter = new NamespaceFiller(this.propertyOverrides(), extra_overrides); XMLReader xr = spf.newSAXParser().getXMLReader(); filter.setParent(xr); Unmarshaller u = jc.createUnmarshaller(); UnmarshallerHandler uh = u.getUnmarshallerHandler(); u.setSchema(schema); u.setEventHandler(new DefaultValidationEventHandler()); filter.setContentHandler(uh); try { filter.parse(xml); } catch(SAXParseException e) { filter.log_error(e); throw new XMLUnmarshallingFailure(); } T result = (T) uh.getResult(); if (result == null || filter.failed()) throw new XMLUnmarshallingFailure(); if (filter.conversion_hint) log.log(Logging.NOTICE, "Use the following command to convert old style files to the new format:\n" + "sed '1d; 2i <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\n<SDRun xmlns:xi=\"http://www.w3.org/2001/XInclude\" xmlns=\"{}\">\n" + "s#<(reactionScheme|morphology|stimulation|initialConditions|outputScheme)File>\\s*(\\w+)\\s*</.*>#<xi:include href=\"\\2.xml\" />#' -r -i.bak \"{}\"", NEURORD_NS, filename != null ? filename : "..."); return result; }