Example usage for javax.xml.bind JAXB unmarshal

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

Introduction

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

Prototype

public static <T> T unmarshal(Source xml, Class<T> type) 

Source Link

Document

Reads in a Java object tree from the given XML input.

Usage

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static boolean isRegistryResponseSuccessFullHeaders(String mtom) throws IOException {
    String soapEnv = Parsing.findSoapOfRegistryResponse(mtom);
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soapEnv), Envelope.class);

    List<Object> body = env.getBody().getAny();
    Iterator it = body.iterator();
    if (it.hasNext()) {
        Element next = (Element) it.next();
        String regRep = MiscUtil.xmlToString(next);
        return Parsing.isRegistryResponseSuccess(regRep);
    } else {/*from  w w  w .  j  a v a  2s. c  o m*/
        return false;
    }

}

From source file:org.apache.juddi.v3.tck.UDDI_160_RESTIntergrationTest.java

@Test
public void InquiryREST_GET_Service() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());
    //find the first service via inquriy soap
    FindService fb = new FindService();
    fb.setMaxRows(1);//from   ww  w  .j av a2s . c o m
    fb.getName().add(new Name(UDDIConstants.WILDCARD, null));
    fb.setFindQualifiers(new FindQualifiers());
    fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
    ServiceList findService = inquiry.findService(fb);
    Assume.assumeTrue(findService != null);
    Assume.assumeTrue(findService.getServiceInfos() != null);
    Assume.assumeTrue(!findService.getServiceInfos().getServiceInfo().isEmpty());

    String url = manager.getClientConfig().getHomeNode().getInquiry_REST_Url();

    Assume.assumeNotNull(url);

    //get the results via inquiry rest
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(
            url + "?serviceKey=" + findService.getServiceInfos().getServiceInfo().get(0).getServiceKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    BusinessService unmarshal = JAXB.unmarshal(response.getEntity().getContent(), BusinessService.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getServiceKey(),
            findService.getServiceInfos().getServiceInfo().get(0).getServiceKey());

}

From source file:it.geosolutions.geobatch.destination.ingestion.GateIngestionProcess.java

/**
 * Imports the gate data from the exported file to database.
 * /*from w w  w.  ja v a  2 s  . c o m*/
 * @param ignorePks Flag to indicates that should ignore pks in the xml file and
 *        create a new one with a sequence manager
 * @throws IOException
 * 
 * @return resume of the operation in a map
 */
public Map<String, Object> doProcess(boolean ignorePks, boolean copyFileAtEnd, String successPath,
        String failPath) throws IOException {

    Map<String, Object> result = new HashMap<String, Object>();
    List<Long> ids = new ArrayList<Long>();
    reset();
    this.ignorePks = ignorePks;
    if (isValid()) {

        int process = -1;
        int trace = -1;
        int errors = 0;
        int total = 0;
        int processed = 0;
        float percent = 0;

        try {

            process = createProcess();

            // write log for the imported file
            trace = logFile(process, DEFAULT_GATE_TYPE, PARTNER, PARTNER_CODE, date, false);

            // Read xml file
            ExportData exportData = null;
            try {
                exportData = JAXB.unmarshal(file, ExportData.class);
            } catch (Exception e) {
                String msg = "Unknown file format for gate ingestion";
                updateProgress(90, msg);
                metadataHandler.logError(trace, errors, msg, getError(e), 0);
                throw new IOException(msg);
            }

            if (exportData != null && exportData.getTransits().size() == 1) {
                Transits transits = exportData.getTransits().get(0);
                total = transits.getTransit().size();
                float ftot = new Float(total);

                // Insert one by one
                for (Transit transit : transits.getTransit()) {
                    Long id = null;
                    try {

                        // Update status
                        inputCount++;
                        float fproc = new Float(++processed);
                        String msg = "Importing data in transit table: " + (processed) + "/" + total;
                        percent = (fproc++ / ftot);
                        if (processed % 100 == 0) {
                            updateProgress(percent * 100, msg);
                            if (LOGGER.isInfoEnabled()) {
                                LOGGER.info(msg);
                            }
                        }

                        // insert
                        id = createTransit(transit);

                        // add to result
                        if (id != null) {
                            // Trace insert
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("Correctly insert id " + id);
                            }
                            ids.add(id);
                        } else {
                            if (LOGGER.isTraceEnabled()) {
                                LOGGER.trace("Error on gate ingestion for element " + inputCount);
                            }
                        }

                    } catch (Exception e) {
                        errors++;
                        if (id != null) {
                            metadataHandler.logError(trace, errors, "Error on gate ingestion", getError(e),
                                    id.intValue());
                            /*String msg = "Error on gate ingestion for id "
                            + id.intValue();
                            updateProgress(percent * 100, msg);
                            LOGGER.error(msg);*/
                        } else {
                            metadataHandler.logError(trace, errors, "Error importing element " + inputCount,
                                    getError(e), 0);
                            /*String msg = "Error on gate ingestion for element "
                            + inputCount;
                            updateProgress(percent * 100, msg);
                            LOGGER.error(msg);*/
                        }
                    }
                }
            } else {
                LOGGER.error("Incorrect format for ingestion");
            }

            // all complete
            importFinished(total, errors, "Data imported in transit table");
            metadataHandler.updateLogFile(trace, total, errors, true);

        } catch (IOException e) {
            errors++;
            metadataHandler.logError(trace, errors, "Error importing data", getError(e), 0);

            // close current process phase
            process = closeProcess(process);

            throw e;
        } finally {
            if (process != -1) {
                // close current process phase
                metadataHandler.closeProcessPhase(process, "A");
            }

        }

        // save counts
        result.put(ERROR_COUNT, errors);
        result.put(PROCESSED_COUNT, processed);
        result.put(TOTAL_COUNT, total);

        if (copyFileAtEnd) {
            if (errors > 0) {
                copyFile(file, failPath);
            } else {
                copyFile(file, successPath);
            }
        }

        // close current process phase
        process = closeProcess(process);
    }

    // save ids
    result.put(IDS, ids);

    return result;
}

