Example usage for javax.xml.bind.util ValidationEventCollector getEvents

List of usage examples for javax.xml.bind.util ValidationEventCollector getEvents

Introduction

In this page you can find the example usage for javax.xml.bind.util ValidationEventCollector getEvents.

Prototype

public ValidationEvent[] getEvents() 

Source Link

Document

Return an array of ValidationEvent objects containing a copy of each of the collected errors and warnings.

Usage

From source file:Main.java

@SuppressWarnings("rawtypes")
public static void marshal(Object object, Writer w) throws JAXBException {
    Class clazz = object.getClass();
    JAXBContext context = s_contexts.get(clazz);
    if (context == null) {
        context = JAXBContext.newInstance(clazz);
        s_contexts.put(clazz, context);//  ww w .jav  a 2s  .co  m
    }

    ValidationEventCollector valEventHndlr = new ValidationEventCollector();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setSchema(null);
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.setEventHandler(valEventHndlr);

    try {
        marshaller.marshal(object, w);
    } catch (Exception e) {
        if (e instanceof JAXBException) {
            throw (JAXBException) e;
        } else {
            throw new MarshalException(e.getMessage(), e);
        }
    }
    if (valEventHndlr.hasEvents()) {
        for (ValidationEvent valEvent : valEventHndlr.getEvents()) {
            if (valEvent.getSeverity() != ValidationEvent.WARNING) {
                // throw a new Marshall Exception if there is a parsing error
                throw new MarshalException(valEvent.getMessage(), valEvent.getLinkedException());
            }
        }
    }
}

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);//from   w ww  .j  ava 2s . com
    }

    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:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from w w w. j a  v a 2 s  .  co  m

    // 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:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private void read() throws JAXBException {
    long currentTime = file.lastModified();
    if (currentTime == lastModified) {
        return;//from w ww.java2s  . com
    }
    Unmarshaller unmarshaller = getUnmarshaller();
    ValidationEventCollector errors = (ValidationEventCollector) unmarshaller.getEventHandler();
    WorkflowDefinition fetchedWf = null;
    try {
        WorkflowDefinition wf = (WorkflowDefinition) unmarshaller.unmarshal(file);
        if (!errors.hasEvents()) {
            readCaches(wf);
            fetchedWf = wf;
        }
    } catch (UnmarshalException ex) {
        if (!errors.hasEvents()) {
            throw ex;
        }
    } finally {
        setProfiles(fetchedWf, currentTime);
    }
    if (errors.hasEvents()) {
        StringBuilder err = new StringBuilder();
        for (ValidationEvent event : errors.getEvents()) {
            err.append(event).append('\n');
        }
        throw new JAXBException(err.toString());
    }
}

From source file:gov.nih.nci.ncicb.tcga.dcc.common.jaxb.JAXBUtil.java

/**
 * This method unmarshals an XML file into a JAXB object element.
 * <p/>// w w  w  .  j  a  va 2s.c o m
 * <p/>
 * The underlying type of the JAXB object element returned by this method will correspond
 * to the JAXB object(s) referenced by the package namespace provided in the parameter list.
 * <p/>
 * <p/>
 * If the <code>filterMetaDataNamespaces</code> parameter is set to true, this method will use
 * the {@link MetaDataXMLNamespaceFilter} to filter the namespace URI of specific meta-data
 * elements during unmarshalling that correspond to the TCGA_BCR.Metadata XSD.
 * <p/>
 * <p/>
 * If the <code>validate</code> parameter is set to true, schema validation will be performed.
 * <p/>
 * <p/>
 * If both <code>filterMetaDataNamespaces</code> and <code>validate</code> are set to true,
 * only the meta-data elements will go through schema validation.
 *
 * @param xmlFile                  - a {@link File} object representing the XML file to unmarshalled
 * @param jaxbPackageName          - a string that represents package namespace of the JAXB context objects
 * @param filterMetaDataNamespaces - boolean that specifies whether or not to filter meta-data
 *                                 namespace URIs using the {@link MetaDataXMLNamespaceFilter}
 * @param validate                 - boolean indicating weather or not the XML should be validated against a schema
 * @return - an instance of {@link UnmarshalResult} representing the result of the unmarhsalling
 * @throws UnmarshalException if an error occurs during unmarshalling
 */
