javax.xml.bind.ValidationEventHandler Java Examples

The following examples show how to use javax.xml.bind.ValidationEventHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConversionService.java    From validator with Apache License 2.0 6 votes vote down vote up
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) {
    if (model == null) {
        throw new ConversionExeption("Can not serialize null");
    }
    try ( final StringWriter w = new StringWriter() ) {
        final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector();
        final Marshaller marshaller = getJaxbContext().createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setSchema(schema);
        marshaller.setEventHandler(handler);
        final XMLOutputFactory xof = XMLOutputFactory.newFactory();
        final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
        if (null == introspector.getElementName(model)) {
            final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
            marshaller.marshal(jaxbElement, xmlStreamWriter);
        } else {
            marshaller.marshal(model, xmlStreamWriter);
        }
        xmlStreamWriter.flush();
        return w.toString();
    } catch (final JAXBException | IOException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e);
    }
}
 
Example #2
Source File: TestSuites.java    From gradle-golang-plugin with Mozilla Public License 2.0 6 votes vote down vote up
@Nonnull
private static javax.xml.bind.Marshaller marshallerFor(@Nonnull TestSuites element) {
    final javax.xml.bind.Marshaller marshaller;
    try {
        marshaller = JAXB_CONTEXT.createMarshaller();
        marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true);
        marshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(ValidationEvent event) {
                return true;
            }
        });
    } catch (final Exception e) {
        throw new RuntimeException("Could not create marshaller to marshall " + element + ".", e);
    }
    return marshaller;
}
 
Example #3
Source File: UnmarshallingContext.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example #4
Source File: UnmarshallingContext.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example #5
Source File: UnmarshallingContext.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Reports an error to the user, and asks if s/he wants
 * to recover. If the canRecover flag is false, regardless
 * of the client instruction, an exception will be thrown.
 *
 * Only if the flag is true and the user wants to recover from an error,
 * the method returns normally.
 *
 * The thrown exception will be catched by the unmarshaller.
 */
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
    ValidationEventHandler eventHandler = parent.getEventHandler();

    boolean recover = eventHandler.handleEvent(event);

    // if the handler says "abort", we will not return the object
    // from the unmarshaller.getResult()
    if(!recover)    aborted = true;

    if( !canRecover || !recover )
        throw new SAXParseException2( event.getMessage(), locator,
            new UnmarshalException(
                event.getMessage(),
                event.getLinkedException() ) );
}
 
Example #6
Source File: GenericJAXBMarshaller.java    From ph-commons with Apache License 2.0 6 votes vote down vote up
/**
 * @param aClassLoader
 *        The class loader to be used for XML schema resolving. May be
 *        <code>null</code>.
 * @return The JAXB unmarshaller to use. Never <code>null</code>.
 * @throws JAXBException
 *         In case the creation fails.
 */
@Nonnull
private Unmarshaller _createUnmarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException
{
  final JAXBContext aJAXBContext = getJAXBContext (aClassLoader);

  // create an Unmarshaller
  final Unmarshaller aUnmarshaller = aJAXBContext.createUnmarshaller ();
  if (m_aVEHFactory != null)
  {
    // Create and set a new event handler
    final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aUnmarshaller.getEventHandler ());
    if (aEvHdl != null)
      aUnmarshaller.setEventHandler (aEvHdl);
  }

  // Set XSD (if any)
  final Schema aValidationSchema = createValidationSchema ();
  if (aValidationSchema != null)
    aUnmarshaller.setSchema (aValidationSchema);

  return aUnmarshaller;
}
 
Example #7
Source File: XMLSerializer.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public void reportError( ValidationEvent ve ) throws SAXException {
    ValidationEventHandler handler;

    try {
        handler = marshaller.getEventHandler();
    } catch( JAXBException e ) {
        throw new SAXException2(e);
    }

    if(!handler.handleEvent(ve)) {
        if(ve.getLinkedException() instanceof Exception)
            throw new SAXException2((Exception)ve.getLinkedException());
        else
            throw new SAXException2(ve.getMessage());
    }
}
 
Example #8
Source File: JaxbSun.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
    // create a parser with validation disabled
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    final SAXParser parser = factory.newSAXParser();

    // Get the JAXB context -- this should be cached
    final JAXBContext ctx = JAXBContextFactory.newInstance(type);

    // get the unmarshaller
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();

    // log errors?
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(final ValidationEvent validationEvent) {
            if (logErrors) {
                System.out.println(validationEvent);
            }
            return false;
        }
    });

    // add our XMLFilter which disables dtd downloading
    final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());

    // Wrap the input stream with our filter
    final SAXSource source = new SAXSource(xmlFilter, new InputSource(in));

    // unmarshal the document
    return unmarshaller.unmarshal(source);
}
 
