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:cz.cas.lib.proarc.common.export.desa.DesaServices.java

private Nomenclatures getNomenclaturesCache(DesaConfiguration dc, UserProfile user) {
    File tmpFolder = FileUtils.getTempDirectory();
    File cache = null;//  ww w  .  jav  a 2s . c  o m
    String operator = getOperatorName(user, dc);
    if (operator == null || operator.isEmpty()) {
        throw new IllegalStateException("Missing operator! id: " + dc.getServiceId() + ", user: "
                + (user == null ? null : user.getUserName()));
    }
    long expiration = dc.getNomenclatureExpiration();
    if (expiration != 0) {
        synchronized (DesaServices.this) {
            // ensure the filename is platform safe and unique for each operator
            String codeAsFilename = String.valueOf(operator.hashCode() & 0x00000000ffffffffL);
            cache = new File(tmpFolder,
                    String.format("%s.%s.nomenclatures.cache", dc.getServiceId(), codeAsFilename));
            if (cache.exists()
                    && (expiration < 0 || System.currentTimeMillis() - cache.lastModified() < expiration)) {
                return JAXB.unmarshal(cache, Nomenclatures.class);
            }
        }
    }
    String producerCode = getProducerCode(user, dc);
    if (producerCode == null || producerCode.isEmpty()) {
        throw new IllegalStateException("Missing producer code! id: " + dc.getServiceId() + ", user: "
                + (user == null ? null : user.getUserName()));
    }
    DesaClient desaClient = getDesaClient(dc);
    Nomenclatures nomenclatures = desaClient.getNomenclatures(operator, producerCode,
            dc.getNomenclatureAcronyms());
    if (cache != null) {
        synchronized (DesaServices.this) {
            JAXB.marshal(nomenclatures, cache);
        }
    }
    return nomenclatures;
}

From source file:es.usc.citius.composit.transformer.wsc.wscxml.WSCTransformer.java

public List<Service> transform(InputStream originalDescription, URL modelReferenceOntoUrl,
        InstanceResolver resolver) throws URISyntaxException {
    // De-serialize from XML
    XMLServices services = JAXB.unmarshal(originalDescription, XMLServices.class);
    List<Service> listServices = new ArrayList<Service>(services.getServices().size());

    // Create service models
    for (XMLService service : services.getServices()) {
        URI srvURI = URI.create(fakeURL + "#" + service.getName());
        URI opURI = URI.create(fakeURL + "/" + service.getName() + "#Operation");
        log.debug("Transforming service (Fake OWL URI: {})", srvURI);
        Service modelService = new Service(srvURI);

        // Create only one hasInput and hasOutput and mandatory parts for each input/output
        Operation operation = new Operation(opURI);

        // The modelReferenceOntoUrl must point to a valid url where the original ontology is
        operation.addInput(generateMessageContent(service.getInputs().getInstances(), "input",
                modelReferenceOntoUrl, resolver));
        operation.addOutput(generateMessageContent(service.getOutputs().getInstances(), "output",
                modelReferenceOntoUrl, resolver));
        operation.setLabel(service.getName() + "_op");

        modelService.addOperation(operation);
        modelService.setLabel(service.getName());
        listServices.add(modelService);// w w  w.j a  va2s.  c  o m
    }
    return listServices;
}

From source file:it.geosolutions.unredd.stats.model.config.ConfigTest.java

public void testRunClassWithRanges() throws IOException {

    File file = ctx.getResource("classpath:classStatWithRanges.xml").getFile();
    assertNotNull("test file not found", file);

    StatisticConfiguration cfg = JAXB.unmarshal(file, StatisticConfiguration.class);
    assertNotNull("Error unmarshalling file", cfg);

    int exludeNull = 0;
    int exludeTrue = 0;
    int exludeFalse = 0;
    int rangesNotNull = 0;
    //check if the ranges has been loaded correctly
    for (int i = 0; i < 2; i++) {
        List<Range> rlist = cfg.getClassifications().get(i).getRanges();
        if (rlist.size() == 4) {
            for (Range r : rlist) {
                if (r.getRange() != null) {
                    rangesNotNull++;/*from w w  w . ja  v a  2 s .c o m*/
                }
                if (r.getIsAnExcludeRange() == null) {
                    exludeNull++;
                    continue;
                }
                if (r.getIsAnExcludeRange()) {
                    exludeTrue++;
                }
                if (!r.getIsAnExcludeRange()) {
                    exludeFalse++;
                }
            }
        }
    }
    if (!(exludeNull == 2 && exludeTrue == 1 && exludeFalse == 1 && rangesNotNull == 4)) {
        fail("The range loaded seems differents as expected...");
    }
    boolean check = StatisticChecker.check(cfg);
    assertTrue("Configuration is not valid", check);
}

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

