Example usage for javax.xml.bind JAXBContext createMarshaller

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

Introduction

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

Prototype

public abstract Marshaller createMarshaller() throws JAXBException;

Source Link

Document

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

Usage

From source file:org.exist.xquery.RestBinariesTest.java

private HttpResponse postXquery(final String xquery) throws JAXBException, IOException {
    final Query query = new Query();
    query.setText(xquery);//from ww w  . ja v  a2  s  .  c om

    final JAXBContext jaxbContext = JAXBContext.newInstance("org.exist.http.jaxb");
    final Marshaller marshaller = jaxbContext.createMarshaller();

    final HttpResponse response;
    try (final FastByteArrayOutputStream baos = new FastByteArrayOutputStream()) {
        marshaller.marshal(query, baos);
        response = executor.execute(Request.Post(getRestUrl() + "/db/").bodyByteArray(baos.toByteArray(),
                ContentType.APPLICATION_XML)).returnResponse();
    }

    if (response.getStatusLine().getStatusCode() != SC_OK) {
        throw new IOException(
                "Unable to query, HTTP response code: " + response.getStatusLine().getStatusCode());
    }

    return response;
}

From source file:edu.duke.cabig.c3pr.webservice.integration.SubjectRegistryWebServicePerformanceTest.java

private void executeBulkQuerySubjectRegistryTest() throws SQLException, Exception {
    SubjectRegistry service = getService();

    // successful creation
    final QueryStudySubjectRegistryRequest request = new QueryStudySubjectRegistryRequest();
    DSETAdvanceSearchCriterionParameter dsetAdvanceSearchCriterionParameter = new DSETAdvanceSearchCriterionParameter();
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%%%"));
    request.setSearchParameter(dsetAdvanceSearchCriterionParameter);

    JAXBContext context = JAXBContext.newInstance("edu.duke.cabig.c3pr.webservice.subjectregistry");
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(request, System.out);
    System.out.flush();//from   ww w  .j  a  v a2 s . com
    startProfiling();
    List<StudySubject> studySubjects = service.querySubjectRegistry(request).getStudySubjects().getItem();
    stopProfiling();
    assertEquals(200, studySubjects.size());
    //      startProfiling();
    //      request.setReduceGraph(iso.BL(true));
    //      service.querySubjectRegistry(request).getStudySubjects();
    //      stopProfiling();
    //      assertEquals(200, studySubjects.size());
}

From source file:hydrograph.ui.engine.util.ConverterUtil.java

/**
 * Store file into workspace./*w  w w . j  a  v a  2 s.  c om*/
 *
 * @param graph the graph
 * @param outPutFile the out put file
 * @param out the out
 * @throws JAXBException the JAXB exception
 * @throws CoreException the core exception
 */
private void storeFileIntoWorkspace(Graph graph, boolean validate, IFile outPutFile, ByteArrayOutputStream out)
        throws JAXBException, CoreException {

    JAXBContext jaxbContext = JAXBContext.newInstance(graph.getClass());
    Marshaller marshaller = jaxbContext.createMarshaller();
    out = new ByteArrayOutputStream();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(graph, out);
    out = ComponentXpath.INSTANCE.addParameters(out);

    /*
     * To-do will be removed in future
     * String updatedXML=escapeXml(out.toString());
    out.reset();
    try {
       if(!unknownComponentLists.isEmpty())
      out.write(updatedXML.getBytes());
    } catch (IOException ioException) {
      LOGGER.error("Unable to update escape sequene in xml file",ioException);
    }*/
    if (outPutFile.exists()) {
        outPutFile.setContents(new ByteArrayInputStream(out.toByteArray()), true, false, null);
    } else {
        outPutFile.create(new ByteArrayInputStream(out.toByteArray()), true, null);
    }
}

From source file:edu.duke.cabig.c3pr.domain.scheduler.runtime.job.CCTSNotificationMessageJob.java

