Example usage for javax.xml.bind Unmarshaller setListener

List of usage examples for javax.xml.bind Unmarshaller setListener

Introduction

In this page you can find the example usage for javax.xml.bind Unmarshaller setListener.

Prototype

public void setListener(Listener listener);

Source Link

Document

Register unmarshal event callback Listener with this Unmarshaller .

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Customer.class);

    XMLInputFactory xif = XMLInputFactory.newFactory();
    XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource(new File("input.xml")));

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    unmarshaller.setListener(new LocationListener(xsr));
    Customer customer = (Customer) unmarshaller.unmarshal(xsr);
}

From source file:Main.java

private static <T> Unmarshaller getUnmarshaller(Class<T> clazz, Unmarshaller.Listener listener)
        throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller unmarshaller = jc.createUnmarshaller();
    if (listener != null) {
        unmarshaller.setListener(listener);
    }//from w w  w  .j a  va 2  s . c  om
    return unmarshaller;
}

From source file:ee.ria.xroad.common.message.SoapParserImpl.java

@SuppressWarnings("unchecked")
static <T> T unmarshalHeader(Class<?> clazz, SOAPHeader soapHeader, boolean checkRequiredFields)
        throws Exception {
    Unmarshaller unmarshaller = JaxbUtils.createUnmarshaller(clazz);

    if (checkRequiredFields) {
        unmarshaller.setListener(new RequiredHeaderFieldsChecker(clazz));
    }/*from  w w  w. java  2 s . co  m*/

    unmarshaller.setEventHandler(event -> {
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
            return true;
        case ValidationEvent.ERROR:
            Throwable t = event.getLinkedException();

            return !(t instanceof AccessorException && t.getCause() instanceof CodedException);
        case ValidationEvent.FATAL_ERROR:
            return false;
        default:
            return true;
        }
    });

    JAXBElement<T> jaxbElement = (JAXBElement<T>) unmarshaller.unmarshal(soapHeader, clazz);
    return jaxbElement.getValue();
}

From source file:com.bitplan.jaxb.JaxbFactory.java

/**
 * get a fitting Unmarshaller/*from  w w  w  .java2  s. c om*/
 * 
 * @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/*from   w w w .  j a  v a  2 s.c o 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.apache.hadoop.hbase.rest.TestTableScan.java

/**
 * An example to scan using listener in unmarshaller for XML.
 * @throws Exception the exception//from   w  w  w  .  j  a v  a2  s.  c  o m
 */
