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

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

Introduction

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

Prototype

ValidationEventCollector

Source Link

Usage

From source file:Main.java

/**
 * Unmarshal.//w w  w.jav a 2s. c  o  m
 *
 * @param inputSource the input source
 * @param clazz the clazz
 * @return the object
 * @throws JAXBException the jAXB exception
 */
public static Object unmarshal(InputSource inputSource, Class<?> clazz) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(clazz);
    Unmarshaller u = jc.createUnmarshaller();
    ValidationEventCollector vec = new ValidationEventCollector();
    u.setEventHandler(vec);
    Object o1 = u.unmarshal(inputSource);
    return o1;

}

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);//from www  .  j a v  a2  s  .  com
    }

    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 w  w . j a  v  a  2  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:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//  ww  w  .  ja va2 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:org.tellervo.desktop.wsi.JaxbResponseHandler.java

public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }/*w  w  w.ja v a  2  s  .  c o  m*/

    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }

    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    /**
     * Methodology
     * 1) Save XML to disk temporarily (it can be big, 
     *       we might want to look at it as a raw file)
     * 2) If we can't write to disk, throw IOException
     * 3) Try to parse
     * 4) Throw error with the raw document (it's malformed XML)
     */

    File tempFile = null;
    OutputStreamWriter fileOut = null;
    boolean usefulFile = false; // preserve this file outside this local context?

    try {
        tempFile = File.createTempFile("tellervo", ".xml");
        fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset);

        // ok, dump the webservice xml to a file
        BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset));

        char indata[] = new char[8192];
        int inlen;

        // write the file out
        while ((inlen = webIn.read(indata)) >= 0)
            fileOut.write(indata, 0, inlen);

        fileOut.close();
    } catch (IOException ioe) {
        // File I/O failed (?!) Clean up and re-throw the IOE.
        if (fileOut != null)
            fileOut.close();
        if (tempFile != null)
            tempFile.delete();

        throw ioe;
    }

    try {
        Unmarshaller um = context.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();

        // validate against this schema
        um.setSchema(validateSchema);

        // collect events instead of throwing exceptions
        um.setEventHandler(vec);

        // do the magic!
        Object ret = um.unmarshal(tempFile);

        // typesafe way of checking if this is the right type!
        return returnClass.cast(ret);
    } catch (UnmarshalException ume) {
        usefulFile = true;
        throw new ResponseProcessingException(ume, tempFile);

    } catch (JAXBException jaxbe) {
        usefulFile = true;
        throw new ResponseProcessingException(jaxbe, tempFile);

    } catch (ClassCastException cce) {
        usefulFile = true;
        throw new ResponseProcessingException(cce, tempFile);

    } finally {
        // clean up and delete
        if (tempFile != null) {
            if (!usefulFile)
                tempFile.delete();
            else
                tempFile.deleteOnExit();
        }
    }

    /*
    try {
       um.un
    } catch (JDOMException jdome) {
    // this document must be malformed
    usefulFile = true;
    throw new XMLParsingException(jdome, tempFile);
       } 
    } catch (IOException ioe) {
       // well, something there failed and it was lower level than just bad XML...
       if(tempFile != null) {
    usefulFile = true;
    throw new XMLParsingException(ioe, tempFile);
       }
               
       throw new XMLParsingException(ioe);
               
    } finally {
       // make sure we closed our file
       if(fileOut != null)
    fileOut.close();
               
       // make sure we delete it, too
       if(tempFile != null)
       {
    if (!usefulFile)
       tempFile.delete();
    else
       tempFile.deleteOnExit();
       }
    }
    */
}

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/>/*from w w  w .ja  va2 s  .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:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private Unmarshaller getUnmarshaller() throws JAXBException {
    JAXBContext jctx = JAXBContext.newInstance(WorkflowDefinition.class);
    Unmarshaller unmarshaller = jctx.createUnmarshaller();
    SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    URL schemaUrl = WorkflowDefinition.class.getResource("workflow.xsd");
    Schema schema = null;/*from  ww w.  jav  a 2 s .  co m*/
    try {
        schema = sf.newSchema(new StreamSource(schemaUrl.toExternalForm()));
    } catch (SAXException ex) {
        throw new JAXBException("Missing schema workflow.xsd!", ex);
    }
    unmarshaller.setSchema(schema);
    ValidationEventCollector errors = new ValidationEventCollector() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            super.handleEvent(event);
            return true;
        }

    };
    unmarshaller.setEventHandler(errors);
    return unmarshaller;
}

