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:net.di2e.ddf.argo.probe.responder.ProbeHandler.java

@Override
public void run() {
    LOGGER.debug("Listening for any multicast packets.");
    String data = "";
    while (!isCanceled) {
        try {//from w ww.  j  a v  a2 s.  c om
            byte buf[] = new byte[1024];
            DatagramPacket pack = new DatagramPacket(buf, buf.length);
            socket.receive(pack);
            data = new String(pack.getData(), pack.getOffset(), pack.getLength());
            LOGGER.debug("Packet received with the following payload: {}.", data);
            Probe probe = JAXB.unmarshal(new StringReader(data), Probe.class);

            List<RespondTo> respondTo = probe.getRa().getRespondTo();

            boolean ignoreProbe = false;
            if (ignoreProbesList != null && !ignoreProbesList.isEmpty()) {
                for (String ignoreProbeString : ignoreProbesList) {
                    String updatedIgnoreString = expandRespondToAddress(ignoreProbeString);
                    // TODO cache the request ID and use that instead of the local hostname
                    if (StringUtils.equalsIgnoreCase(updatedIgnoreString, respondTo.get(0).getValue())) {
                        LOGGER.debug(
                                "Configuration is set to ignore probes that have a respondTo of '{}'. Incoming probe contains respondTo of '{}'. IGNORING PROBE.",
                                ignoreProbeString, respondTo.get(0).getValue());
                        ignoreProbe = true;
                    }
                }
            }
            if (!ignoreProbe) {
                List<String> contractIDs = probe.getScids().getServiceContractID();
                // TODO handle the different contractID
                // URI contractId = probe.getContractID();
                String probeId = probe.getId();
                String response = generateServiceResponse(probe.getRespondToPayloadType(), contractIDs,
                        probeId);

                if (StringUtils.isNotBlank(response)) {
                    LOGGER.debug("Returning back to {} with the following response:\n{}",
                            respondTo.get(0).getValue(), response);
                    sendResponse(respondTo.get(0).getValue(), response, probe.getRespondToPayloadType());
                } else {
                    LOGGER.debug(
                            "No services found that match the incoming contract IDs, not sending a response.");
                }
            }
        } catch (DataBindingException e) {
            LOGGER.warn("Issue parsing probe response: {}", data, e);
        } catch (SocketTimeoutException ste) {
            LOGGER.trace("Received timeout on socket, resetting socket to check for cancellation.");
        } catch (IOException ioe) {
            if (!isCanceled) {
                LOGGER.warn("Error while trying to receive a packet, shutting down listener", ioe);
            }
            break;
        }
    }
    if (isCanceled) {
        LOGGER.debug("Listener was canceled, not receiving any more multicast packets.");
    }

}

From source file:com.github.thesmartenergy.cnr.SmartChargingProvider.java

@Override
public void create(ProcessExecution processExecution) throws PEPException {
    super.create(processExecution);
    String id = processExecution.getId();
    Model input = processExecution.getInput();
    try {/*from   w w w .j  a va 2s  .  c  o  m*/
        // get XML document
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ResourceDescription presentation = new ResourceDescription(DEV_BASE + "inputGraph");
            PresentationUtils presentationUtils = new PresentationUtils();
            STTLHandler lowerer = new STTLHandler(BASE, presentationUtils);
            lowerer.lower(input, out, MediaType.APPLICATION_XML_TYPE, presentation);
        } catch (RDFPException ex) {
            throw new PEPException("Error while lowering input", ex);
        }
        String xml = new String(out.toByteArray(), "UTF-8");
        GetChargingPlans getChargingPlans = JAXB.unmarshal(xml, GetChargingPlans.class);

        LOG.info("sending message: " + xml);

        // embed value in a SOAP envelope
        SOAPMessage soapMessage = createSoapMessage(getChargingPlans);
        out = new ByteArrayOutputStream();
        soapMessage.writeTo(out);
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        String string = IOUtils.toString(in, Charset.forName("UTF-8"));
        LOG.info("sending message: " + string);
        BrokeredMessage message = new BrokeredMessage(string);
        message.setMessageId(id);
        service.sendQueueMessage(queue, message);
    } catch (ServiceException | SOAPException | IOException ex) {
        throw new PEPException(ex);
    }
}

From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static OOListResponse listFlows(OOServer s, String... folders) throws IOException {

    String foldersPath = "";

    for (String folder : folders) {
        foldersPath += folder + "/";
    }/*from   w ww. jav  a2s.  co  m*/

    String url = StringUtils.slashify(s.getUrl()) + REST_SERVICES_URL_PATH + LIST_OPERATION_URL_PATH
            + foldersPath;

    final HttpResponse response = OOBuildStep.getHttpClient().execute(new HttpGet(OOBuildStep.URI(url)));

    final int statusCode = response.getStatusLine().getStatusCode();

    final HttpEntity entity = response.getEntity();

    try {

        if (statusCode == HttpStatus.SC_OK) {

            return JAXB.unmarshal(entity.getContent(), OOListResponse.class);
        } else {

            throw new RuntimeException("unable to get list of flows from " + url + ", response code: "
                    + statusCode + "(" + HttpStatus.getStatusText(statusCode) + ")");
        }
    } finally {
        EntityUtils.consume(entity);
    }
}

From source file:eu.openanalytics.rsb.RestAdminITCase.java

