Example usage for javax.xml.bind ValidationEventHandler ValidationEventHandler

List of usage examples for javax.xml.bind ValidationEventHandler ValidationEventHandler

Introduction

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

Prototype

ValidationEventHandler

Source Link

Usage

From source file:main.java.refinement_class.Useful.java

public static Object unmashal2(String schema_file, String xml_file, Class c) {
    Object obj = null;/*w  ww .  ja  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 {

            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:main.java.refinement_class.Useful.java

public static boolean validation(String schema_file, String xml_file) {
    Object obj = null;//w  ww  .  j av  a  2 s  . co  m

    // create a JAXBContext capable of handling classes generated into
    // JAXBContext jc = JAXBContext.newInstance(ObjectFactory.class );

    JAXBContext jc;
    try {
        jc = JAXBContext.newInstance();

        // 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());
        }

    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        LOG.error(e.toString());
    }

    return true;

}

From source file:it.cnr.icar.eric.common.BindingUtility.java

public 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  .  ja v a 2s.  com*/
    });

    return unmarshaller;
}

From source file:it.cnr.icar.eric.client.ui.common.UIUtility.java

public Object convertToRimBinding(Object uiBindingObj) throws JAXRException {
    Object rimBindingObj = null;//  ww  w . ja  v a 2s. c  o m
    StringWriter sw = new StringWriter();
    try {
        Marshaller marshaller = uiJaxbContext.createMarshaller();
        if (uiBindingObj instanceof it.cnr.icar.eric.client.ui.common.conf.bindings.InternationalStringType) {
            it.cnr.icar.eric.client.ui.common.conf.bindings.ObjectFactory oF = new it.cnr.icar.eric.client.ui.common.conf.bindings.ObjectFactory();
            marshaller.marshal(oF.createInternationalString((InternationalStringType) uiBindingObj), sw);

            Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller();
            rimBindingObj = JAXBIntrospector
                    .getValue(unmarshaller.unmarshal(new StreamSource(new StringReader(sw.toString()))));
        } else {
            marshaller.marshal(uiBindingObj, sw);
            Unmarshaller unmarshaller = BindingUtility.getInstance().getJAXBContext().createUnmarshaller();
            //unmarshaller.setValidating(true);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                public boolean handleEvent(ValidationEvent event) {
                    boolean keepOn = false;

                    return keepOn;
                }
            });

            rimBindingObj = unmarshaller.unmarshal(new StreamSource(new StringReader(sw.toString())));
        }

    } catch (JAXBException e) {
        e.printStackTrace();
        throw new JAXRException(e);
    }
    return rimBindingObj;
}

From source file:org.alfresco.repo.audit.model.AuditModelRegistryImpl.java

/**
 * Unmarshalls the Audit model from a stream.
 *//*from w  w w  . j a  va  2 s .co m*/
private static Audit unmarshallModel(InputStream is, final String source) {
    final Schema schema;
    final JAXBContext jaxbCtx;
    final Unmarshaller jaxbUnmarshaller;
    try {
        SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
        schema = sf.newSchema(ResourceUtils.getURL(AUDIT_SCHEMA_LOCATION));
        jaxbCtx = JAXBContext.newInstance("org.alfresco.repo.audit.model._3");
        jaxbUnmarshaller = jaxbCtx.createUnmarshaller();
        jaxbUnmarshaller.setSchema(schema);
        jaxbUnmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent ve) {
                if (ve.getSeverity() == ValidationEvent.FATAL_ERROR
                        || ve.getSeverity() == ValidationEvent.ERROR) {
                    ValidationEventLocator locator = ve.getLocator();
                    logger.error("Invalid Audit XML: \n" + "   Source:   " + source + "\n"
                            + "   Location: Line " + locator.getLineNumber() + " column "
                            + locator.getColumnNumber() + "\n" + "   Error:    " + ve.getMessage());
                }
                return false;
            }
        });
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Failed to load Alfresco Audit Schema from " + AUDIT_SCHEMA_LOCATION,
                e);
    }
    try {
        // Unmarshall with validation
        @SuppressWarnings("unchecked")
        JAXBElement<Audit> auditElement = (JAXBElement<Audit>) jaxbUnmarshaller.unmarshal(is);

        Audit audit = auditElement.getValue();
        // Done
        return audit;
    } catch (Throwable e) {
        // Dig out a SAXParseException, if there is one
        Throwable saxError = ExceptionStackUtil.getCause(e, SAXParseException.class);
        if (saxError != null) {
            e = saxError;
        }
        throw new AuditModelException("Failed to read Audit model XML: \n" + "   Source: " + source + "\n"
                + "   Error:  " + e.getMessage());
    } finally {
        try {
            is.close();
        } catch (IOException e) {
        }
    }
}