From source file:it.geosolutions.geobatch.opensdi.ndvi.NDVIStatsAction.java

/**
 * This method obtain all data for the resources configured and generate the CSV file 
 * //from w  w  w  . ja va2 s .c  o  m
 * @param file
 * 
 * @throws Exception
 */
private void processXMLFile(File file) throws Exception {

    StatsBean sb = JAXB.unmarshal(file, StatsBean.class);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Working NDVI action : " + sb.toString());
    }

    CLASSIFIER_TYPE classifier = sb.getClassifier();
    MASK_TYPE mask = sb.getForestMask();

    String ndviFileName = sb.getNdviFileName();

    SimpleFeatureCollection fc = getClassifiers(classifier, mask);

    GridCoverage2D coverage = null;
    try {
        coverage = getNdviTiff(ndviFileName);
        generateCSV(coverage, fc, classifier, mask, ndviFileName, configuration.getCsvSeparator(),
                sb.getForestMaskFullPath());
    } finally {
        if (coverage != null) {
            disposeCoverage(coverage);
        }
    }

}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

private static MetadataLevel getMetadataLevelFromSoap(String soap) {
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soap), Envelope.class);
    List<Object> headers = env.getHeader().getAny();
    if (headers == null) {
        return MetadataLevel.XDS;
    }//from ww  w. j  a va  2 s.  c  o m
    Iterator it = headers.iterator();
    while (it.hasNext()) {
        Element header = (Element) it.next();
        if (header.getLocalName().equals(ELEMENT_NAME_METADATA_LEVEL)
                && header.getNamespaceURI().equals(NAMESPACE_DIRECT)) {
            String metadataLevel = header.getFirstChild().getTextContent();
            if (metadataLevel.equals(METADATA_LEVEL_MINIMAL)) {
                return MetadataLevel.MINIMAL;
            } else if (metadataLevel.equals(METADATA_LEVEL_XDS)) {
                return MetadataLevel.XDS;
            }
        } else if (header.getLocalName().equals(ELEMENT_NAME_DIRECT_ADDRESS_BLOCK)
                && header.getNamespaceURI().equals(NAMESPACE_DIRECT)) {
            Element directAddressBlock = header;
            NodeList childrenDirectAddressBlock = directAddressBlock.getChildNodes();
            for (int i = 0; i < childrenDirectAddressBlock.getLength(); i++) {
                Element child = null;
                if (childrenDirectAddressBlock.item(i) instanceof Element) {
                    child = (Element) childrenDirectAddressBlock.item(i);
                    if (child.getLocalName().equals(ELEMENT_NAME_METADATA_LEVEL)
                            && child.getNamespaceURI().equals(NAMESPACE_DIRECT)) {
                        String metadataLevel = child.getFirstChild().getTextContent();
                        if (metadataLevel.equals(METADATA_LEVEL_MINIMAL)) {
                            return MetadataLevel.MINIMAL;
                        } else if (metadataLevel.equals(METADATA_LEVEL_XDS)) {
                            return MetadataLevel.XDS;
                        }
                    }
                }
            }
        }
    }
    return MetadataLevel.XDS;
}

From source file:org.apache.juddi.v3.tck.UDDI_160_RESTIntergrationTest.java

@Test
public void InquiryREST_GET_Binding() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());

    BindingTemplate bt = getFirstBindingTemplate();
    Assume.assumeTrue(bt != null);//ww w .ja v  a2 s.c om

    String url = manager.getClientConfig().getHomeNode().getInquiry_REST_Url();

    Assume.assumeNotNull(url);
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url + "?bindingKey=" + bt.getBindingKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    BindingTemplate unmarshal = JAXB.unmarshal(response.getEntity().getContent(), BindingTemplate.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getServiceKey(), bt.getServiceKey());
    Assert.assertEquals(unmarshal.getBindingKey(), bt.getBindingKey());

}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

