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:org.eclipsetrader.internal.brokers.paper.PaperBroker.java

public void load(File file) throws JAXBException {
    if (!file.exists()) {
        return;/*from   ww  w  . j  a va 2  s . c o  m*/
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(OrderMonitor[].class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    unmarshaller.setEventHandler(new ValidationEventHandler() {

        @Override
        public boolean handleEvent(ValidationEvent event) {
            Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0,
                    "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
            Activator.log(status);
            return true;
        }
    });
    JAXBElement<OrderMonitor[]> element = unmarshaller.unmarshal(new StreamSource(file), OrderMonitor[].class);
    if (element != null) {
        Calendar today = Calendar.getInstance();
        Calendar order = Calendar.getInstance();
        for (OrderMonitor monitor : element.getValue()) {
            order.setTime(monitor.getOrder().getDate());
            if (order.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
                pendingOrders.add(monitor);
            }
        }
    }
}

From source file:org.eclipsetrader.news.internal.connectors.RSSNewsProvider.java

protected FeedSource[] getActiveSubscriptions() {
    List<FeedSource> list = new ArrayList<FeedSource>();

    try {//from   w w w .j  ava  2 s  . com
        File file = Activator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
        if (file.exists()) {
            JAXBContext jaxbContext = JAXBContext.newInstance(FeedSource[].class);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            unmarshaller.setEventHandler(new ValidationEventHandler() {

                @Override
                public boolean handleEvent(ValidationEvent event) {
                    Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0,
                            "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
                    Activator.getDefault().getLog().log(status);
                    return true;
                }
            });
            JAXBElement<FeedSource[]> element = unmarshaller.unmarshal(new StreamSource(file),
                    FeedSource[].class);
            for (FeedSource source : element.getValue()) {
                if (source.isEnabled()) {
                    list.add(source);
                }
            }
        }
    } catch (Exception e) {
        Status status = new Status(IStatus.WARNING, Activator.PLUGIN_ID, 0, "Error reading RSS subscriptions", //$NON-NLS-1$
                null);
        Activator.getDefault().getLog().log(status);
    }

    return list.toArray(new FeedSource[list.size()]);
}

From source file:org.eclipsetrader.yahoo.internal.news.NewsProvider.java

public void startUp() throws JAXBException {
    File file = YahooActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(new ValidationEventHandler() {

            @Override//from ww w  . jav a2  s  . co  m
            public boolean handleEvent(ValidationEvent event) {
                Status status = new Status(IStatus.WARNING, YahooActivator.PLUGIN_ID, 0,
                        "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
                YahooActivator.getDefault().getLog().log(status);
                return true;
            }
        });
        JAXBElement<HeadLine[]> element = unmarshaller.unmarshal(new StreamSource(file), HeadLine[].class);
        oldItems.addAll(Arrays.asList(element.getValue()));

        Date limitDate = getLimitDate();
        for (Iterator<HeadLine> iter = oldItems.iterator(); iter.hasNext();) {
            if (iter.next().getDate().before(limitDate)) {
                iter.remove();
            }
        }

        int hoursAsRecent = YahooActivator.getDefault().getPreferenceStore()
                .getInt(YahooActivator.PREFS_HOURS_AS_RECENT);

        Calendar today = Calendar.getInstance();
        today.add(Calendar.HOUR_OF_DAY, -hoursAsRecent);
        Date recentLimitDate = today.getTime();

        for (HeadLine headLine : oldItems) {
            if (!headLine.getDate().before(recentLimitDate)) {
                headLine.setRecent(true);
            }
        }
    }
}

From source file:org.eclipsetrader.yahoojapan.internal.news.NewsProvider.java

public void startUp() throws JAXBException {
    File file = YahooJapanActivator.getDefault().getStateLocation().append(HEADLINES_FILE).toFile();
    if (file.exists()) {
        JAXBContext jaxbContext = JAXBContext.newInstance(HeadLine[].class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        unmarshaller.setEventHandler(new ValidationEventHandler() {

            @Override//w w w.  ja  v  a2s .  c  om
            public boolean handleEvent(ValidationEvent event) {
                Status status = new Status(IStatus.WARNING, YahooJapanActivator.PLUGIN_ID, 0,
                        "Error validating XML: " + event.getMessage(), null); //$NON-NLS-1$
                YahooJapanActivator.getDefault().getLog().log(status);
                return true;
            }
        });
        JAXBElement<HeadLine[]> element = unmarshaller.unmarshal(new StreamSource(file), HeadLine[].class);
        oldItems.addAll(Arrays.asList(element.getValue()));

        Date limitDate = getLimitDate();
        for (Iterator<HeadLine> iter = oldItems.iterator(); iter.hasNext();) {
            if (iter.next().getDate().before(limitDate)) {
                iter.remove();
            }
        }

        int hoursAsRecent = YahooJapanActivator.getDefault().getPreferenceStore()
                .getInt(YahooJapanActivator.PREFS_HOURS_AS_RECENT);

        Calendar today = Calendar.getInstance();
        today.add(Calendar.HOUR_OF_DAY, -hoursAsRecent);
        Date recentLimitDate = today.getTime();

        for (HeadLine headLine : oldItems) {
            if (!headLine.getDate().before(recentLimitDate)) {
                headLine.setRecent(true);
            }
        }
    }
}

From source file:org.eobjects.analyzer.configuration.JaxbConfigurationReader.java

/**
 * Convenience method to get the untouched JAXB configuration object from an
 * inputstream.//from  www.j  av a2  s. c  o m
 * 
 * @param inputStream
 * @return
 */
public Configuration unmarshall(InputStream inputStream) {
    try {
        Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();

        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
        Configuration configuration = (Configuration) unmarshaller.unmarshal(inputStream);
        return configuration;
    } catch (JAXBException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.eobjects.analyzer.job.JaxbJobReader.java

private Job unmarshallJob(InputStream inputStream) {
    try {/*from w ww.  ja va 2s . com*/
        Unmarshaller unmarshaller = _jaxbContext.createUnmarshaller();

        unmarshaller.setEventHandler(new JaxbValidationEventHandler());
        Job job = (Job) unmarshaller.unmarshal(inputStream);
        return job;
    } catch (JAXBException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.fuin.units4j.Units4JUtils.java

/**
 * Unmarshals the given data using a given context. A <code>null</code> XML
 * data argument returns <code>null</code>.
 * /*from   w  w  w  .  j  ava 2s.co  m*/
 * @param ctx
 *            Context to use.
 * @param xmlData
 *            XML data or <code>null</code>.
 * @param adapters
 *            Adapters to associate with the unmarshaller or
 *            <code>null</code>.
 * 
 * @return Data or <code>null</code>.
 * 
 * @param <T>
 *            Type of the expected data.
 */
@SuppressWarnings("unchecked")
public static <T> T unmarshal(@NotNull final JAXBContext ctx, final String xmlData,
        final XmlAdapter<?, ?>[] adapters) {
    if (xmlData == null) {
        return null;
    }
    try {
        final Unmarshaller unmarshaller = ctx.createUnmarshaller();
        if (adapters != null) {
            for (XmlAdapter<?, ?> adapter : adapters) {
                unmarshaller.setAdapter(adapter);
            }
        }
        unmarshaller.setEventHandler(new ValidationEventHandler() {
            @Override
            public boolean handleEvent(final ValidationEvent event) {
                if (event.getSeverity() > 0) {
                    if (event.getLinkedException() == null) {
                        throw new RuntimeException("Error unmarshalling the data: " + event.getMessage());
                    }
                    throw new RuntimeException("Error unmarshalling the data", event.getLinkedException());
                }
                return true;
            }
        });
        return (T) unmarshaller.unmarshal(new StringReader(xmlData));
    } catch (final JAXBException ex) {
        throw new RuntimeException("Error unmarshalling test data", ex);
    }
}

From source file:org.jvnet.hyperjaxb3.samples.pows.common.BindingUtility.java

public static 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;
        }/*from   w ww .j a va  2 s .co m*/
    });

    return unmarshaller;
}

From source file:org.multicore_association.measure.mem.generate.MemCodeGen.java

/**
 * Get the data which need to make CSource from SHIM file.
 * @return Flag for success judgements//from   w w  w . j a v  a 2s .  c o m
 */
private boolean getDataFromShim() {
    boolean ch = true;

    try {
        JAXBContext context = JAXBContext.newInstance(PACKAGENAME);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }

        //         JAXBElement<SystemConfiguration> root = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class);
        //         sysConf = root.getValue();
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    ch = makeCPUListFromShim();
    if (!ch) {
        return ch;
    }
    ch = makeSlaveListFromShim();
    if (!ch) {
        return ch;
    }

    ch = makeAddressSpaceListFromShim();
    if (!ch) {
        return ch;
    }

    ch = makeAccessPatternListFromShim();
    if (!ch) {
        return ch;
    }

    return ch;
}

From source file:org.multicore_association.measure.mem.writeback.SetResultToShim.java

/**
 * Set the value to read the existing SHIM file.
 * @return Flag for success judgements// ww  w.  j av  a 2 s .co  m
 * @throws ShimFileFormatException
 * @throws ShimFileGenerateException
 */
private static boolean appendToExistingShim() {
    /*
     * append to existing llvm-shim
     */
    SystemConfiguration sysConf = null;

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();

        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            unmarshaller.setSchema(schema);
            unmarshaller.setEventHandler(new ValidationEventHandler() {
                @Override
                public boolean handleEvent(ValidationEvent event) {
                    if ((event.getSeverity() == ValidationEvent.FATAL_ERROR)
                            || (event.getSeverity() == ValidationEvent.ERROR)) {
                        ValidationEventLocator loc = event.getLocator();
                        parseErrList.add("    Line[" + loc.getLineNumber() + "] : " + event.getMessage());
                    }
                    return true;
                }
            });
        }

        sysConf = unmarshaller.unmarshal(new StreamSource(shimf), SystemConfiguration.class).getValue();

        if (parseErrList.size() > 0) {
            System.err.println("Error: input SHIM file validation error");

            System.err.println("    Validation error location:");
            for (int i = 0; i < parseErrList.size(); i++) {
                System.err.println(parseErrList.get(i));
            }
            return false;
        }
    } catch (Exception e) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        e.printStackTrace();
        return false;
    }

    AddressSpaceSet addrSpaceSet = sysConf.getAddressSpaceSet();
    if (addrSpaceSet == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    List<AddressSpace> addrSpaceList = addrSpaceSet.getAddressSpace();
    if (addrSpaceList == null) {
        System.err.println("Error: failed to parse the SHIM file, please check the contents of the file");
        return false;
    }

    masterComponentMap = new HashMap<String, MasterComponent>();
    slaveComponentMap = new HashMap<String, SlaveComponent>();
    accessTypeMap = new HashMap<String, AccessType>();

    List<String> route = new ArrayList<String>();
    ComponentSet cs = sysConf.getComponentSet();
    route.add(cs.getName());

    makeRefMapFromComponentSet(cs, route);

    for (int i = 0; i < measureList.size(); i++) {
        MeasurementsCSVData data = measureList.get(i);

        route.clear();

        /*
         * search AddressSpaceName
         */
        AddressSpace addrSp = null;
        for (Iterator<AddressSpace> j = addrSpaceList.iterator(); j.hasNext();) {
            AddressSpace as = j.next();

            if (as.getName() != null && as.getName().equals(data.getAddressSpaceName())) {
                addrSp = as;
                break;
            }
        }
        if (addrSp == null) {
            System.err.println("Error: Unknown 'Address Space' name (\"" + data.getAddressSpaceName() + "\").");
            return false;
        }

        route.add(addrSp.getName());

        /*
         * search SubSpaceName
         */
        SubSpace subSp = null;
        List<SubSpace> ssList = addrSp.getSubSpace();
        for (Iterator<SubSpace> j = ssList.iterator(); j.hasNext();) {
            SubSpace ss = j.next();

            route.add(ss.getName());
            String path = createPathName(route);
            route.remove(ss.getName());
            if (path != null && path.equals(data.getSubSpaceName())) {
                subSp = ss;
                break;
            }

        }
        if (subSp == null) {
            System.err.println("Error: Unknown 'Sub Space' name (\"" + data.getSubSpaceName() + "\").");
            return false;
        }

        /*
         * search SlaveComponentRef in MasterSlaveBinding
         */
        MasterSlaveBindingSet msBindSet = null;
        msBindSet = subSp.getMasterSlaveBindingSet();
        if (msBindSet == null) {
            continue;
        }

        MasterSlaveBinding msBind = null;
        List<MasterSlaveBinding> msBindList = msBindSet.getMasterSlaveBinding();
        SlaveComponent scComp = slaveComponentMap.get(data.getSlaveComponentName());
        if (scComp == null) {
            System.err.println(
                    "Error: Unknown 'Slave Comonent' name (\"" + data.getSlaveComponentName() + "\").");
            return false;
        }
        for (Iterator<MasterSlaveBinding> j = msBindList.iterator(); j.hasNext();) {
            MasterSlaveBinding msb = j.next();
            SlaveComponent sca = (SlaveComponent) msb.getSlaveComponentRef();

            if (sca != null && sca.getId().equals(scComp.getId())) {
                msBind = msb;
                break;
            }
        }
        if (msBind == null) {
            continue;
        }

        /*
         * search MasterComponentRef in Accessor
         */
        Accessor accessor = null;
        List<Accessor> acList = msBind.getAccessor();
        MasterComponent mcComp = masterComponentMap.get(data.getMasterComponentName());
        if (mcComp == null) {
            System.err.println(
                    "Error: Unknown 'Master Comonent' name (\"" + data.getMasterComponentName() + "\").");
            return false;
        }
        for (Iterator<Accessor> j = acList.iterator(); j.hasNext();) {
            Accessor ac = j.next();
            MasterComponent mc = (MasterComponent) ac.getMasterComponentRef();

            if (mc != null && mc.getId().equals(mcComp.getId())) {
                accessor = ac;
                break;
            }
        }
        if (accessor == null) {
            continue;
        }

        /*
         * search PerformanceSet
         */
        PerformanceSet perfrmSet = null;

        if (accessor.getPerformanceSet().size() != 0) {
            perfrmSet = accessor.getPerformanceSet().get(0);
        }
        if (perfrmSet == null) {
            continue;
        }

        /*
         * search Performance
         */
        List<Performance> pfrmList = perfrmSet.getPerformance();
        AccessType atComp = accessTypeMap.get(data.getAccessTypeName());
        if (atComp == null) {
            System.err.println("Error: Unknown 'Access Type' name (\"" + data.getAccessTypeName() + "\").");
            return false;
        }
        for (Iterator<Performance> j = pfrmList.iterator(); j.hasNext();) {
            Performance pfm = j.next();
            AccessType at = (AccessType) pfm.getAccessTypeRef();

            if (at != null && at.getId().equals(atComp.getId())) {
                Latency latency = new Latency();
                Pitch pitch = new Pitch();

                latency.setBest(data.getBestLatency());
                latency.setWorst(data.getWorstLatency());
                latency.setTypical(data.getTypicalLatency());
                pitch.setBest(data.getBestPitch());
                pitch.setWorst(data.getWorstPitch());
                pitch.setTypical(data.getTypicalPitch());

                pfm.setLatency(latency);
                pfm.setPitch(pitch);
                break;
            }
        }
    }

    try {
        JAXBContext context = JAXBContext.newInstance(SystemConfiguration.class.getPackage().getName());

        Marshaller marshaller = context.createMarshaller();
        /* validation check setup */
        if (!shimSchemaPath.equals("")) {
            SchemaFactory sf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(new File(shimSchemaPath));
            marshaller.setSchema(schema);
        }
        QName qname = new QName("", "SystemConfiguration");

        JAXBElement<SystemConfiguration> elem = new JAXBElement<SystemConfiguration>(qname,
                SystemConfiguration.class, sysConf);

        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //         marshaller.marshal(elem, new PrintStream(shimf));
        marshaller.marshal(elem, System.out);
    } catch (JAXBException e) {
        e.printStackTrace();
        System.err.println("Error: exception occurs in SHIM file generation"); //$NON-NLS-1$
        return false;
    } catch (SAXException e) {
        e.printStackTrace();
        System.err.println("Error: output SHIM file validation error"); //$NON-NLS-1$
        return false;
    }

    return true;
}