From source file:org.apache.falcon.extensions.util.ExtensionProcessBuilderUtils.java

private static org.apache.falcon.entity.v0.process.Process bindAttributesInTemplate(
        final String processTemplate, final Properties extensionProperties, final String extensionName,
        final String wfPath, final String wfLibPath) throws FalconException {
    if (StringUtils.isBlank(processTemplate) || extensionProperties == null) {
        throw new FalconException("Process template or properties cannot be null");
    }//from   w  ww .  j  a  v  a  2  s. c o  m

    org.apache.falcon.entity.v0.process.Process process;
    try {
        Unmarshaller unmarshaller = EntityType.PROCESS.getUnmarshaller();
        // Validation can be skipped for unmarshalling as we want to bind template with the properties.
        // Vaildation is handled as part of marshalling
        unmarshaller.setSchema(null);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent validationEvent) {
                return true;
            }
        });
        process = (org.apache.falcon.entity.v0.process.Process) unmarshaller
                .unmarshal(new StringReader(processTemplate));
    } catch (Exception e) {
        throw new FalconException(e);
    }

    /* For optional properties user might directly set them in the process xml and might not set it in properties
       file. Before doing the submission validation is done to confirm process xml doesn't have
       EXTENSION_VAR_PATTERN
    */

    String processName = extensionProperties.getProperty(ExtensionProperties.JOB_NAME.getName());
    if (StringUtils.isNotEmpty(processName)) {
        process.setName(processName);
    }

    // DR process template has only one cluster
    bindClusterProperties(process.getClusters().getClusters().get(0), extensionProperties);

    // bind scheduling properties
    String processFrequency = extensionProperties.getProperty(ExtensionProperties.FREQUENCY.getName());
    if (StringUtils.isNotEmpty(processFrequency)) {
        process.setFrequency(Frequency.fromString(processFrequency));
    }

    String zone = extensionProperties.getProperty(ExtensionProperties.TIMEZONE.getName());
    if (StringUtils.isNotBlank(zone)) {
        process.setTimezone(TimeZone.getTimeZone(zone));
    } else {
        process.setTimezone(TimeZone.getTimeZone("UTC"));
    }

    bindWorkflowProperties(process.getWorkflow(), extensionName, wfPath, wfLibPath);
    bindRetryProperties(process.getRetry(), extensionProperties);
    bindNotificationProperties(process.getNotification(), extensionProperties);
    bindACLProperties(process.getACL(), extensionProperties);
    bindTagsProperties(process, extensionProperties);
    bindCustomProperties(process.getProperties(), extensionProperties);

    return process;
}

From source file:org.apache.falcon.recipe.util.RecipeProcessBuilderUtils.java

private static org.apache.falcon.entity.v0.process.Process bindAttributesInTemplate(final String templateFile,
        final Properties recipeProperties) throws Exception {
    if (templateFile == null || recipeProperties == null) {
        throw new IllegalArgumentException("Invalid arguments passed");
    }/*from  ww w .  j av a2 s . c  om*/

    Unmarshaller unmarshaller = EntityType.PROCESS.getUnmarshaller();
    // Validation can be skipped for unmarshalling as we want to bind tempalte with the properties. Vaildation is
    // hanles as part of marshalling
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        public boolean handleEvent(ValidationEvent validationEvent) {
            return true;
        }
    });

    URL processResourceUrl = new File(templateFile).toURI().toURL();
    org.apache.falcon.entity.v0.process.Process process = (org.apache.falcon.entity.v0.process.Process) unmarshaller
            .unmarshal(processResourceUrl);

    /* For optional properties user might directly set them in the process xml and might not set it in properties
       file. Before doing the submission validation is done to confirm process xml doesn't have RECIPE_VAR_PATTERN
    */

    String processName = recipeProperties.getProperty(RecipeToolOptions.RECIPE_NAME.getName());
    if (StringUtils.isNotEmpty(processName)) {
        process.setName(processName);
    }

    // DR process template has only one cluster
    bindClusterProperties(process.getClusters().getClusters().get(0), recipeProperties);

    // bind scheduling properties
    String processFrequency = recipeProperties.getProperty(RecipeToolOptions.PROCESS_FREQUENCY.getName());
    if (StringUtils.isNotEmpty(processFrequency)) {
        process.setFrequency(Frequency.fromString(processFrequency));
    }

    bindWorkflowProperties(process.getWorkflow(), recipeProperties);
    bindRetryProperties(process.getRetry(), recipeProperties);
    bindNotificationProperties(process.getNotification(), recipeProperties);
    bindACLProperties(process.getACL(), recipeProperties);
    bindTagsProperties(process, recipeProperties);
    bindCustomProperties(process.getProperties(), recipeProperties);

    return process;
}