From source file:org.rhq.core.clientapi.agent.metadata.test.ConfigurationMetadataParser2Test.java

@BeforeSuite
public void loadPluginDescriptor() throws Exception {
    try {//from   w  w  w .  j av  a  2 s .c  om
        URL descriptorUrl = this.getClass().getClassLoader().getResource(DESCRIPTOR_FILENAME);
        LOG.info("Loading plugin descriptor at: " + descriptorUrl);

        JAXBContext jaxbContext = JAXBContext.newInstance(DescriptorPackages.PC_PLUGIN);

        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();
        unmarshaller.setEventHandler(vec);
        pluginDescriptor = (PluginDescriptor) unmarshaller.unmarshal(descriptorUrl.openStream());
    } catch (Throwable t) {
        // Catch RuntimeExceptions and Errors and dump their stack trace, because Surefire will completely swallow them
        // and throw a cryptic NPE (see http://jira.codehaus.org/browse/SUREFIRE-157)!
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}

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

/**
 * Loads a plugin descriptor from the given plugin jar and returns it.
 *
 * This is a static method to provide a convenience method for others to be able to use.
 *
 * @param pluginJarFileUrl URL to a plugin jar file
 * @return the plugin descriptor found in the given plugin jar file
 * @throws PluginContainerException if failed to find or parse a descriptor file in the plugin jar
 *///from   ww  w  .j  a  v a 2 s . c  om
public static PluginDescriptor loadPluginDescriptorFromUrl(URL pluginJarFileUrl)
        throws PluginContainerException {

    final Log logger = LogFactory.getLog(AgentPluginDescriptorUtil.class);

    if (pluginJarFileUrl == null) {
        throw new PluginContainerException("A valid plugin JAR URL must be supplied.");
    }
    logger.debug("Loading plugin descriptor from plugin jar at [" + pluginJarFileUrl + "]...");

    testPluginJarIsReadable(pluginJarFileUrl);

    JarInputStream jis = null;
    JarEntry descriptorEntry = null;
    ValidationEventCollector validationEventCollector = new ValidationEventCollector();
    try {
        jis = new JarInputStream(pluginJarFileUrl.openStream());
        JarEntry nextEntry = jis.getNextJarEntry();
        while (nextEntry != null && descriptorEntry == null) {
            if (PLUGIN_DESCRIPTOR_PATH.equals(nextEntry.getName())) {
                descriptorEntry = nextEntry;
            } else {
                jis.closeEntry();
                nextEntry = jis.getNextJarEntry();
            }
        }

        if (descriptorEntry == null) {
            throw new Exception("The plugin descriptor does not exist");
        }

        return parsePluginDescriptor(jis, validationEventCollector);
    } catch (Exception e) {
        throw new PluginContainerException(
                "Could not successfully parse the plugin descriptor [" + PLUGIN_DESCRIPTOR_PATH
                        + "] found in plugin jar at [" + pluginJarFileUrl + "].",
                new WrappedRemotingException(e));
    } finally {
        if (jis != null) {
            try {
                jis.close();
            } catch (Exception e) {
                logger.warn("Cannot close jar stream [" + pluginJarFileUrl + "]. Cause: " + e);
            }
        }

        logValidationEvents(pluginJarFileUrl, validationEventCollector, logger);
    }
}

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

/**
 * Parses a descriptor from InputStream without a validator.
 * @param is input to check//from w w w.ja  v  a  2  s.  c  o m
 * @return parsed PluginDescriptor
 * @throws PluginContainerException if validation fails
 */
public static PluginDescriptor parsePluginDescriptor(InputStream is) throws PluginContainerException {
    return parsePluginDescriptor(is, new ValidationEventCollector());
}