public static UnmarshalResult unmarshal(final File xmlFile, final String jaxbPackageName,
        final boolean filterMetaDataNamespaces, final boolean validate) throws UnmarshalException {

    Object jaxbObject = null;
    ValidationEventCollector validationEventCollector = (validate ? new ValidationEventCollector() : null);
    JAXBContext jaxbContext;
    Unmarshaller unmarshaller;

    if (xmlFile != null && jaxbPackageName != null) {
        FileReader xmlFileReader = null;
        try {
            // Get the JAXB context using the package name and create an unmarshaller
            jaxbContext = JAXBContext.newInstance(jaxbPackageName);
            unmarshaller = jaxbContext.createUnmarshaller();
            xmlFileReader = new FileReader(xmlFile);

            // Unmarshal the XML file
            if (filterMetaDataNamespaces) {
                final SAXSource source = applyMetaDataNamespaceFilter(unmarshaller, xmlFileReader);
                jaxbObject = unmarshaller.unmarshal(source);

                // Perform schema validation meta-data elements only
                if (validate) {
                    final String metaDataXML = getMetaDataXMLAsString(jaxbContext, jaxbObject);
                    jaxbObject = validate(unmarshaller, validationEventCollector, new StringReader(metaDataXML),
                            true);
                }
            } else {

                // Perform schema validation of all XML elements
                if (validate) {
                    jaxbObject = validate(unmarshaller, validationEventCollector, xmlFileReader, false);
                } else {
                    jaxbObject = unmarshaller.unmarshal(xmlFile);
                }
            }
        } catch (Exception e) {
            throw new UnmarshalException(e);
        } finally {
            IOUtils.closeQuietly(xmlFileReader);
        }
    } else {
        throw new UnmarshalException(new StringBuilder()
                .append("Unmarshalling failed because either the XML file '").append(xmlFile)
                .append("' or package namespace '").append(jaxbPackageName).append("' was null").toString());
    }

    // Return the result of the unmarshalling
    if (validationEventCollector != null) {
        return new UnmarshalResult(jaxbObject, Arrays.asList(validationEventCollector.getEvents()));
    } else {
        return new UnmarshalResult(jaxbObject, new ArrayList<ValidationEvent>());
    }
}

From source file:org.rhq.core.clientapi.descriptor.AgentPluginDescriptorUtil.java

private static void logValidationEvents(URL pluginJarFileUrl, ValidationEventCollector validationEventCollector,
        Log logger) {/*from  w w  w . j a va  2  s  .co m*/
    for (ValidationEvent event : validationEventCollector.getEvents()) {
        // First build the message to be logged. The message will look something like this:
        //
        //   Validation fatal error while parsing [jopr-jboss-as-plugin-4.3.0-SNAPSHOT.jar:META-INF/rhq-plugin.xml]
        //   at line 221, column 94: cvc-minInclusive-valid: Value '20000' is not facet-valid with respect to
        //   minInclusive '30000' for type '#AnonType_defaultIntervalmetric'.
        //
        StringBuilder message = new StringBuilder();
        String severity = null;
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
            severity = "warning";
            break;
        case ValidationEvent.ERROR:
            severity = "error";
            break;
        case ValidationEvent.FATAL_ERROR:
            severity = "fatal error";
            break;
        }
        message.append("Validation ").append(severity);
        File pluginJarFile = new File(pluginJarFileUrl.getPath());
        message.append(" while parsing [").append(pluginJarFile.getName()).append(":")
                .append(PLUGIN_DESCRIPTOR_PATH).append("]");
        ValidationEventLocator locator = event.getLocator();
        message.append(" at line ").append(locator.getLineNumber());
        message.append(", column ").append(locator.getColumnNumber());
        message.append(": ").append(event.getMessage());

        // Now write the message to the log at an appropriate level.
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
        case ValidationEvent.ERROR:
            logger.warn(message);
            break;
        case ValidationEvent.FATAL_ERROR:
            logger.error(message);
            break;
        }
    }
}

