Example usage for javax.xml.bind Unmarshaller unmarshal

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

Introduction

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

Prototype

public Object unmarshal(javax.xml.stream.XMLEventReader reader) throws JAXBException;

Source Link

Document

Unmarshal XML data from the specified pull parser and return the resulting content tree.

Usage

From source file:org.kemri.wellcome.dhisreport.api.model.HttpDhis2Server.java

@Override
public ImportSummary postReport(DataValueSet report) throws DHIS2ReportingException {
    log.debug("Posting datavalueset report");
    ImportSummary summary = null;/*from w  w  w  .  j  av a  2 s  .c o  m*/

    StringWriter xmlReport = new StringWriter();
    try {
        JAXBContext jaxbDataValueSetContext = JAXBContext.newInstance(DataValueSet.class);
        Marshaller dataValueSetMarshaller = jaxbDataValueSetContext.createMarshaller();
        // output pretty printed
        dataValueSetMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        dataValueSetMarshaller.marshal(report, xmlReport);
    } catch (JAXBException ex) {
        log.error(ex.getMessage());
        throw new Dxf2Exception("Problem marshalling dataValueSet", ex);
    }

    String host = getUrl().getHost();
    int port = getUrl().getPort();

    HttpHost targetHost = new HttpHost(host, port, getUrl().getProtocol());
    DefaultHttpClient httpclient = new DefaultHttpClient();
    BasicHttpContext localcontext = new BasicHttpContext();

    try {
        String postUrl = getUrl().toString() + DATAVALUESET_PATH;
        log.error("Post URL: " + postUrl);
        HttpPost httpPost = new HttpPost(postUrl);
        Credentials creds = new UsernamePasswordCredentials(username, password);
        Header bs = new BasicScheme().authenticate(creds, httpPost, localcontext);
        httpPost.addHeader("Authorization", bs.getValue());
        httpPost.addHeader("Content-Type", "application/xml; charset=utf-8");
        httpPost.addHeader("Accept", "application/xml");

        httpPost.setEntity(new StringEntity(xmlReport.toString()));
        HttpResponse response = httpclient.execute(targetHost, httpPost, localcontext);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            JAXBContext jaxbImportSummaryContext = JAXBContext.newInstance(ImportSummary.class);
            Unmarshaller importSummaryUnMarshaller = jaxbImportSummaryContext.createUnmarshaller();
            summary = (ImportSummary) importSummaryUnMarshaller.unmarshal(entity.getContent());
        }
    } catch (Exception ex) {
        log.error(ex.getMessage());
        throw new Dhis2Exception(this, "Problem accessing Dhis2 server", ex);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return summary;
}

From source file:com.u2apple.tool.dao.DeviceXmlDaoJaxbImpl.java

/**
 * ?.//from   w w w  .j a va2s.c om
 *
 * @return
 * @throws ShuameException
 */
private void loadStaticMapFile() throws JAXBException {
    File file = new File(Configuration.getProperty(Constants.DEVICES_XML));
    JAXBContext jaxbContext = JAXBContext.newInstance(StaticMapFile.class);
    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    staticMapFile = (StaticMapFile) jaxbUnmarshaller.unmarshal(file);
}

From source file:eu.eexcess.zbw.recommender.PartnerConnector.java