private static boolean isSoapValidDirectAddressBlock(String soap) {
    Envelope env = (Envelope) JAXB.unmarshal(new StringReader(soap), Envelope.class);
    List<Object> headers = env.getHeader().getAny();
    if (headers == null) {
        return false;
    }/*from  w w  w  . j  a v  a2  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);
            if (directFrom.getLength() > 0 && directTo.getLength() > 0) {
                return true;
            } else {
                return false;
            }
        }
    }
    return false;

}

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

@Test
public void InquiryREST_GET_TModel() throws Exception {
    Assume.assumeTrue(TckPublisher.isEnabled());
    Assume.assumeTrue(TckPublisher.isInquiryRestEnabled());
    FindTModel fb = new FindTModel();
    fb.setMaxRows(1);/*from www  . j  a v  a 2  s  . c o  m*/
    fb.setName(new Name(UDDIConstants.WILDCARD, null));
    fb.setFindQualifiers(new FindQualifiers());
    fb.getFindQualifiers().getFindQualifier().add(UDDIConstants.APPROXIMATE_MATCH);
    TModelList findTModel = inquiry.findTModel(fb);
    Assume.assumeTrue(findTModel != null);
    Assume.assumeTrue(findTModel.getTModelInfos() != null);
    Assume.assumeTrue(!findTModel.getTModelInfos().getTModelInfo().isEmpty());

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

    Assume.assumeNotNull(url);

    HttpClient client = new DefaultHttpClient();

    HttpGet httpGet = new HttpGet(
            url + "?tModelKey=" + findTModel.getTModelInfos().getTModelInfo().get(0).getTModelKey());
    logger.info("Fetching " + httpGet.getURI());
    HttpResponse response = client.execute(httpGet);

    Assert.assertTrue(response.getStatusLine().getStatusCode() == 200);
    logger.info("Response content: " + response.getEntity().getContent());
    TModel unmarshal = JAXB.unmarshal(response.getEntity().getContent(), TModel.class);
    client.getConnectionManager().shutdown();
    Assert.assertNotNull(unmarshal);
    Assert.assertEquals(unmarshal.getTModelKey(),
            findTModel.getTModelInfos().getTModelInfo().get(0).getTModelKey());

}

From source file:at.ac.univie.isc.asio.engine.sql.JooqEngineTest.java

@Test
public void update_to_xml() throws Exception {
    final Command params = CommandBuilder.empty().language(Language.SQL)
            .single(JooqEngine.PARAM_UPDATE, REFERENCE_UPDATE).accept(SQL_RESULTS_TYPE).build();
    final byte[] bytes = performInvocationWith(params);
    final SqlResult results = JAXB.unmarshal(new ByteArrayInputStream(bytes), SqlResult.class);
    assertThat(results.getHead().getStatement(), is(REFERENCE_UPDATE));
    assertThat(results.getUpdate().getAffected(), is(1L));
}

From source file:net.sourceforge.mavenhippo.gen.BeanGeneratorTest.java

private ContentTypeBean getContentTypeBean(String fileName) {
    Node node = JAXB.unmarshal(ClassLoader.getSystemResourceAsStream(fileName), Node.class);
    @SuppressWarnings("unchecked")
    ContentTypeBean contentTypeBean = new ContentTypeBean(node, ((BidiMap) namespaces).inverseBidiMap());
    return contentTypeBean;
}

From source file:com.fujitsu.dc.test.jersey.box.ServiceSchmaTest.java

() {
    try {//from   ww  w.  j av  a2s.c  om
        Setup.deleteUserDatas(Setup.TEST_CELL1);
        Setup.deleteTestCollectionSchema(Setup.TEST_CELL1);
        Setup.deleteMaxPropTestCollectionSchema(Setup.TEST_CELL1);

        Setup.createTestCollectionSchema(Setup.TEST_CELL1);

        TResponse res = Http.request("box/$metadata-$metadata-get.txt")
                .with("path", "\\$metadata")
                .with("col", "setodata")
                .with("accept", "application/xml")
                .with("token", DcCoreConfig.getMasterToken())
                .returns()
                .statusCode(HttpStatus.SC_OK)
                .debug();

        // ???
        String str = res.getBody();
        String regex = "Namespace=\"(UserData)\">";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        matcher.find();
        String namespace = matcher.group(1);

        Edmx edmx = JAXB.unmarshal(new StringReader(str), Edmx.class);
        Edmx checkBody = getUserSchemaRightEdmx(namespace);
        assertTrue(checkBody.equals(edmx));

    } finally {
        Setup.createMaxPropTestCollectionSchema(Setup.TEST_CELL1);
        Setup.createUserDatas(Setup.TEST_CELL1);
    }
}

From source file:io.personium.test.jersey.box.ServiceSchmaTest.java

() {
    try {/*from   w  w w .  j  a  v  a 2 s  .  c om*/
        Setup.deleteUserDatas(Setup.TEST_CELL1);
        Setup.deleteTestCollectionSchema(Setup.TEST_CELL1);
        Setup.deleteMaxPropTestCollectionSchema(Setup.TEST_CELL1);

        Setup.createTestCollectionSchema(Setup.TEST_CELL1);

        TResponse res = Http.request("box/$metadata-$metadata-get.txt")
                .with("path", "\\$metadata")
                .with("col", "setodata")
                .with("accept", "application/xml")
                .with("token", PersoniumUnitConfig.getMasterToken())
                .returns()
                .statusCode(HttpStatus.SC_OK)
                .debug();

        // ???
        String str = res.getBody();
        String regex = "Namespace=\"(UserData)\">";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        matcher.find();
        String namespace = matcher.group(1);

        Edmx edmx = JAXB.unmarshal(new StringReader(str), Edmx.class);
        Edmx checkBody = getUserSchemaRightEdmx(namespace);
        assertTrue(checkBody.equals(edmx));

    } finally {
        Setup.createMaxPropTestCollectionSchema(Setup.TEST_CELL1);
        Setup.createUserDatas(Setup.TEST_CELL1);
    }
}

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

@Test
public void testXmlRead() 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  ww  w.  j  a v a2  s .c om
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);
    assertEquals(content, resultContent);
    long lastModified = editor.getLastModified();
    assertTrue(String.valueOf(lastModified), lastModified != 0 && lastModified < System.currentTimeMillis());
    assertEquals(format, editor.getProfile().getDsFormatURI());
}