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

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

Introduction

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

Prototype

public boolean hasEvents() 

Source Link

Document

Returns true if this event collector contains at least one ValidationEvent.

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);/*from   w  ww.ja v  a2  s .c  o 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  w  w .j  a va2s .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:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfiles.java

private void read() throws JAXBException {
    long currentTime = file.lastModified();
    if (currentTime == lastModified) {
        return;/* w  w  w  .j av a2 s.co m*/
    }
    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:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;/*from  w  w w.  j  ava  2 s .c o 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");
            }
        }
    }
}