@Override
public Document queryPartner(PartnerConfiguration partnerConfiguration, SecureUserProfile userProfile,
        PartnerdataLogger logger) throws IOException {

    // Configure//from   w w w.  ja  v a  2 s .  c  o  m
    try {
        Client client = new Client(PartnerConfigurationEnum.CONFIG.getClientJAXBContext());
        queryGenerator = PartnerConfigurationEnum.CONFIG.getQueryGenerator();

        String query = getQueryGenerator().toQuery(userProfile);
        query = query.replaceAll("\"", "");
        query = query.replaceAll("\\(", " ");
        query = query.replaceAll("\\)", " ");
        query = URLEncoder.encode(query, "UTF-8");
        Map<String, String> valuesMap = new HashMap<String, String>();
        valuesMap.put("query", query);
        if (userProfile.numResults != null)
            valuesMap.put("size", userProfile.numResults.toString());
        else
            valuesMap.put("size", "10");
        String searchRequest = StrSubstitutor.replace(partnerConfiguration.searchEndpoint, valuesMap);

        WebResource service = client.resource(searchRequest);
        log.log(Level.INFO, "SearchRequest: " + searchRequest);

        Builder builder = service.accept(MediaType.APPLICATION_XML);
        String response = builder.get(String.class);
        StringReader respStringReader = new StringReader(response);
        client.destroy();
        JAXBContext jaxbContext = JAXBContext.newInstance(ZBWDocument.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        ZBWDocument zbwResponse = (ZBWDocument) jaxbUnmarshaller.unmarshal(respStringReader);
        for (ZBWDocumentHit hit : zbwResponse.hits.hit) {
            try {
                if (hit.element.type.equals("event")) {
                    Document detail = fetchDocumentDetails(hit.element.id);
                    PartnerdataTracer.dumpFile(this.getClass(), partnerConfiguration, detail, "detail-response",
                            logger);
                    String latValue = getValueWithXPath("/doc/record/geocode/lat", detail);
                    String longValue = getValueWithXPath("/doc/record/geocode/lng", detail);
                    hit.element.lat = latValue;
                    hit.element.lng = longValue;
                }
            } catch (Exception e) {
                log.log(Level.WARNING,
                        "Could not get longitude and latitude for event element " + hit.element.id, e);
            }
            // put all creators in the creatorString
            if (hit.element.creator != null) {
                for (String creator : hit.element.creator) {
                    if (hit.element.creatorString == null)
                        hit.element.creatorString = "";
                    if (hit.element.creatorString.length() > 0)
                        hit.element.creatorString += ", ";
                    hit.element.creatorString += creator;
                }
            }
        }
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.newDocument();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.marshal(zbwResponse, document);

        return document;
    } catch (Exception e) {
        throw new IOException("Cannot query partner REST API!", e);
    }

}

From source file:eu.openminted.toolkit.elsevier.retriever.JaxbMarshalingTest.java

@Test
public void shoudDeserialise() {
    try {/*www.j  av a2s.  co m*/
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File testXml = new File("src/test/resources/S0140673616313228");
        FullTextRetrievalResponse deserialisedObject = (FullTextRetrievalResponse) unmarshaller
                .unmarshal(testXml);

        Assert.assertNotNull(deserialisedObject);
        Assert.assertEquals(deserialisedObject.getCoredata().getDc_identifier(),
                testObject.getCoredata().getDc_identifier());
        Assert.assertEquals(deserialisedObject.getCoredata().getLink(), testObject.getCoredata().getLink());
        Assert.assertEquals(deserialisedObject.getCoredata().getOpenaccess(),
                testObject.getCoredata().getOpenaccess());
        Assert.assertEquals(deserialisedObject.getCoredata().isOpenaccessArticle(),
                testObject.getCoredata().isOpenaccessArticle());

        //            Assert.assertEquals(deserialisedObject, testObject);

        System.out.println("Deserialized object :\n" + deserialisedObject.toString());
        System.out.println("\nTestObject :\n" + testObject.toString());
    } catch (JAXBException jAXBException) {
        jAXBException.printStackTrace();
    }
}

From source file:org.jasig.portlet.widget.service.GoogleGadgetService.java

public Module getModule(String url) {

    Module module = null;//  ww w .j av a  2  s  . c om

    try {

        InputStream stream = getStreamFromUrl(url);
        JAXBContext jc = JAXBContext.newInstance(Module.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        module = (Module) unmarshaller.unmarshal(stream);

    } catch (JAXBException e) {
        log.error(e);
    } catch (ClientProtocolException e) {
        log.error(e);
    } catch (IOException e) {
        log.error(e);
    }

    return module;
}

From source file:be.e_contract.mycarenet.certra.CertRAClient.java

public EHActorQualitiesDataResponse getActorQualities(byte[] signedCms) throws Exception {
    GetEHActorQualitiesRequest request = this.protocolObjectFactory.createGetEHActorQualitiesRequest();
    request.setEHActorQualitiesDataRequest(signedCms);

    GetEHActorQualitiesResponse response = this.port.getActorQualities(request);
    byte[] responseCms = response.getEHActorQualitiesDataResponse();

    byte[] responseData = getCmsData(responseCms);

    JAXBContext jaxbContext = JAXBContext
            .newInstance(be.e_contract.mycarenet.certra.cms.aqdr.ObjectFactory.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    EHActorQualitiesDataResponse ehActorQualitiesDataResponse = (EHActorQualitiesDataResponse) unmarshaller
            .unmarshal(new ByteArrayInputStream(responseData));
    return ehActorQualitiesDataResponse;
}

From source file:com.u2apple.tool.dao.DeviceXmlDaoJaxbImpl.java

private void loadVids() throws JAXBException {
    File dir = new File(Configuration.getProperty(Constants.VID_DIR));
    File[] files = dir.listFiles(new FilenameFilter() {
        @Override/*from   ww w .jav a2s. c o m*/
        public boolean accept(File dir, String name) {
            return Pattern.matches(VID_FILE_NAME_PATTERN, name);
        }
    });
    if (files != null) {
        for (File file : files) {
            JAXBContext jaxbContext = JAXBContext.newInstance(VID.class);
            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            VID vid = (VID) jaxbUnmarshaller.unmarshal(file);
            if (vid != null) {
                staticMapFile.getVids().add(vid);
            }
        }
    }
}

From source file:vitro.vgw.communication.idas.IdasProxyImpl.java

private Object sendRequest(Object request) throws VitroGatewayException {

    Object result = null;//from   w ww . j  a  v a2s.c  om

    InputStream instream = null;

    try {
        HttpPost httpPost = new HttpPost(endPoint);

        JAXBContext jaxbContext = Utils.getJAXBContext();

        Marshaller mar = jaxbContext.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        mar.marshal(request, baos);

        String requestXML = baos.toString(HTTP.UTF_8);

        StringEntity entityPar = new StringEntity(requestXML, "application/xml", HTTP.UTF_8);

        httpPost.setEntity(entityPar);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            instream = entity.getContent();

            Unmarshaller unmarshaller = Utils.getJAXBContext().createUnmarshaller();
            Object idasResponse = unmarshaller.unmarshal(instream);

            if (idasResponse instanceof ExceptionReport) {
                throw Utils.parseException((ExceptionReport) idasResponse);
            }

            result = idasResponse;

        } else {
            throw new VitroGatewayException("Server response does not contain any body");
        }
    } catch (VitroGatewayException e) {
        throw e;
    } catch (Exception e) {
        throw new VitroGatewayException(e);
    } finally {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException e) {
                logger.error("Error while closing server response stream", e);
            }
        }
    }

    return result;

}

