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:edu.duke.cabig.c3pr.webservice.integration.SubjectRegistryWebServicePerformanceTest.java

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

    // successful creation
    final QueryStudySubjectRegistryRequest request = new QueryStudySubjectRegistryRequest();
    DSETAdvanceSearchCriterionParameter dsetAdvanceSearchCriterionParameter = new DSETAdvanceSearchCriterionParameter();
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("=", "500"));
    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();/*w  ww . j  av  a  2 s.  c o m*/
    startProfiling();
    service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    startProfiling();
    DSETStudySubject studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(20, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-100"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(100, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-200"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(200, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-300"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(300, studySubjects.getItem().size());
    dsetAdvanceSearchCriterionParameter.getItem().add(createAdvanceSearchParam("like", "%-400"));
    startProfiling();
    studySubjects = service.querySubjectRegistry(request).getStudySubjects();
    stopProfiling();
    assertNotNull(studySubjects);
    assertEquals(400, studySubjects.getItem().size());
}

From source file:com.bitplan.jaxb.JaxbFactory.java

/**
 * get a marshaller for the given <T> instance
 * /*from  w  w w.  j  a v a 2  s  . co m*/
 * @param instance
 *          - the instance to get a marshaller for
 * @return a marshaller for <T>
 * @throws JAXBException
 */
public Marshaller getMarshaller(T instance) throws JAXBException {
    JAXBContext lcontext = getJAXBContext();
    Marshaller marshaller = lcontext.createMarshaller();
    if (this.marshalListener != null) {
        marshaller.setListener(marshalListener);
    }
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    return marshaller;
}

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

private void importStudySubjects(int sbegin, int send, int pbegin, int pend, String batch) throws Exception {
    SubjectRegistry service = getService();

    // successful creation
    final ImportStudySubjectRegistryRequest request = new ImportStudySubjectRegistryRequest();
    request.setStudySubjects(new DSETStudySubject());
    //String batch = "";
    for (int start = sbegin; start < send; start++) {
        int study = start;
        //batch += "-"+(400-20*(study-500));
        for (int subject = pbegin; subject < pend; subject++) {
            StudySubject studySubject = createStudySubjectForImport();
            //Override some values
            ((Person) studySubject.getEntity()).setRaceCode(iso.DSETCD(iso.CD(RACE_WHITE)));
            ((Person) studySubject.getEntity()).setTelecomAddress(iso.BAGTEL(iso.TEL(TEST_EMAIL_ADDR_ISO)));
            ((Person) studySubject.getEntity()).getBiologicEntityIdentifier().get(0).getIdentifier()
                    .setExtension(subject + "");

            studySubject.getSubjectIdentifier().get(0).getIdentifier()
                    .setExtension(RandomStringUtils.randomAlphanumeric(6) + "--" + batch);
            studySubject.getSubjectIdentifier().get(0).setPrimaryIndicator(iso.BL(true));

            studySubject.getStudySubjectProtocolVersion().getStudySiteProtocolVersion()
                    .getStudyProtocolVersion().getStudyProtocolDocument().getDocument().getDocumentIdentifier()
                    .get(0).getIdentifier().setExtension(study + "");

            //add 1st consent
            studySubject.getStudySubjectProtocolVersion().getStudySubjectConsentVersion().clear();
            StudySubjectConsentVersion studySubjectConsentVersion = new StudySubjectConsentVersion();
            studySubjectConsentVersion.setConsentDeliveryDate(iso.TSDateTime(TEST_CONSENT_DELIVERY_DATE1));
            studySubjectConsentVersion.setInformedConsentDate(iso.TSDateTime(TEST_CONSENT_SIGNED_DATE1));
            studySubjectConsentVersion.setConsentingMethod(iso.CD(TEST_CONSENTING_METHOD1));
            studySubjectConsentVersion.setConsentPresenter(iso.ST(TEST_CONSENT_PRESENTER1));
            studySubjectConsentVersion.setConsent(new DocumentVersion());
            studySubjectConsentVersion.getConsent().setOfficialTitle(iso.ST(TEST_CONSENT_NAME1));
            studySubjectConsentVersion.getConsent().setVersionNumberText(iso.ST(TEST_CONSENT_VERSION1));
            PerformedStudySubjectMilestone subjectAnswer = new PerformedStudySubjectMilestone();
            subjectAnswer.setMissedIndicator(iso.BL(TEST_CONSENT_ANS11));
            subjectAnswer.setConsentQuestion(new DocumentVersion());
            subjectAnswer.getConsentQuestion().setOfficialTitle(iso.ST(TEST_CONSENT_QUES11));
            studySubjectConsentVersion.getSubjectConsentAnswer().add(subjectAnswer);
            studySubject.getStudySubjectProtocolVersion().getStudySubjectConsentVersion()
                    .add(studySubjectConsentVersion);

            request.getStudySubjects().getItem().add(studySubject);
        }/*from w w w  .j  av a  2  s  . c  om*/
    }

    JAXBContext context = JAXBContext.newInstance("edu.duke.cabig.c3pr.webservice.subjectregistry");
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(request, System.out);
    System.out.flush();
    DSETStudySubject createdStudySubjects = service.importSubjectRegistry(request).getStudySubjects();
    assertNotNull(createdStudySubjects);
    //      assertEquals(scount*pcount, createdStudySubjects.getItem().size());
}

From source file:net.longfalcon.newsj.Nzb.java

private Marshaller getMarshaller() throws JAXBException {
    if (_marshaller == null) {
        JAXBContext jaxbContext = JAXBContext.newInstance(File.class, Group.class, Groups.class, Head.class,
                Meta.class, net.longfalcon.newsj.xml.Nzb.class, Segment.class, Segments.class);
        _marshaller = jaxbContext.createMarshaller();
    }/*  ww  w . j  a v a  2 s  .com*/
    return _marshaller;
}

From source file:gov.nih.nci.integration.caaers.CaAERSParticipantServiceClientIntegrationTest.java

private Marshaller getMarshaller() throws JAXBException {
    final JAXBContext jc = JAXBContext.newInstance(ParticipantType.class);
    return jc.createMarshaller();
}

From source file:de.uniwue.info6.database.jaxb.ScenarioExporter.java

/**
 *
 *
 * @param scenario// w  w w . j ava2s.co  m
 */
public File generateScenarioXml(Scenario scenario) {
    scenario = populateScenario(scenario);
    File base = new File(scriptSystemPath + File.separator + Cfg.RESOURCE_PATH);
    File saveDir = new File(base, String.valueOf(scenario.getId()));

    try {
        if (!saveDir.exists() && saveDir.getParentFile().exists()) {
            saveDir.mkdir();
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy_MM_dd-HH_mm_ss");
        String baseName = "scenario_" + scenario.getId() + "_export_" + fmt.format(new Date());

        String conflict = "VERSION_CONFLICT";
        File scenarioXml = new File(saveDir, baseName + ".xml");
        File scenarioXmlConflict = new File(saveDir, baseName + "_" + conflict + ".xml");
        File scenarioXsd = new File(saveDir, baseName + ".xsd");
        File scenarioXsdConflict = new File(saveDir, baseName + "_" + conflict + ".xsd");
        File scenarioMain = new File(scriptSystemPath, "reference_schema.xsd");
        File scenarioMainConflict = new File(saveDir, baseName + "_" + "REFERENCE_SCHEMA.xsd");

        JAXBContext jaxbContext = JAXBContext.newInstance(Scenario.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(scenario, scenarioXml);

        SchemaOutputResolver sor = new CustomOutputResolver(saveDir, baseName + ".xsd");
        jaxbContext.generateSchema(sor);

        if (!scenarioMain.exists()) {
            LOGGER.error("REFERENCE SCHEMA IS MISSING: " + scenarioMain);
        }

        if (!scenarioXsd.exists()) {
            LOGGER.error("GENERATED XSD IS MISSING: " + scenarioXsd);
        }

        if (!scenarioXml.exists()) {
            LOGGER.error("GENERATED XML IS MISSING: " + scenarioXml);
        }

        if (scenarioMain.exists() && scenarioXsd.exists() && scenarioXml.exists()) {
            String referenceMD5 = calculateMD5FromFile(scenarioMain);
            String newMD5 = calculateMD5FromFile(scenarioXsd);

            File export = null;
            boolean falseMD5 = !referenceMD5.equals(newMD5);
            File conflictReadme = new File(saveDir, conflict + "_README.txt");

            if (falseMD5) {
                FileUtils.moveFile(scenarioXml, scenarioXmlConflict);
                FileUtils.moveFile(scenarioXsd, scenarioXsdConflict);
                FileUtils.copyFile(scenarioMain, scenarioMainConflict);
                scenarioXml = scenarioXmlConflict;
                scenarioXsd = scenarioXsdConflict;
                export = new File(saveDir, "scenario_" + scenario.getId() + "_export_" + conflict + ".zip");
                String readme = Cfg.inst().getProp(DEF_LANGUAGE, "MISC.XSD_XML_CONFLICT") + "\n"
                        + scenarioMainConflict.getName();

                if (conflictReadme.exists()) {
                    conflictReadme.delete();
                }
                if (!conflictReadme.exists()) {
                    conflictReadme.createNewFile();
                }

                PrintWriter out = new PrintWriter(conflictReadme);
                out.println(readme);
                out.flush();
                out.close();
            } else {
                export = new File(saveDir, "scenario_" + scenario.getId() + "_export.zip");
            }

            ArrayList<File> exportFiles = new ArrayList<File>();
            if (scenarioXml.exists()) {
                exportFiles.add(scenarioXml);
            }
            if (scenarioXsd.exists()) {
                exportFiles.add(scenarioXsd);
            }
            if (falseMD5 && conflictReadme.exists() && scenarioMainConflict.exists()) {
                exportFiles.add(conflictReadme);
                exportFiles.add(scenarioMainConflict);
            }
            if (export.exists()) {
                export.delete();
            }
            return zip(exportFiles, export);
        }

    } catch (Exception e) {
        LOGGER.error("EXPORT XSD/XML FAILED!", e);
    }
    return null;
}

From source file:TwitterRetrieval.java

private void Twitter2XML(PostsType posts, PrintWriter out) throws Exception {
    JAXBContext context = JAXBContext.newInstance("entities");
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(posts, out);// w w w.ja v a  2  s .  c o  m
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapterOutbound.java

@Override
public void receive(GeoEvent geoEvent) {

    stringBuffer.setLength(0);// ww w.j  ava 2 s  .  c  o m
    GeoEventDefinition definition = geoEvent.getGeoEventDefinition();
    System.out.println("Creating Event to marshal...");
    Event event = new Event();
    for (FieldDefinition fieldDefinition : definition.getFieldDefinitions()) {
        try {
            String attributeName = fieldDefinition.getName();
            Object value;
            if ((value = geoEvent.getField(attributeName)) != null) {

                if (attributeName.equalsIgnoreCase("version")) {
                    event.setVersion((Double) value);
                } else if (attributeName.equalsIgnoreCase("uid")) {
                    event.setUid(value.toString());
                } else if (attributeName.equalsIgnoreCase("type")) {
                    event.setType(value.toString());
                } else if (attributeName.equalsIgnoreCase("how")) {
                    event.setHow(value.toString());
                } else if (attributeName.equalsIgnoreCase("time")) {
                    event.setTime((Date) value);
                } else if (attributeName.equalsIgnoreCase("start")) {
                    event.setStart((Date) value);
                } else if (attributeName.equalsIgnoreCase("stale")) {
                    event.setStale((Date) value);
                } else if (attributeName.equalsIgnoreCase("access")) {
                    event.setAccess(value.toString());
                } else if (attributeName.equalsIgnoreCase("opex")) {
                    event.setOpex(value.toString());
                } else if (attributeName.equalsIgnoreCase("qos")) {
                    event.setQos(value.toString());
                } else if (attributeName.equalsIgnoreCase("detail")) {
                    event.setDetail(this.unpackDetial(fieldDefinition, geoEvent.getFieldGroup("detail")));

                    // GETALLFIELDS
                    // CHECK ITS TYPE IF GROUP THEN INSPECT THEM
                } else if (attributeName.equalsIgnoreCase("point")) {
                    Point p = pointFromJson(value);
                    event.setPoint(pointFromJson(p));
                }
            }

        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

    }

    /////////////////////////
    String xmlResult = null;
    StringBuilder myResult = new StringBuilder();
    int content;

    System.out.println("Event created.");

    System.out.println("Marshalling Event into XML.");

    try {

        JAXBContext contextObj = JAXBContext.newInstance(Event.class);
        Marshaller marshallerObj = contextObj.createMarshaller();
        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        marshallerObj.marshal(event, os);
        ByteArrayInputStream bais = new ByteArrayInputStream(os.toByteArray());

        while ((content = bais.read()) != -1) {
            myResult.append((char) content);
        }

        xmlResult = fixEscapeCharacters(myResult.toString());
        System.out.println("**** XML RESULTS ***");
        System.out.println(xmlResult);
        //this.byteListener.receive(ByteBuffer.wrap(xmlResult.getBytes()), "");
        super.receive(ByteBuffer.wrap(xmlResult.getBytes()), "", geoEvent);
    } catch (JAXBException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("Done");
}

From source file:demo.jaxrs.server.CustomerServiceImpl.java

public Customer getCustomer1(String id) {
    System.out.println("----invoking getCustomer, Customer id is: " + id);
    long idNumber = Long.parseLong(id);
    Customer c = customers.get(idNumber);
    Customer c1;/*from ww w  .j a  v  a2  s .co  m*/
    JAXBContext ctx;
    try {
        ctx = JAXBContext.newInstance(Customer.class);
        StringWriter writer = new StringWriter();
        ctx.createMarshaller().marshal(c, writer);
        String custString = writer.toString();
        c1 = (Customer) ctx.createUnmarshaller().unmarshal(new StringReader(custString));
    } catch (JAXBException e) {
        e.printStackTrace();
    }
    return c;
}

From source file:org.opennms.features.vaadin.pmatrix.manual.AppContextSpecificationMarshalTest.java

public void testJaxbFromContext() {
    System.out.println("start of test:testJaxbFromContext()");
    try {/* w ww.  j  a v  a 2 s. c om*/
        String testFileName = this.getClass().getSimpleName() + "_File.xml";
        File file = new File("target/" + testFileName);
        PrintWriter writer = new PrintWriter(file, "UTF-8");
        writer.close();
        System.out.println("file location:" + file.getAbsolutePath());

        // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix
        // need to provide bundles class loader
        ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader();
        JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model", cl);

        //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model");

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        PmatrixSpecificationList pmatrixSpecificationList_context = (PmatrixSpecificationList) appContext
                .getBean("pmatrixSpecificationList");
        //PmatrixSpecification pmatrixSpec_Context = (PmatrixSpecification) appContext.getBean("pmatrixSpecification");

        //System.out.println("list to be marshalled:");
        System.out.println(pmatrixSpecificationList_context);

        System.out.println("marshalled list:");
        //jaxbMarshaller.marshal(testDatalist, file);

        //jaxbMarshaller.marshal(pmatrixSpec, System.out); // works
        //jaxbMarshaller.marshal(pmatrixSpecificationList, System.out); //works

        //test of marshaling context data
        //jaxbMarshaller.marshal(pmatrixSpecificationList_context, System.out);
        jaxbMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION,
                "http://xmlns.opennms.org/xsd/config/pmatrix pmatrixConfig.xsd");

        jaxbMarshaller.marshal(pmatrixSpecificationList_context, file);
        //jaxbMarshaller.marshal(pmatrixSpecificationList_context, file);

        //unmarshal test file

        Unmarshaller jaxbUnMarshaller = jaxbContext.createUnmarshaller();

        //Object o = jaxbUnMarshaller.unmarshal( new StringReader( marshalledXml )  );

        Object o = jaxbUnMarshaller.unmarshal(file);

        System.out.println("o.tostring:" + o.toString());
        if (o instanceof PmatrixSpecificationList) {
            System.out.println("unmarshalled list:");
            System.out.println((PmatrixSpecificationList) o);

        } else
            System.out.println("cant unmarshal object:");

    } catch (JAXBException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("end of test:testAppContext()");
}