public static DirectAddressing getDirectAddressing(String mtom) throws MessagingException, IOException {

    SOAPWithAttachment swa = Parsing.parseMtom(mtom);
    DirectAddressing directAddressing = new DirectAddressing();
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(swa.getSoap()), Envelope.class);
    List<Object> headers = env.getHeader().getAny();
    if (headers == null) {
        return directAddressing;
    }// ww  w  .jav  a 2 s.c  o m
    Iterator it = headers.iterator();
    boolean foundDirectAddressBlock = false;
    while (it.hasNext()) {
        Element header = (Element) it.next();
        if (header.getLocalName().equals(ELEMENT_NAME_DIRECT_ADDRESS_BLOCK)
                && header.getNamespaceURI().equals(NAMESPACE_DIRECT)) {
            foundDirectAddressBlock = true;
            NodeList directFrom = header.getElementsByTagNameNS(NAMESPACE_DIRECT, ELEMENT_NAME_DIRECT_FROM);
            NodeList directTo = header.getElementsByTagNameNS(NAMESPACE_DIRECT, ELEMENT_NAME_DIRECT_TO);

            directAddressing.setDirectFrom(directFrom.item(0).getFirstChild().getNodeValue());
            directAddressing.setDirectTo(directTo.item(0).getFirstChild().getNodeValue());
        } else if (header.getLocalName().equals(ELEMENT_NAME_WSA_MESSAGEID)
                && header.getNamespaceURI().equals(NAMESPACE_WSA)) {
            directAddressing.setMessageID(header.getFirstChild().getNodeValue());
        }
    }
    return directAddressing;
}

From source file:cz.cas.lib.proarc.common.fedora.RemoteStorageTest.java

@Test
public void testXmlWrite() throws Exception {
    String dsId = "testId";
    LocalObject local = new LocalStorage().create();
    local.setLabel(test.getMethodName());
    String format = "testns";
    XmlStreamEditor leditor = local.getEditor(FoxmlUtils.inlineProfile(dsId, format, "label"));
    EditorResult editorResult = leditor.createResult();
    TestXml content = new TestXml("test content");
    JAXB.marshal(content, editorResult);
    leditor.write(editorResult, 0, null);

    RemoteStorage fedora = new RemoteStorage(client);
    fedora.ingest(local, "junit");

    RemoteObject remote = fedora.find(local.getPid());
    RemoteXmlStreamEditor editor = new RemoteXmlStreamEditor(remote, dsId);
    Source src = editor.read();/*from  w  w w  . j  a v  a  2  s  .c o m*/
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);

    // write modification
    String expectedContent = "changed test content";
    resultContent.data = expectedContent;
    editorResult = editor.createResult();
    JAXB.marshal(resultContent, editorResult);
    long lastModified = editor.getLastModified();
    assertEquals(format, editor.getProfile().getDsFormatURI());
    editor.write(editorResult, lastModified, null);
    remote.flush();

    // test current editor
    assertTrue(lastModified < editor.getLastModified());
    long expectLastModified = editor.getLastModified();
    resultContent = JAXB.unmarshal(editor.read(), TestXml.class);
    assertEquals(new TestXml(expectedContent), resultContent);
    assertEquals(format, editor.getProfile().getDsFormatURI());

    // test new editor
    remote = fedora.find(local.getPid());
    editor = new RemoteXmlStreamEditor(remote, dsId);
    src = editor.read();
    assertNotNull(src);
    resultContent = JAXB.unmarshal(src, TestXml.class);
    assertEquals(new TestXml(expectedContent), resultContent);
    long resultLastModified = editor.getLastModified();
    assertEquals(expectLastModified, resultLastModified);
    assertEquals(format, editor.getProfile().getDsFormatURI());
}

From source file:gov.nist.healthcare.ttt.parsing.Parsing.java

private static String getDocumentFromSoap(String soap) {
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soap), Envelope.class);

    Body body = env.getBody();//  w w w  .  j av a 2s .com
    List<Object> any = body.getAny();
    Element regresp = (Element) any.get(0);

    ProvideAndRegisterDocumentSetRequestType pnr = (ProvideAndRegisterDocumentSetRequestType) JAXB.unmarshal(
            new StringReader(MiscUtil.xmlToString(regresp)), ProvideAndRegisterDocumentSetRequestType.class);
    List<Document> documents = pnr.getDocument();
    if (!documents.isEmpty()) {
        Document document = documents.get(0);
        byte[] documentByteArray = document.getValue();

        String payload = new String(documentByteArray);
        if (Parsing.isBase64Encoded(payload)) {
            return new String(Base64.getDecoder().decode(documentByteArray));
        } else {
            return payload;
        }
    }
    return null;
}