Example #9
Source File: AbstractMarshallerImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
 */
public void setEventHandler(ValidationEventHandler handler)
    throws JAXBException {

    if( handler == null ) {
        eventHandler = new DefaultValidationEventHandler();
    } else {
        eventHandler = handler;
    }
}
 
Example #10
Source File: BridgeContextImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void setErrorHandler(ValidationEventHandler handler) {
    try {
        unmarshaller.setEventHandler(handler);
        marshaller.setEventHandler(handler);
    } catch (JAXBException e) {
        // impossible
        throw new Error(e);
    }
}
 
Example #11
Source File: JaxbOpenejbJar2.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
    final InputSource inputSource = new InputSource(in);

    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(false);
    final SAXParser parser = factory.newSAXParser();

    final JAXBContext ctx = getContext(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(final ValidationEvent validationEvent) {
            if (logErrors) {
                System.out.println(validationEvent);
            }
            return false;
        }
    });

    unmarshaller.setListener(new Unmarshaller.Listener() {
        public void afterUnmarshal(final Object object, final Object object1) {
            super.afterUnmarshal(object, object1);
        }

        public void beforeUnmarshal(final Object target, final Object parent) {
            super.beforeUnmarshal(target, parent);
        }
    });


    final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());

    final SAXSource source = new SAXSource(xmlFilter, inputSource);

    return unmarshaller.unmarshal(source, type);
}
 
Example #12
Source File: BridgeContextImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public void setErrorHandler(ValidationEventHandler handler) {
    try {
        unmarshaller.setEventHandler(handler);
        marshaller.setEventHandler(handler);
    } catch (JAXBException e) {
        // impossible
        throw new Error(e);
    }
}
 
Example #13
Source File: XMLStreamDataWriterTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private DataWriterImpl<XMLStreamWriter> newDataWriter(ValidationEventHandler handler) throws Exception {
    JAXBDataBinding db = getTestWriterFactory();

    DataWriterImpl<XMLStreamWriter> dw = (DataWriterImpl<XMLStreamWriter>)db.createWriter(XMLStreamWriter.class);
    assertNotNull(dw);

    // Build message to set custom event handler
    org.apache.cxf.message.Message message = new org.apache.cxf.message.MessageImpl();
    message.put(JAXBDataBinding.WRITER_VALIDATION_EVENT_HANDLER, handler);

    dw.setProperty("org.apache.cxf.message.Message", message);

    return dw;
}
 
Example #14
Source File: AbstractMarshallerImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
 */
public void setEventHandler(ValidationEventHandler handler)
    throws JAXBException {

    if( handler == null ) {
        eventHandler = new DefaultValidationEventHandler();
    } else {
        eventHandler = handler;
    }
}
 
Example #15
Source File: BridgeContextImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void setErrorHandler(ValidationEventHandler handler) {
    try {
        unmarshaller.setEventHandler(handler);
        marshaller.setEventHandler(handler);
    } catch (JAXBException e) {
        // impossible
        throw new Error(e);
    }
}
 
Example #16
Source File: AbstractMarshallerImpl.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/**
 * @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
 */
public void setEventHandler(ValidationEventHandler handler)
    throws JAXBException {

    if( handler == null ) {
        eventHandler = new DefaultValidationEventHandler();
    } else {
        eventHandler = handler;
    }
}
 
Example #17
Source File: UnmarshallerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final ValidationEventHandler getEventHandler() {
    try {
        return super.getEventHandler();
    } catch (JAXBException e) {
        // impossible
        throw new AssertionError();
    }
}
 
Example #18
Source File: AbstractMarshallerImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
 */
public void setEventHandler(ValidationEventHandler handler)
    throws JAXBException {

    if( handler == null ) {
        eventHandler = new DefaultValidationEventHandler();
    } else {
        eventHandler = handler;
    }
}
 