@Test
public void getRServiPools() throws Exception {
    final WebConversation wc = new WebConversation();
    final WebRequest request = new GetMethodWebRequest(RSB_BASE_URI + "/api/rest/admin/system/rservi_pools");
    final WebResponse response = wc.sendRequest(request);
    assertEquals(200, response.getResponseCode());
    final RServiPools rServiPools = JAXB.unmarshal(new StringReader(response.getText()), RServiPools.class);
    assertFalse(rServiPools.getContents().isEmpty());
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

@Override
public SelectionListModel getAnnotations(String quickhash1) throws IOException {
    SelectionListModel ssModel = new DefaultSelectionListModel();

    try {//from w w  w  . ja  v  a 2  s .  c  o m
        URI u = new URI(uriPrefix + quickhash1 + "/");
        System.out.println(u);

        GetMethod g = new GetMethod(u.toString());
        try {
            InputStream in = getBody(g);
            if (in != null) {
                RegionList rl = JAXB.unmarshal(in, RegionList.class);

                // convert RegionList
                for (Region r : rl.getRegion()) {
                    Shape s = SlideAnnotation.stringToShape(r.getPath());
                    Integer id = r.getId();
                    String creator = r.getCreator();

                    List<SlideAnnotationNote> notes = new ArrayList<SlideAnnotationNote>();
                    for (Note n : r.getNotes().getNote()) {
                        SlideAnnotationNote san = new SlideAnnotationNote(n.getCreator(), n.getId(),
                                n.getText());
                        notes.add(san);
                    }

                    SlideAnnotation sa = new SlideAnnotation(s, id, creator, notes);
                    System.out.println(sa);
                    ssModel.add(sa);
                }
            }
        } finally {
            g.releaseConnection();
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }

    return ssModel;
}

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

public void testLoad01() throws IOException {

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

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

    boolean check = StatisticChecker.check(cfg);
    assertTrue("Configuration is not valid", check);

    assertNotNull(cfg.getOutput().getFile());

    for (ClassificationLayer xls : cfg.getClassifications()) {
        LOGGER.info("Classification: " + xls);
    }/*from  w w w.  j  a  va 2s  . c o m*/
}

From source file:eu.openanalytics.rsb.RestAdminITCase.java

@Test
public void getCatalog() throws Exception {
    final WebConversation wc = new WebConversation();
    final WebRequest request = new GetMethodWebRequest(RSB_BASE_URI + "/api/rest/admin/catalog");
    final WebResponse response = wc.sendRequest(request);
    assertEquals(200, response.getResponseCode());

    final Catalog catalog = JAXB.unmarshal(new StringReader(response.getText()), Catalog.class);
    final List<CatalogDirectory> directories1 = catalog.getDirectories();
    final List<CatalogDirectory> directories = directories1;

    // check all catalog dirs
    assertEquals(4, directories.size());
    for (final CatalogDirectory cd : directories) {
        assertEquals(cd.getType(), Configuration.CatalogSection.valueOf(cd.getType()).toString());
        assertTrue(StringUtils.isNotBlank(cd.getPath()));
    }/*from w w  w  .  j  a v a  2 s.c  om*/

    // check one catalog file
    final CatalogFileType catalogFile = directories.get(0).getFiles().get(0);
    assertTrue(StringUtils.isNotBlank(catalogFile.getName()));
    assertTrue(StringUtils.isNotBlank(catalogFile.getDataUri()));
}

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

() {

    TResponse res = Http.request("box/$metadata-$metadata-get.txt")
            .with("path", "\\$metadata")
            .with("col", "setodata")
            .with("accept", "application/atomsvc+xml")
            .with("token", DcCoreConfig.getMasterToken())
            .returns()//from  ww w.j  a  v a 2s.co  m
            .statusCode(HttpStatus.SC_OK)
            .debug();

    // ???
    String str = res.getBody();

    Service service = JAXB.unmarshal(new StringReader(str), Service.class);

    Service rightService = new Service();
    rightService.workspace = new Workspace("Default",
            new HashSet<Collection>(Arrays.asList(new Collection("ComplexType", "ComplexType"),
                    new Collection("ComplexTypeProperty", "ComplexTypeProperty"),
                    new Collection("AssociationEnd", "AssociationEnd"),
                    new Collection("EntityType", "EntityType"),
                    new Collection("Property", "Property"))));

    assertTrue(rightService.isEqualTo(service));
}

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

() {

    TResponse res = Http.request("box/$metadata-$metadata-get.txt")
            .with("path", "\\$metadata")
            .with("col", "setodata")
            .with("accept", "application/atomsvc+xml")
            .with("token", PersoniumUnitConfig.getMasterToken())
            .returns()//from  w w w  .j  ava 2  s .  co m
            .statusCode(HttpStatus.SC_OK)
            .debug();

    // ???
    String str = res.getBody();

    Service service = JAXB.unmarshal(new StringReader(str), Service.class);

    Service rightService = new Service();
    rightService.workspace = new Workspace("Default",
            new HashSet<Collection>(Arrays.asList(new Collection("ComplexType", "ComplexType"),
                    new Collection("ComplexTypeProperty", "ComplexTypeProperty"),
                    new Collection("AssociationEnd", "AssociationEnd"),
                    new Collection("EntityType", "EntityType"),
                    new Collection("Property", "Property"))));

    assertTrue(rightService.isEqualTo(service));
}

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

public void _testRunAreaSmall() throws IOException {

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

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

    boolean check = StatisticChecker.check(cfg);
    assertTrue("Configuration is not valid", check);

    StatsRunner sr = new StatsRunner(cfg);
    sr.run();/*w w w.ja va  2  s.c o  m*/
}