From source file:org.rhq.enterprise.server.plugins.url.XmlIndexParser.java

@SuppressWarnings("unchecked")
protected Map<String, RemotePackageInfo> jaxbParse(InputStream indexStream, URL indexUrl, String rootUrlString)
        throws Exception {

    JAXBContext jaxbContext = JAXBContext.newInstance(XmlSchemas.PKG_CONTENTSOURCE_PACKAGEDETAILS);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    // Enable schema validation
    URL pluginSchemaURL = XmlIndexParser.class.getClassLoader().getResource(PLUGIN_SCHEMA_PATH);
    Schema pluginSchema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
            .newSchema(pluginSchemaURL);
    unmarshaller.setSchema(pluginSchema);

    ValidationEventCollector vec = new ValidationEventCollector();
    unmarshaller.setEventHandler(vec);// w w  w .  j av a  2 s  .  com

    BufferedReader reader = new BufferedReader(new InputStreamReader(indexStream));
    JAXBElement<PackageType> packagesXml = (JAXBElement<PackageType>) unmarshaller.unmarshal(reader);

    for (ValidationEvent event : vec.getEvents()) {
        log.debug("URL content source index [" + indexUrl + "] message {Severity: " + event.getSeverity()
                + ", Message: " + event.getMessage() + ", Exception: " + event.getLinkedException() + "}");
    }

    Map<String, RemotePackageInfo> fileList = new HashMap<String, RemotePackageInfo>();

    List<PackageDetailsType> allPackages = packagesXml.getValue().getPackage();
    for (PackageDetailsType pkg : allPackages) {
        URL locationUrl = new URL(rootUrlString + pkg.getLocation());
        ContentProviderPackageDetails details = translateXmlToDomain(pkg);
        FullRemotePackageInfo rpi = new FullRemotePackageInfo(locationUrl, details);
        fileList.put(stripLeadingSlash(rpi.getLocation()), rpi);
    }

    return fileList;
}

From source file:org.rhq.enterprise.server.xmlschema.ServerPluginDescriptorUtil.java

private static void logValidationEvents(URL pluginJarFileUrl,
        ValidationEventCollector validationEventCollector) {
    for (ValidationEvent event : validationEventCollector.getEvents()) {
        // First build the message to be logged. The message will look something like this:
        //// w ww . ja  va2s  .co m
        //   Validation fatal error while parsing [jopr-jboss-as-plugin-4.3.0-SNAPSHOT.jar:META-INF/rhq-plugin.xml]
        //   at line 221, column 94: cvc-minInclusive-valid: Value '20000' is not facet-valid with respect to
        //   minInclusive '30000' for type '#AnonType_defaultIntervalmetric'.
        //
        StringBuilder message = new StringBuilder();
        String severity = null;
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
            severity = "warning";
            break;
        case ValidationEvent.ERROR:
            severity = "error";
            break;
        case ValidationEvent.FATAL_ERROR:
            severity = "fatal error";
            break;
        }
        message.append("Validation ").append(severity);
        File pluginJarFile = new File(pluginJarFileUrl.getPath());
        message.append(" while parsing [").append(pluginJarFile.getName()).append(":")
                .append(PLUGIN_DESCRIPTOR_PATH).append("]");
        ValidationEventLocator locator = event.getLocator();
        message.append(" at line ").append(locator.getLineNumber());
        message.append(", column ").append(locator.getColumnNumber());
        message.append(": ").append(event.getMessage());

        // Now write the message to the log at an appropriate level.
        switch (event.getSeverity()) {
        case ValidationEvent.WARNING:
        case ValidationEvent.ERROR:
            LOG.warn(message);
            break;
        case ValidationEvent.FATAL_ERROR:
            LOG.error(message);
            break;
        }
    }
}