Example #19
Source File: JaxbJavaee.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * Read in a T from the input stream.
 *
 * @param type     Class of object to be read in
 * @param in       input stream to read
 * @param validate whether to validate the input.
 * @param <T>      class of object to be returned
 * @return a T read from the input stream
 * @throws ParserConfigurationException is the SAX parser can not be configured
 * @throws SAXException                 if there is an xml problem
 * @throws JAXBException                if the xml cannot be marshalled into a T.
 */
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean validate) throws ParserConfigurationException, SAXException, JAXBException {
    final InputSource inputSource = new InputSource(in);

    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    factory.setValidating(validate);
    final SAXParser parser = factory.newSAXParser();

    final JAXBContext ctx = JaxbJavaee.getContext(type);
    final Unmarshaller unmarshaller = ctx.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(final ValidationEvent validationEvent) {
            System.out.println(validationEvent);
            return false;
        }
    });

    final JaxbJavaee.NoSourceFilter xmlFilter = new JaxbJavaee.NoSourceFilter(parser.getXMLReader());
    xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());

    final SAXSource source = new SAXSource(xmlFilter, inputSource);

    currentPublicId.set(new TreeSet<String>());
    try {
        return unmarshaller.unmarshal(source);
    } finally {
        currentPublicId.set(null);
    }
}
 
Example #20
Source File: UnmarshallerImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final ValidationEventHandler getEventHandler() {
    try {
        return super.getEventHandler();
    } catch (JAXBException e) {
        // impossible
        throw new AssertionError();
    }
}
 
Example #21
Source File: UnmarshallerImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final ValidationEventHandler getEventHandler() {
    try {
        return super.getEventHandler();
    } catch (JAXBException e) {
        // impossible
        throw new AssertionError();
    }
}
 
Example #22
Source File: ConversionService.java    From validator with Apache License 2.0 5 votes vote down vote up
public <T> T readXml(final URI xml, final Class<T> type, final Schema schema, final ValidationEventHandler handler) {
    checkInputEmpty(xml);
    checkTypeEmpty(type);
    CollectingErrorEventHandler defaultHandler = null;
    ValidationEventHandler handler2Use = handler;
    if (schema != null && handler == null) {
        defaultHandler = new CollectingErrorEventHandler();
        handler2Use = defaultHandler;
    }
    try {
        final XMLInputFactory inputFactory = XMLInputFactory.newFactory();
        inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
        inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        final XMLStreamReader xsr = inputFactory.createXMLStreamReader(new StreamSource(xml.toASCIIString()));
        final Unmarshaller u = getJaxbContext().createUnmarshaller();
        u.setSchema(schema);

        u.setEventHandler(handler2Use);
        final T value = u.unmarshal(xsr, type).getValue();
        if (defaultHandler != null && defaultHandler.hasErrors()) {
            throw new ConversionExeption(
                    String.format("Schema errors while reading content from %s: %s", xml, defaultHandler.getErrorDescription()));
        }

        return value;
    } catch (final JAXBException | XMLStreamException e) {
        throw new ConversionExeption(String.format("Can not unmarshal to type %s from %s", type.getSimpleName(), xml.toString()), e);
    }
}
 
Example #23
Source File: JAXBDataBase.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected ValidationEventHandler getValidationEventHandler(String cn) {
    try {
        return (ValidationEventHandler)ClassLoaderUtils.loadClass(cn, getClass()).newInstance();
    } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
        LOG.log(Level.INFO, "Could not create validation event handler", e);
    }
    return null;
}
 
Example #24
Source File: DomHandlerEx.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public Source marshal(DomAndLocation domAndLocation, ValidationEventHandler errorHandler) {
    return new DOMSource(domAndLocation.element);
}
 
Example #25
Source File: DataReaderImpl.java    From cxf with Apache License 2.0 4 votes vote down vote up
WSUIDValidationHandler(ValidationEventHandler o) {
    origHandler = o;
}
 
Example #26
Source File: AbstractMarshallerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @see javax.xml.bind.Marshaller#getEventHandler()
 */
public ValidationEventHandler getEventHandler() throws JAXBException {
    return eventHandler;
}
 
Example #27
Source File: DomHandlerEx.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public Source marshal(DomAndLocation domAndLocation, ValidationEventHandler errorHandler) {
    return new DOMSource(domAndLocation.element);
}
 
Example #28
Source File: DomHandlerEx.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public ResultImpl createUnmarshaller(ValidationEventHandler errorHandler) {
    return new ResultImpl();
}
 
Example #29
Source File: XmlIO.java    From beam with Apache License 2.0 4 votes vote down vote up
@Nullable
abstract ValidationEventHandler getValidationEventHandler();
 
Example #30
Source File: DomHandlerEx.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
public ResultImpl createUnmarshaller(ValidationEventHandler errorHandler) {
    return new ResultImpl();
}