From source file:org.dkpro.core.io.xces.XcesBasicXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();/*from   w  w  w . jav  a 2  s .c o m*/
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReaderBasic = xmlInputFactory.createXMLEventReader(is);

        //JAXB context for XCES body with basic type
        JAXBContext contextBasic = JAXBContext.newInstance(XcesBodyBasic.class);
        Unmarshaller unmarshallerBasic = contextBasic.createUnmarshaller();

        unmarshallerBasic.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent eBasic = null;
        while ((eBasic = xmlEventReaderBasic.peek()) != null) {
            if (isStartElement(eBasic, "body")) {
                try {
                    XcesBodyBasic parasBasic = (XcesBodyBasic) unmarshallerBasic
                            .unmarshal(xmlEventReaderBasic, XcesBodyBasic.class).getValue();
                    readPara(jb, parasBasic);
                } catch (RuntimeException ex) {
                    getLogger().warn("Input is not in basic xces format.");
                }
            } else {
                xmlEventReaderBasic.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.dkpro.core.io.xces.XcesXmlReader.java

@Override
public void getNext(JCas aJCas) throws IOException, CollectionException {

    Resource res = nextFile();//from   w  w w .j a  va2  s.com
    initCas(aJCas, res);

    InputStream is = null;

    try {
        is = CompressionUtils.getInputStream(res.getLocation(), res.getInputStream());

        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(is);

        JAXBContext context = JAXBContext.newInstance(XcesBody.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(ValidationEvent event) {
                throw new RuntimeException(event.getMessage(), event.getLinkedException());
            }
        });

        JCasBuilder jb = new JCasBuilder(aJCas);

        XMLEvent e = null;
        while ((e = xmlEventReader.peek()) != null) {

            if (isStartElement(e, "body")) {
                try {
                    XcesBody paras = (XcesBody) unmarshaller.unmarshal(xmlEventReader, XcesBody.class)
                            .getValue();
                    readPara(jb, paras);
                } catch (RuntimeException ex) {
                    System.out.println("Unable to parse XCES format: " + ex);
                }
            } else {
                xmlEventReader.next();
            }

        }
        jb.close();

    } catch (XMLStreamException ex1) {
        throw new IOException(ex1);
    } catch (JAXBException e1) {
        throw new IOException(e1);
    } finally {
        closeQuietly(is);
    }

}

From source file:org.eclipse.smila.connectivity.framework.schema.internal.JaxbPluginContext.java

/**
 * Creates the validating unmarshaller./*from   www.j a v a2 s .  co  m*/
 * 
 * @return the unmarshaller
 * 
 * @throws JAXBException
 *           the JAXB exception
 * @throws SchemaNotFoundException
 *           the index order schema not found exception
 */
public Unmarshaller createValidatingUnmarshaller() throws JAXBException, SchemaNotFoundException {
    initilize();
    assertNotNull(_context);
    final Unmarshaller unmarshaller = _context.createUnmarshaller();
    final SchemaFactory sf = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
    try {
        sf.setResourceResolver(new XSDContextURIResolver(sf.getResourceResolver()));
        final javax.xml.validation.Schema schema = sf
                .newSchema(Platform.getBundle(_id).getEntry(_plugIn.getSchemaLocation()));
        unmarshaller.setSchema(schema);
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            public boolean handleEvent(final ValidationEvent ve) {
                if (ve.getSeverity() != ValidationEvent.WARNING) {
                    final ValidationEventLocator vel = ve.getLocator();
                    _log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                    return false;
                }
                return true;
            }
        });
    } catch (final org.xml.sax.SAXException se) {
        throw new SchemaRuntimeException("Unable to validate due to following error.", se);
    }
    return unmarshaller;
}