From source file:com.aionemu.commons.scripting.scriptmanager.ScriptManager.java

/**
 * Loads script contexes from descriptor
 * /*from   ww  w.ja v  a2  s.  c  o  m*/
 * @param scriptDescriptor
 *          xml file that describes contexes
 * @throws Exception
 *           if can't load file
 */
public synchronized void load(File scriptDescriptor) throws Exception {
    FileInputStream fin = new FileInputStream(scriptDescriptor);
    JAXBContext c = JAXBContext.newInstance(ScriptInfo.class, ScriptList.class);
    Unmarshaller u = c.createUnmarshaller();

    ScriptList list = null;
    try {
        list = (ScriptList) u.unmarshal(fin);
    } catch (Exception e) {
        throw e;
    } finally {
        if (fin != null)
            fin.close();
    }

    for (ScriptInfo si : list.getScriptInfos()) {
        ScriptContext context = createContext(si, null);
        if (context != null) {
            contexts.add(context);
            context.init();
        }
    }
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

public ReportType getReportFromFile(String file) {
    try {//  w w w  . j  ava  2  s .co m
        JAXBContext jaxbContext = JAXBContext.newInstance(ReportType.class.getPackage().getName());

        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = schemaFactory.newSchema(testObj.irixSchemaFile);

        Unmarshaller u = jaxbContext.createUnmarshaller();
        u.setSchema(schema);
        JAXBElement obj = (JAXBElement) u.unmarshal(new File(file));
        return (ReportType) obj.getValue();
    } catch (JAXBException | SAXException e) {
        log.debug("Failed to parse report test data: " + file);
        log.debug(e);
        return null;
    }
}