@Test
public void testScanUsingListenerUnmarshallerXML() throws Exception {
    StringBuilder builder = new StringBuilder();
    builder.append("/*");
    builder.append("?");
    builder.append(Constants.SCAN_COLUMN + "=" + COLUMN_1);
    builder.append("&");
    builder.append(Constants.SCAN_LIMIT + "=10");
    Response response = client.get("/" + TABLE + builder.toString(), Constants.MIMETYPE_XML);
    assertEquals(200, response.getCode());
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    JAXBContext context = JAXBContext.newInstance(ClientSideCellSetModel.class, RowModel.class,
            CellModel.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();

    final ClientSideCellSetModel.Listener listener = new ClientSideCellSetModel.Listener() {
        @Override
        public void handleRowModel(ClientSideCellSetModel helper, RowModel row) {
            assertTrue(row.getKey() != null);
            assertTrue(row.getCells().size() > 0);
        }
    };

    // install the callback on all ClientSideCellSetModel instances
    unmarshaller.setListener(new Unmarshaller.Listener() {
        public void beforeUnmarshal(Object target, Object parent) {
            if (target instanceof ClientSideCellSetModel) {
                ((ClientSideCellSetModel) target).setCellSetModelListener(listener);
            }
        }

        public void afterUnmarshal(Object target, Object parent) {
            if (target instanceof ClientSideCellSetModel) {
                ((ClientSideCellSetModel) target).setCellSetModelListener(null);
            }
        }
    });

    // create a new XML parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader reader = factory.newSAXParser().getXMLReader();
    reader.setContentHandler(unmarshaller.getUnmarshallerHandler());
    assertFalse(ClientSideCellSetModel.listenerInvoked);
    reader.parse(new InputSource(response.getStream()));
    assertTrue(ClientSideCellSetModel.listenerInvoked);

}

From source file:org.jboss.rusheye.parser.Parser.java

private void parseFile(File file, boolean tmpfile) {
    VisualSuite visualSuite = null;/*ww  w.j ava2  s  .co  m*/
    try {
        XMLValidationSchemaFactory schemaFactory = XMLValidationSchemaFactory
                .newInstance(XMLValidationSchema.SCHEMA_ID_W3C_SCHEMA);
        URL schemaURL = getClass().getClassLoader().getResource("org/jboss/rusheye/visual-suite.xsd");
        XMLValidationSchema schema = schemaFactory.createSchema(schemaURL);

        XMLInputFactory2 factory = (XMLInputFactory2) XMLInputFactory.newInstance();

        StreamFilter filter = new StreamFilter() {
            @Override
            public boolean accept(XMLStreamReader reader) {
                return reader.isStartElement();
            }
        };

        XMLStreamReader2 reader = factory.createXMLStreamReader(file);
        XMLStreamReader2 filteredReader = new Stax2FilteredStreamReader(reader, filter);

        reader.validateAgainst(schema);

        // EventFilter filter = new EventFilter() {
        // @Override
        // public boolean accept(XMLEvent reader) {
        // return reader.isStartElement();
        // }
        // };
        //
        // XMLEventReader reader = factory.createXMLEventReader(file);
        // XMLEventReader filteredReader = factory.createFilteredReader(reader, filter);

        JAXBContext ctx = JAXBContext.newInstance(VisualSuite.class.getPackage().getName());
        Unmarshaller um = ctx.createUnmarshaller();

        UnmarshallerMultiListener listener = new UnmarshallerMultiListener();
        um.setListener(listener);

        // skip parsing of the first element - visual-suite
        filteredReader.nextTag();

        visualSuite = new VisualSuite();
        handler.setVisualSuite(visualSuite);
        handler.getContext().invokeListeners().onSuiteStarted(visualSuite);

        listener.registerListener(new UniqueIdentityChecker(handler.getContext()));

        while (filteredReader.hasNext()) {
            try {
                // go on the start of the next tag
                filteredReader.nextTag();

                Object o = um.unmarshal(reader);
                if (o instanceof GlobalConfiguration) {
                    GlobalConfiguration globalConfiguration = (GlobalConfiguration) o;
                    handler.getContext().setCurrentConfiguration(globalConfiguration);
                    visualSuite.setGlobalConfiguration(globalConfiguration);
                    handler.getContext().invokeListeners().onConfigurationReady(visualSuite);

                    RetriverInjector retriverInjector = new RetriverInjector(this);
                    for (Mask mask : globalConfiguration.getMasks()) {
                        retriverInjector.afterUnmarshal(mask, null);
                    }
                    listener.registerListener(retriverInjector);
                }
                if (o instanceof Test) {
                    Test test = (Test) o;
                    handler.getContext().setCurrentConfiguration(test);
                    handler.getContext().setCurrentTest(test);
                    for (Pattern pattern : test.getPatterns()) {
                        handler.getContext().invokeListeners().onPatternReady(test, pattern);
                    }
                    Test testWrapped = ConfigurationCompiler.wrap(test, visualSuite.getGlobalConfiguration());
                    handler.getContext().invokeListeners().onTestReady(testWrapped);
                }
            } catch (WstxParsingException e) {
                // intentionally blank - wrong end of document detection
            }

        }
    } catch (XMLStreamException e) {
        throw handleParsingException(e, e);
    } catch (JAXBException e) {
        throw handleParsingException(e, e.getLinkedException());
    } finally {
        if (visualSuite != null && handler.getContext() != null) {
            handler.getContext().invokeListeners().onSuiteReady(visualSuite);
        }
        if (tmpfile) {
            FileUtils.deleteQuietly(file);
        }
    }
}

From source file:org.linguafranca.pwdb.kdbx.jaxb.JaxbSerializableDatabase.java

@Override
public JaxbSerializableDatabase load(InputStream inputStream) {
    try {//from w ww  .j  a v a 2  s .  c  o  m
        JAXBContext jc = JAXBContext.newInstance(KeePassFile.class);
        Unmarshaller u = jc.createUnmarshaller();
        u.setListener(new Unmarshaller.Listener() {
            @Override
            public void afterUnmarshal(Object target, Object parent) {
                try {
                    if (target instanceof StringField.Value) {
                        StringField.Value value = (StringField.Value) target;
                        if (value.getProtected() != null && value.getProtected()) {
                            byte[] encrypted = Base64.decodeBase64(value.getValue().getBytes());
                            String decrypted = new String(encryption.decrypt(encrypted), "UTF-8");
                            value.setValue(decrypted);
                            value.setProtected(false);
                        }
                    }
                    if (target instanceof JaxbGroupBinding && (parent instanceof JaxbGroupBinding)) {
                        ((JaxbGroupBinding) target).parent = ((JaxbGroupBinding) parent);
                    }
                    if (target instanceof JaxbEntryBinding && (parent instanceof JaxbGroupBinding)) {
                        ((JaxbEntryBinding) target).parent = ((JaxbGroupBinding) parent);
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new IllegalStateException();
                }
            }
        });
        keePassFile = (KeePassFile) u.unmarshal(inputStream);
        return this;
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.openhab.binding.homematic.internal.communicator.client.CcuClient.java

/**
 * Main method for sending a TclRega script and parsing the XML result.
 */// ww w . j a v a 2s.c o m
@SuppressWarnings("unchecked")
private synchronized <T> T sendScript(String script, Class<T> clazz) throws HomematicClientException {
    PostMethod post = null;
    try {
        script = StringUtils.trim(script);
        if (StringUtils.isEmpty(script)) {
            throw new RuntimeException("Homematic TclRegaScript is empty!");
        }
        if (TRACE_ENABLED) {
            logger.trace("TclRegaScript: {}", script);
        }

        post = new PostMethod(context.getConfig().getTclRegaUrl());
        RequestEntity re = new ByteArrayRequestEntity(script.getBytes("ISO-8859-1"));
        post.setRequestEntity(re);
        httpClient.executeMethod(post);

        String result = post.getResponseBodyAsString();
        result = StringUtils.substringBeforeLast(result, "<xml><exec>");
        if (TRACE_ENABLED) {
            logger.trace("Result TclRegaScript: {}", result);
        }

        Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
        um.setListener(new CommonUnmarshallerListener());
        return (T) um.unmarshal(new StringReader(result));
    } catch (Exception ex) {
        throw new HomematicClientException(ex.getMessage(), ex);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.openhab.binding.homematic.internal.communicator.client.TclRegaScriptClient.java

/**
 * Main method for sending a TclRega script and parsing the XML result.
 *//*from  w w  w.  ja va 2s . c o  m*/
@SuppressWarnings("unchecked")
private synchronized <T> T sendScript(String script, Class<T> clazz) throws CcuClientException {
    PostMethod post = null;
    try {
        script = StringUtils.trim(script);
        if (StringUtils.isEmpty(script)) {
            throw new RuntimeException("Homematic TclRegaScript is empty!");
        }
        if (TRACE_ENABLED) {
            logger.trace("TclRegaScript: {}", script);
        }

        post = new PostMethod(context.getConfig().getTclRegaUrl());
        RequestEntity re = new ByteArrayRequestEntity(script.getBytes("ISO-8859-1"));
        post.setRequestEntity(re);
        httpClient.executeMethod(post);

        String result = post.getResponseBodyAsString();
        result = StringUtils.substringBeforeLast(result, "<xml><exec>");
        if (TRACE_ENABLED) {
            logger.trace("Result TclRegaScript: {}", result);
        }

        Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
        um.setListener(new CommonUnmarshallerListener());
        return (T) um.unmarshal(new StringReader(result));
    } catch (Exception ex) {
        throw new CcuClientException(ex.getMessage(), ex);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}