Example usage for javax.xml.bind JAXBContext createUnmarshaller

List of usage examples for javax.xml.bind JAXBContext createUnmarshaller

Introduction

In this page you can find the example usage for javax.xml.bind JAXBContext createUnmarshaller.

Prototype

public abstract Unmarshaller createUnmarshaller() throws JAXBException;

Source Link

Document

Create an Unmarshaller object that can be used to convert XML data into a java content tree.

Usage

From source file:org.cbio.portal.pipelines.foundation.FoundationFileTasklet.java

/**
 * Extract the case data from source xml file by root tag
 * @param xmlFile/* w  w w .  j  a  va2  s .c  o m*/
 * @return
 * @throws JAXBException
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException 
 */
private List<CaseType> extractFileCaseData(File xmlFile)
        throws JAXBException, IOException, ParserConfigurationException, SAXException {
    List<CaseType> newCases = new ArrayList();

    // get the document root and determine how to unmarshal document
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlFile);
    Element root = document.getDocumentElement();
    if (root.getNodeName().equals("ClientCaseInfo")) {
        // unmarshal document with root tag = ClientCaseInfo
        JAXBContext context = JAXBContext.newInstance(ClientCaseInfoType.class);
        Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
        ClientCaseInfoType cci = (ClientCaseInfoType) jaxbUnmarshaller.unmarshal(root);
        newCases.addAll(cci.getCases().getCase());
    } else {
        // unmarshal document with root tag = ResultsReport
        JAXBContext context = JAXBContext.newInstance(ResultsReportType.class);
        Unmarshaller jaxbUnmarshaller = context.createUnmarshaller();
        ResultsReportType rrt = (ResultsReportType) jaxbUnmarshaller.unmarshal(root);
        newCases.add(new CaseType(rrt.getVariantReport()));
    }

    return newCases;
}

From source file:eu.over9000.skadi.io.PersistenceHandler.java

public PersistenceHandler() {
    try {/*from w  w  w . ja  va 2 s. co  m*/
        final JAXBContext context = JAXBContext.newInstance(StateContainer.class);
        this.marshaller = context.createMarshaller();
        this.unmarshaller = context.createUnmarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    } catch (final JAXBException e) {
        LOGGER.error("exception construction persistence handler", e);
    }
}

From source file:com.github.lindenb.jvarkit.tools.blast.BlastFilterJS.java

@Override
protected Collection<Throwable> call(String inputName) throws Exception {

    final CompiledScript compiledScript;
    Unmarshaller unmarshaller;/*from www  .  j a  va  2s.c  o  m*/
    Marshaller marshaller;
    try {
        compiledScript = super.compileJavascript();

        JAXBContext jc = JAXBContext.newInstance("gov.nih.nlm.ncbi.blast");

        unmarshaller = jc.createUnmarshaller();
        marshaller = jc.createMarshaller();

        XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
        xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
        xmlInputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.FALSE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PrintWriter pw = openFileOrStdoutAsPrintWriter();
        XMLOutputFactory xof = XMLOutputFactory.newFactory();
        xof.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, Boolean.FALSE);
        XMLEventWriter w = xof.createXMLEventWriter(pw);

        StreamSource src = null;
        if (inputName == null) {
            LOG.info("Reading stdin");
            src = new StreamSource(stdin());
        } else {
            LOG.info("Reading file " + inputName);
            src = new StreamSource(new File(inputName));
        }

        XMLEventReader r = xmlInputFactory.createXMLEventReader(src);

        XMLEventFactory eventFactory = XMLEventFactory.newFactory();

        SimpleBindings bindings = new SimpleBindings();
        while (r.hasNext()) {
            XMLEvent evt = r.peek();
            switch (evt.getEventType()) {
            case XMLEvent.START_ELEMENT: {
                StartElement sE = evt.asStartElement();
                Hit hit = null;
                JAXBElement<Hit> jaxbElement = null;
                if (sE.getName().getLocalPart().equals("Hit")) {
                    jaxbElement = unmarshaller.unmarshal(r, Hit.class);
                    hit = jaxbElement.getValue();
                } else {
                    w.add(r.nextEvent());
                    break;
                }

                if (hit != null) {

                    bindings.put("hit", hit);

                    boolean accept = super.evalJavaScriptBoolean(compiledScript, bindings);

                    if (accept) {
                        marshaller.marshal(jaxbElement, w);
                        w.add(eventFactory.createCharacters("\n"));
                    }
                }

                break;
            }
            case XMLEvent.SPACE:
                break;
            default: {
                w.add(r.nextEvent());
                break;
            }
            }
            r.close();
        }
        w.flush();
        w.close();
        pw.flush();
        pw.close();
        return RETURN_OK;
    } catch (Exception err) {
        return wrapException(err);
    } finally {

    }
}