private String serialize(Notification notification) {
    try {//ww w.  ja  v a2 s  .c  o  m
        JAXBContext context = JAXBContext.newInstance(Notification.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        JAXBElement<Notification> jaxbElement = new JAXBElement<Notification>(
                new QName(CCTS_NOTIFICATIONS_NS, "notification"), Notification.class, notification);
        CharArrayWriter writer = new CharArrayWriter();
        m.marshal(jaxbElement, writer);
        return String.valueOf(writer.toCharArray());
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }

}

From source file:gov.nih.nci.integration.caaers.invoker.CaAERSUpdateRegistrationServiceInvocationStrategy.java

private Marshaller getMarshaller() throws JAXBException {
    if (marshaller == null) {
        final JAXBContext jc = JAXBContext.newInstance(ParticipantType.class);
        marshaller = jc.createMarshaller();
    }//from   ww w  .j  a v a  2s  . c  o m
    return marshaller;
}

From source file:org.javelin.sws.ext.bind.jaxb.JaxbTest.java

@Test
public void unmarshalSameQNames() throws Exception {
    JAXBContext ctx = JAXBContext.newInstance(org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1.class,
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class);
    Marshaller m = ctx.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

    log.info("context1");
    org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1 mc1 = new org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1();
    mc1.setP(new MyProperty1());
    m.marshal(new JAXBElement<org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1>(new QName("a", "a"),
            org.javelin.sws.ext.bind.jaxb.context1.MyClassJ1.class, mc1), System.out);
    log.info("context2");
    org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2 mc2 = new org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2();
    mc2.setP(new MyProperty2());
    m.marshal(new JAXBElement<org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2>(new QName("a", "a"),
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class, mc2), System.out);

    Object object = ctx.createUnmarshaller().unmarshal(
            new StreamSource(
                    new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\r\n"
                            + "<ns2:a xmlns=\"urn:x\" xmlns:ns2=\"a\">\r\n" + "    <p/>\r\n" + "</ns2:a>")),
            org.javelin.sws.ext.bind.jaxb.context2.MyClassJ2.class);
    log.info("Class: {}", ((JAXBElement<?>) object).getValue().getClass());
}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void notifyScoreUpdate(ScoreRecord record) throws LpRestException {
    String contentType = "application/xml";
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/scores", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, contentType);

    try {//from  w  ww  . ja va 2  s . c om
        JAXBContext jc = JAXBContext.newInstance(ScoreRecord.class);
        Writer marshalledRecord = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(record, marshalledRecord);

        postMethod.setRequestEntity(new StringRequestEntity(marshalledRecord.toString(), contentType, "UTF-8"));

        httpClient.executeMethod(postMethod);
    } catch (JAXBException e1) {
        e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec)
        throws LpRestException {
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/notify/%s", DefaultRestResource.REST_URI, modelSetId);

    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("simulationid", simulationid);
    queryString[1] = new NameValuePair("userid", userId);
    putMethod.setQueryString(queryString);

    try {/*from ww w .  j a  v  a 2s. c om*/
        JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
        Writer recWriter = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(rec, recWriter);

        RequestEntity requestEntity = new StringRequestEntity(recWriter.toString(), contentType, "UTF-8");
        putMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(putMethod);
    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:esg.common.security.PolicyGleaner.java

public synchronized boolean savePolicyAs(Policies policy, String policyFileLocation) {
    boolean success = false;
    if (policy == null) {
        log.error("Sorry internal policy representation is null ? [" + policy
                + "] perhaps you need to load policy file first?");
        return success;
    }//from w ww . j a  v a2  s .  c om
    log.info("Saving policy information to " + policyFileLocation);
    try {
        JAXBContext jc = JAXBContext.newInstance(Policies.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(policy, new FileOutputStream(policyFileLocation));
        success = true;
    } catch (Exception e) {
        log.error(e);
    }
    return success;
}

From source file:ca.ualberta.physics.cssdp.catalogue.resource.ProjectResourceTest.java

@Test
public void testCreateGetAndDeleteWithJSONAndXML() throws Exception {

    Project project = new Project();
    project.setExternalKey(Mnemonic.of("TEST"));
    project.setHost("localhost");
    project.setName("Test Project");

    Observatory o = new Observatory();
    o.setExternalKey(Mnemonic.of("TEST-OBSERV"));
    o.setDescription("Test Observatory");
    o.setProject(project);/*from   w  w w .  java2  s .co  m*/
    o.setLocation(10d, 10d);
    project.getObservatories().add(o);

    InstrumentType i = new InstrumentType();
    i.setExternalKey(Mnemonic.of("TEST-INST"));
    i.setDescription("Test Instrument Type");
    i.setProject(project);
    project.getInstrumentTypes().add(i);

    DataProduct dp = new DataProduct();
    dp.setExternalKey(Mnemonic.of("TEST-DP"));
    dp.setDescription("Test Data Product");
    dp.setInstrumentTypes(project.getInstrumentTypes());
    dp.addObservatories(project.getObservatories());
    dp.setProject(project);
    project.getDataProducts().add(dp);

    String projectJSON = mapper.writeValueAsString(project);
    System.out.println(projectJSON);
    Response res = given().body(projectJSON).and().contentType("application/json").expect().statusCode(201)
            .when().post(ResourceUrls.PROJECT);

    Project createdProject = get(res.getHeader("location")).as(Project.class);

    Assert.assertNotNull(createdProject.getId());
    for (Observatory obs : createdProject.getObservatories()) {
        Assert.assertNotNull(obs.getId());
        Assert.assertTrue(obs.getId().toString(), obs.getId() > 0);
    }
    for (InstrumentType it : createdProject.getInstrumentTypes()) {
        Assert.assertNotNull(it.getId());
        Assert.assertTrue(it.getId().toString(), it.getId() > 0);
    }
    for (DataProduct dataProduct : createdProject.getDataProducts()) {
        Assert.assertNotNull(dataProduct.getId());
        Assert.assertTrue(dataProduct.getId().toString(), dataProduct.getId() > 0);
        for (Observatory o2 : dataProduct.getObservatories()) {
            Assert.assertNotNull(o2.getId());
            Assert.assertTrue(o2.getId().toString(), o2.getId() > 0);
        }
        for (InstrumentType it2 : dataProduct.getInstrumentTypes()) {
            Assert.assertNotNull(it2.getId());
            Assert.assertTrue(it2.getId().toString(), it2.getId() > 0);
        }

    }

    expect().statusCode(200).when().delete(res.getHeader("location"));
    expect().statusCode(404).when().get(res.getHeader("location"));

    // same test with XML now
    project.setExternalKey(Mnemonic.of("TEST2"));

    StringWriter writer = new StringWriter();
    JAXBContext context = JAXBContext.newInstance(Project.class);
    Marshaller m = context.createMarshaller();
    m.marshal(project, writer);

    String xml = writer.toString();
    System.out.println(xml);
    res = given().content(xml).and().contentType("application/xml").expect().statusCode(201).when()
            .contentType(ContentType.XML).post(ResourceUrls.PROJECT);

    createdProject = get(res.getHeader("location")).as(Project.class);

    Assert.assertNotNull(createdProject.getId());
    for (Observatory obs : createdProject.getObservatories()) {
        Assert.assertNotNull(obs.getId());
        Assert.assertTrue(obs.getId().toString(), obs.getId() > 0);
    }
    for (InstrumentType it : createdProject.getInstrumentTypes()) {
        Assert.assertNotNull(it.getId());
        Assert.assertTrue(it.getId().toString(), it.getId() > 0);
    }
    for (DataProduct dataProduct : createdProject.getDataProducts()) {
        Assert.assertNotNull(dataProduct.getId());
        Assert.assertTrue(dataProduct.getId().toString(), dataProduct.getId() > 0);
        for (Observatory o2 : dataProduct.getObservatories()) {
            Assert.assertNotNull(o2.getId());
            Assert.assertTrue(o2.getId().toString(), o2.getId() > 0);
        }
        for (InstrumentType it2 : dataProduct.getInstrumentTypes()) {
            Assert.assertNotNull(it2.getId());
            Assert.assertTrue(it2.getId().toString(), it2.getId() > 0);
        }

    }

    expect().statusCode(200).when().delete(res.getHeader("location"));
    expect().statusCode(404).when().get(res.getHeader("location"));

}