Example usage for javax.xml.bind Unmarshaller setEventHandler

List of usage examples for javax.xml.bind Unmarshaller setEventHandler

Introduction

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

Prototype

public void setEventHandler(ValidationEventHandler handler) throws JAXBException;

Source Link

Document

Allow an application to register a ValidationEventHandler .

Usage

From source file:eu.esdihumboldt.hale.io.project.jaxb.reader.ProjectParser.java

/**
 * @see AbstractIOProvider#execute(ProgressIndicator, IOReporter)
 *//*  w w  w .  ja  va  2  s.co  m*/
@Override
protected IOReport execute(ProgressIndicator progress, IOReporter reporter)
        throws IOProviderConfigurationException, IOException {
    progress.begin(Messages.ProjectParser_0, ProgressIndicator.UNKNOWN);
    try {
        File file;
        try {
            file = new File(getSource().getLocation());
        } catch (IllegalArgumentException e) {
            file = null;
        }
        String basePath = (file == null) ? (new File(".").getAbsolutePath())
                : (FilenameUtils.getFullPath(file.getAbsolutePath()));

        // Unmarshal the project file
        JAXBContext jc;
        JAXBElement<HaleProject> root;
        try {
            jc = JAXBContext.newInstance(PROJECT_CONTEXT, ObjectFactory.class.getClassLoader());
            Unmarshaller u = jc.createUnmarshaller();
            u.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
            root = u.unmarshal(new StreamSource(getSource().getInput()), HaleProject.class);
        } catch (JAXBException e) {
            reporter.error(
                    new IOMessageImpl("Unmarshalling the HaleProject from the given resource failed: {0}", e,
                            -1, -1, getSource().getLocation()));
            reporter.setSuccess(false);
            return reporter;
        }

        project = new Project();
        projectFiles = new HashMap<String, ProjectFile>();
        report = reporter;

        HaleProject haleProject = root.getValue();

        // populate project and project files
        loadProject(haleProject);
        loadSchemas(haleProject, basePath);
        loadAlignment(haleProject, basePath);
        loadStyle(haleProject, basePath);
        loadInstances(haleProject, basePath);
        loadTasks(haleProject, basePath);
        loadConfig(haleProject);

        report = null;

        reporter.setSuccess(true);
        return reporter;
    } finally {
        progress.end();
    }
}

From source file:org.anodyneos.jse.cron.CronDaemon.java

public CronDaemon(InputSource source) throws JseException {

    Schedule schedule;//from   w  ww .ja v a2s.  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");
            }
        }
    }
}

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;//  ww w .j a  v  a  2  s .  c  o 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:it.cnr.icar.eric.client.ui.common.UIUtility.java

public Object convertToRimBinding(Object uiBindingObj) throws JAXRException {
    Object rimBindingObj = null;//w w w.  ja v a 2  s  .  com
    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: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;
        }// www  . j  a  v  a  2  s .  c  om
    });

    return unmarshaller;
}

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

/**
 * Unmarshalls the Audit model from a stream.
 *//*from  ww  w.  jav a 2s  .  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.converter.OozieProcessMapper.java

@SuppressWarnings("unchecked")
protected JAXBElement<org.apache.falcon.oozie.hive.ACTION> unMarshalHiveAction(ACTION wfAction) {
    try {//from   w ww  .j a v  a  2  s. c om
        Unmarshaller unmarshaller = HIVE_ACTION_JAXB_CONTEXT.createUnmarshaller();
        unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
        return (JAXBElement<org.apache.falcon.oozie.hive.ACTION>) unmarshaller
                .unmarshal((ElementNSImpl) wfAction.getAny());
    } catch (JAXBException e) {
        throw new RuntimeException("Unable to unmarshall hive action.", 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   www  .j av  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   w w  w . jav  a2s  . co  m

    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.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

public void readMessage(InMessage message, MessageContext context) throws XFireFault {
    if (this.requestInfo == null) {
        throw new XFireFault("Unable to read message: no request info was found!", XFireFault.RECEIVER);
    }/*from w w w .  j a  v  a2 s  .  com*/

    Object bean;
    try {
        Unmarshaller unmarshaller = this.jaxbContext.createUnmarshaller();
        XMLStreamReader streamReader = message.getXMLStreamReader();
        if (this.requestInfo.isSchemaValidate()) {
            try {
                TransformerFactory xformFactory = TransformerFactory.newInstance();
                DOMResult domResult = new DOMResult();
                xformFactory.newTransformer().transform(new StAXSource(streamReader, true), domResult);
                unmarshaller.getSchema().newValidator().validate(new DOMSource(domResult.getNode()));
                streamReader = XMLInputFactory.newInstance()
                        .createXMLStreamReader(new DOMSource(domResult.getNode()));
            } catch (Exception e) {
                throw new XFireRuntimeException("Unable to validate the request against the schema.");
            }
        }
        unmarshaller.setEventHandler(getValidationEventHandler());
        unmarshaller.setAttachmentUnmarshaller(new AttachmentUnmarshaller(context));
        bean = unmarshaller.unmarshal(streamReader, this.requestInfo.getBeanClass()).getValue();
    } catch (JAXBException e) {
        throw new XFireRuntimeException("Unable to unmarshal type.", e);
    }

    List<Object> parameters = new ArrayList<Object>();
    if (this.requestInfo.isBare()) {
        //bare method, doesn't need to be unwrapped.
        parameters.add(bean);
    } else {
        for (PropertyDescriptor descriptor : this.requestInfo.getPropertyOrder()) {
            try {
                parameters.add(descriptor.getReadMethod().invoke(bean));
            } catch (IllegalAccessException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            } catch (InvocationTargetException e) {
                throw new XFireFault("Problem with property " + descriptor.getName() + " on "
                        + this.requestInfo.getBeanClass().getName() + ".", e, XFireFault.RECEIVER);
            }
        }
    }

    message.setBody(parameters);
}