Example usage for javax.xml.bind ValidationEvent getLocator

List of usage examples for javax.xml.bind ValidationEvent getLocator

Introduction

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

Prototype

public ValidationEventLocator getLocator();

Source Link

Document

Retrieve the locator for this warning/error.

Usage

From source file:Main.java

public static <T> T unmarshal(Reader r, Class<T> clazz)
        throws JAXBException, XMLStreamException, FactoryConfigurationError {
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);/*  w  ww.j  a  va2  s .c o  m*/
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    XMLStreamReader xmlsr = XMLInputFactory.newFactory().createXMLStreamReader(r);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    unmarshaller.setSchema(null);
    unmarshaller.setEventHandler(valEventHndlr);

    JAXBElement<T> elem = null;
    try {
        elem = unmarshaller.unmarshal(xmlsr, clazz);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new UnmarshalException(e.getMessage(), e);
        }
    }

    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Unmarshall Exception if there is a parsing error
                String msg = MessageFormat.format("Line {0}, Col: {1}: {2}",
                        valEvent.getLocator().getLineNumber(), valEvent.getLocator().getColumnNumber(),
                        valEvent.getLinkedException().getMessage());
                throw new UnmarshalException(msg, valEvent.getLinkedException());
            }
        }
    }
    return elem.getValue();
}

From source file:com.rapid.server.RapidHttpServlet.java

public static Unmarshaller getUnmarshaller() throws JAXBException, IOException {

    // initialise the unmarshaller
    Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();
    // add the encrypted xml adapter
    unmarshaller.setAdapter(_encryptedXmlAdapter);

    // add a validation listener (this makes for better error messages)
    unmarshaller.setEventHandler(new ValidationEventHandler() {
        @Override/*from  w  ww  . j  ava 2s  .  c o m*/
        public boolean handleEvent(ValidationEvent event) {

            // get the location
            ValidationEventLocator location = event.getLocator();

            // log
            _logger.debug("JAXB validation event - " + event.getMessage()
                    + (location == null ? ""
                            : " at line " + location.getLineNumber() + ", column " + location.getColumnNumber()
                                    + ", node " + location.getNode()));

            // messages with "unrecognized type name" are very useful they're not sever themselves must almost always followed by a severe with a less meaningful message 
            if (event.getMessage().contains("unrecognized type name")
                    || event.getSeverity() == ValidationEvent.FATAL_ERROR) {
                return false;
            } else {
                return true;
            }

        }
    });

    // return
    return unmarshaller;
}

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