From source file:com.spend.spendService.MainPage.java

private SearchEngines getSearchEnginesFromXml() {
    try {//from   ww  w.j a  v  a2s  .c o  m
        File file = new File("SearchEngines.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(SearchEngines.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        SearchEngines searchEngineList = (SearchEngines) jaxbUnmarshaller.unmarshal(file);
        return searchEngineList;

    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.fcrepo.auth.oauth.integration.api.ContainerWrapper.java

public void start() throws Exception {

    final JAXBContext context = JAXBContext.newInstance(WebAppConfig.class);
    final Unmarshaller u = context.createUnmarshaller();
    final WebAppConfig o = (WebAppConfig) u.unmarshal(getClass().getResource(this.configLocation));

    final URI uri = URI.create("http://localhost:" + port + "/");

    final Map<String, String> initParams = new HashMap<String, String>();

    server = GrizzlyWebContainerFactory.create(uri, initParams);

    // create a "root" web application
    final WebappContext wac = new WebappContext(o.displayName(), "");

    for (final ContextParam p : o.contextParams()) {
        wac.addContextInitParameter(p.name(), p.value());
    }/* www.j  av a  2s  .co m*/

    for (final Listener l : o.listeners) {
        wac.addListener(l.className());
    }

    for (final Servlet s : o.servlets) {
        final ServletRegistration servlet = wac.addServlet(s.servletName(), s.servletClass());

        final Collection<ServletMapping> mappings = o.servletMappings(s.servletName());
        for (final ServletMapping sm : mappings) {
            servlet.addMapping(sm.urlPattern());
        }
        for (final InitParam p : s.initParams()) {
            servlet.setInitParameter(p.name(), p.value());
        }
    }

    for (final Filter f : o.filters) {
        final FilterRegistration filter = wac.addFilter(f.filterName(), f.filterClass());

        final Collection<FilterMapping> mappings = o.filterMappings(f.filterName());
        for (final FilterMapping sm : mappings) {
            final String urlPattern = sm.urlPattern();
            final String servletName = sm.servletName();
            if (urlPattern != null) {
                filter.addMappingForUrlPatterns(null, urlPattern);
            } else {
                filter.addMappingForServletNames(null, servletName);
            }

        }
        for (final InitParam p : f.initParams()) {
            filter.setInitParameter(p.name(), p.value());
        }
    }

    wac.deploy(server);

    final URL webXml = this.getClass().getResource("/web.xml");
    logger.error(webXml.toString());

    logger.debug("started grizzly webserver endpoint at " + server.getHttpHandler().getName());
}

From source file:org.fcrepo.integration.auth.oauth.api.ContainerWrapper.java

public void start() throws Exception {

    final JAXBContext context = JAXBContext.newInstance(WebAppConfig.class);
    final Unmarshaller u = context.createUnmarshaller();
    final WebAppConfig o = (WebAppConfig) u.unmarshal(getClass().getResource(this.configLocation));

    final URI uri = URI.create("http://localhost:" + port + "/");

    final Map<String, String> initParams = new HashMap<>();

    server = GrizzlyWebContainerFactory.create(uri, initParams);

    // create a "root" web application
    final WebappContext wac = new WebappContext(o.displayName(), "");

    for (final ContextParam p : o.contextParams()) {
        wac.addContextInitParameter(p.name(), p.value());
    }/*  w w w.  ja  va 2  s.c  o  m*/

    for (final Listener l : o.listeners) {
        wac.addListener(l.className());
    }

    for (final Servlet s : o.servlets) {
        final ServletRegistration servlet = wac.addServlet(s.servletName(), s.servletClass());

        final Collection<ServletMapping> mappings = o.servletMappings(s.servletName());
        for (final ServletMapping sm : mappings) {
            servlet.addMapping(sm.urlPattern());
        }
        for (final InitParam p : s.initParams()) {
            servlet.setInitParameter(p.name(), p.value());
        }
    }

    for (final Filter f : o.filters) {
        final FilterRegistration filter = wac.addFilter(f.filterName(), f.filterClass());

        final Collection<FilterMapping> mappings = o.filterMappings(f.filterName());
        for (final FilterMapping sm : mappings) {
            final String urlPattern = sm.urlPattern();
            final String servletName = sm.servletName();
            if (urlPattern != null) {
                filter.addMappingForUrlPatterns(null, urlPattern);
            } else {
                filter.addMappingForServletNames(null, servletName);
            }

        }
        for (final InitParam p : f.initParams()) {
            filter.setInitParameter(p.name(), p.value());
        }
    }

    wac.deploy(server);

    final URL webXml = this.getClass().getResource("/web.xml");
    logger.error(webXml.toString());

    logger.debug("started grizzly webserver endpoint at " + server.getHttpHandler().getName());
}

From source file:org.jasig.portlet.courses.dao.xml.MockCoursesSectionDao.java

@Override
public TermList getTermList(PortletRequest request) {
    try {//from w  w w .  j a v  a 2 s .c om
        JAXBContext jaxbContext = JAXBContext.newInstance(TermsAndCourses.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        this.summary = (TermsAndCourses) unmarshaller.unmarshal(mockData.getInputStream());
    } catch (IOException e) {
        log.error("Failed to read mock data for TermList", e);
    } catch (JAXBException e) {
        log.error("Failed to unmarshall mock data for TermList", e);
    }
    return summary.getTermList();
}

From source file:com.intuit.tank.script.TankXmlUploadBean.java

public void processScript(InputStream inputStream, String fileName) throws Exception {
    try {//from  ww  w.  j a  v a  2  s  .c  o  m
        ScriptDao dao = new ScriptDao();
        JAXBContext ctx = JAXBContext.newInstance(ScriptTO.class.getPackage().getName());
        ScriptTO scriptTo = (ScriptTO) ctx.createUnmarshaller().unmarshal(inputStream);
        Script script = ScriptServiceUtil.transferObjectToScript(scriptTo);
        if (script.getId() > 0) {
            Script existing = dao.findById(script.getId());
            if (existing == null) {
                LOG.error("Error updating script: Script passed with unknown id.");
                messages.error("Script " + fileName + " passed with unknown id.");
                return;
            }
            if (!existing.getName().equals(script.getName())) {
                LOG.error("Error updating script: Cannot change the name of an existing Script.");
                messages.error("Cannot change the name of an existing script.");
                return;
            }
            if (!security.isAdmin() && !security.isOwner(script)) {
                LOG.error("Error updating script: Cannot change the name of an existing Script.");
                messages.error("You do not have rights to modify " + script.getName() + ".");
                return;
            }
        } else {
            script.setCreator(identity.getUser().getId());
        }
        script = dao.saveOrUpdate(script);
        messages.info("Script " + script.getName() + " from file " + fileName + " has been added.");
        scriptEvent.fire(new ModifiedScriptMessage(script, this));
    } catch (Exception e) {
        LOG.error("Error unmarshalling script: " + e.getMessage() + " from file " + fileName, e);
        messages.error("Error unmarshalling script: " + e.toString() + " from file " + fileName);
    }
}

From source file:org.jasig.portlet.campuslife.dao.ScreenScrapingService.java

/**
 * Deserialize a menu from the provided XML.
 * /*from w ww.  j  av a2s .  c  o m*/
 * @param xml
 * @return
 * @throws JAXBException
 */
protected T deserializeItem(String xml) throws JAXBException {

    final JAXBContext jc = JAXBContext.newInstance(getPackageName());
    final Unmarshaller u = jc.createUnmarshaller();

    @SuppressWarnings("unchecked")
    final T menu = (T) u.unmarshal(IOUtils.toInputStream(xml));
    return menu;
}

From source file:se.vgregion.domain.infrastructure.webservice.RestCalendarEventsRepository.java

private CalendarEvents extractCalendarEvents(InputStream bis) throws IOException, JAXBException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[4096];
    int n;//from  w  w  w .  j  a  va  2s  .  c om
    while ((n = bis.read(buf)) != -1) {
        baos.write(buf, 0, n);
    }

    String inUtf8 = new String(baos.toByteArray(), "UTF-8");
    String inIso8859 = new String(baos.toByteArray(), "ISO-8859-1");
    int numberSwedishCharactersFromUtf8 = StringUtils.countMatches(inUtf8, "")
            + StringUtils.countMatches(inUtf8, "") + StringUtils.countMatches(inUtf8, "");
    int numberSwedishCharactersFromIso8859 = StringUtils.countMatches(inIso8859, "")
            + StringUtils.countMatches(inIso8859, "") + StringUtils.countMatches(inIso8859, "");

    String toUse;
    if (numberSwedishCharactersFromIso8859 > numberSwedishCharactersFromUtf8) {
        toUse = inIso8859;
    } else {
        toUse = inUtf8;
    }

    JAXBContext jaxbContext = JAXBContext.newInstance(CalendarEvents.class);
    return (CalendarEvents) jaxbContext.createUnmarshaller().unmarshal(new StringReader(toUse));
}