public static boolean validation(String schema_file, String xml_file) {
    Object obj = null;//from   w  w  w  . j  a va  2s.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:main.java.refinement_class.Useful.java

public static Object unmashal2(String schema_file, String xml_file, Class c) {
    Object obj = null;//from w  w  w .j a v a2 s  . co 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 Object unmashal(String schema_file, String xml_file, Class c) {
    Object obj = null;//from   ww  w . j a  va  2  s. 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.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from www  .java  2 s  .c  om

    // parse source
    try {

        JAXBContext jc = JAXBContext.newInstance("org.anodyneos.jse.cron.config");
        Unmarshaller u = jc.createUnmarshaller();
        //Schedule
        Source schemaSource = new StreamSource(Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("org/anodyneos/jse/cron/cron.xsd"));

        SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = sf.newSchema(schemaSource);
        u.setSchema(schema);
        ValidationEventCollector vec = new ValidationEventCollector();
        u.setEventHandler(vec);

        JAXBElement<?> rootElement;
        try {
            rootElement = ((JAXBElement<?>) u.unmarshal(source));
        } catch (UnmarshalException ex) {
            if (!vec.hasEvents()) {
                throw ex;
            } else {
                for (ValidationEvent ve : vec.getEvents()) {
                    ValidationEventLocator vel = ve.getLocator();
                    log.error("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                            + ve.getMessage());
                }
                throw new JseException("Validation failed for source publicId='" + source.getPublicId()
                        + "'; systemId='" + source.getSystemId() + "';");
            }
        }

        schedule = (Schedule) rootElement.getValue();

        if (vec.hasEvents()) {
            for (ValidationEvent ve : vec.getEvents()) {
                ValidationEventLocator vel = ve.getLocator();
                log.warn("Line:Col[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + "]:"
                        + ve.getMessage());
            }
        }

    } catch (JseException e) {
        throw e;
    } catch (Exception e) {
        throw new JseException("Cannot parse " + source + ".", e);
    }

    SpringHelper springHelper = new SpringHelper();

    ////////////////
    //
    // Configure Spring and Create Beans
    //
    ////////////////

    TimeZone defaultTimeZone;

    if (schedule.isSetTimeZone()) {
        defaultTimeZone = getTimeZone(schedule.getTimeZone());
    } else {
        defaultTimeZone = TimeZone.getDefault();
    }

    if (schedule.isSetSpringContext() && schedule.getSpringContext().isSetConfig()) {
        for (Config config : schedule.getSpringContext().getConfig()) {
            springHelper.addXmlClassPathConfigLocation(config.getClassPathResource());
        }
    }

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {
        for (Job job : jobGroup.getJob()) {
            if (job.isSetBeanRef()) {
                if (job.isSetBean() || job.isSetClassName()) {
                    throw new JseException("Cannot set bean or class attribute for job when beanRef is set.");
                } // else config ok
            } else {
                if (!job.isSetClassName()) {
                    throw new JseException("must set either class or beanRef for job.");
                }
                GenericBeanDefinition beanDef = new GenericBeanDefinition();
                MutablePropertyValues propertyValues = new MutablePropertyValues();

                if (!job.isSetBean()) {
                    job.setBean(UUID.randomUUID().toString());
                }

                if (springHelper.containsBean(job.getBean())) {
                    throw new JseException(
                            "Bean name already used; overriding not allowed here: " + job.getBean());
                }

                beanDef.setBeanClassName(job.getClassName());

                for (Property prop : job.getProperty()) {
                    String value = null;
                    if (prop.isSetSystemProperty()) {
                        value = System.getProperty(prop.getSystemProperty());
                    }
                    if (null == value) {
                        value = prop.getValue();
                    }

                    propertyValues.addPropertyValue(prop.getName(), value);
                }

                beanDef.setPropertyValues(propertyValues);
                springHelper.registerBean(job.getBean(), beanDef);
                job.setBeanRef(job.getBean());
            }
        }
    }

    springHelper.init();

    ////////////////
    //
    // Configure Timer Services
    //
    ////////////////

    for (org.anodyneos.jse.cron.config.JobGroup jobGroup : schedule.getJobGroup()) {

        String jobGroupName;
        JseTimerService service = new JseTimerService();

        timerServices.add(service);

        if (jobGroup.isSetName()) {
            jobGroupName = jobGroup.getName();
        } else {
            jobGroupName = UUID.randomUUID().toString();
        }

        if (jobGroup.isSetMaxConcurrent()) {
            service.setMaxConcurrent(jobGroup.getMaxConcurrent());
        }

        for (Job job : jobGroup.getJob()) {

            TimeZone jobTimeZone = defaultTimeZone;

            if (job.isSetTimeZone()) {
                jobTimeZone = getTimeZone(job.getTimeZone());
            } else {
                jobTimeZone = defaultTimeZone;
            }

            Object obj;

            Date notBefore = null;
            Date notAfter = null;

            if (job.isSetNotBefore()) {
                notBefore = job.getNotBefore().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }
            if (job.isSetNotAfter()) {
                notAfter = job.getNotAfter().toGregorianCalendar(jobTimeZone, null, null).getTime();
            }

            CronSchedule cs = new CronSchedule(job.getSchedule(), jobTimeZone, job.getMaxIterations(),
                    job.getMaxQueue(), notBefore, notAfter);

            obj = springHelper.getBean(job.getBeanRef());
            log.info("Adding job " + jobGroup.getName() + "/" + job.getName() + " using bean "
                    + job.getBeanRef());
            if (obj instanceof CronJob) {
                ((CronJob) obj).setCronContext(new CronContext(jobGroupName, job.getName(), cs));
            }
            if (obj instanceof JseDateAwareJob) {
                service.createTimer((JseDateAwareJob) obj, cs);
            } else if (obj instanceof Runnable) {
                service.createTimer((Runnable) obj, cs);
            } else {
                throw new JseException("Job must implement Runnable or JseDateAwareJob");
            }
        }
    }
}

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

/**
 * Unmarshalls the Audit model from a stream.
 *//*from   w  ww  .  j a  v  a  2 s .c  om*/
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.cloudgraph.config.CloudGraphConfigValidationEventHandler.java

public boolean handleEvent(ValidationEvent ve) {
    boolean result = this.cumulative;
    this.errorCount++;
    ValidationEventLocator vel = ve.getLocator();

    String message = "Line:Col:Offset[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + ":"
            + String.valueOf(vel.getOffset()) + "] - " + ve.getMessage();

    switch (ve.getSeverity()) {
    case ValidationEvent.WARNING:
        log.warn(message);/* w  ww .  j a v  a2  s.  com*/
        break;
    case ValidationEvent.ERROR:
    case ValidationEvent.FATAL_ERROR:
        log.fatal(message);
        throw new CloudGraphConfigurationException(message);
    default:
        log.error(message);
    }
    return result;
}

From source file:org.cloudgraph.store.mapping.StoreMappingValidationEventHandler.java

public boolean handleEvent(ValidationEvent ve) {
    boolean result = this.cumulative;
    this.errorCount++;
    ValidationEventLocator vel = ve.getLocator();

    String message = "Line:Col:Offset[" + vel.getLineNumber() + ":" + vel.getColumnNumber() + ":"
            + String.valueOf(vel.getOffset()) + "] - " + ve.getMessage();

    switch (ve.getSeverity()) {
    case ValidationEvent.WARNING:
        log.warn(message);//from   ww w . j  a  v a2  s . c o  m
        break;
    case ValidationEvent.ERROR:
    case ValidationEvent.FATAL_ERROR:
        log.fatal(message);
        throw new StoreMappingException(message);
    default:
        log.error(message);
    }
    return result;
}

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

/**
 * Creates the validating unmarshaller.//from w  w  w. java2  s. com
 * 
 * @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;
}