Example usage for javax.xml.bind Marshaller JAXB_ENCODING

List of usage examples for javax.xml.bind Marshaller JAXB_ENCODING

Introduction

In this page you can find the example usage for javax.xml.bind Marshaller JAXB_ENCODING.

Prototype

String JAXB_ENCODING

To view the source code for javax.xml.bind Marshaller JAXB_ENCODING.

Click Source Link

Document

The name of the property used to specify the output encoding in the marshalled XML data.

Usage

From source file:com.mymita.vaadlets.JAXBUtils.java

private static final void marshal(final Writer aWriter, final Vaadlets vaadlets,
        final Resource theSchemaResource) {
    try {/*from ww w .  j  av  a2  s. co m*/
        final JAXBContext jc = JAXBContext.newInstance(CONTEXTPATH);
        final Marshaller marshaller = jc.createMarshaller();
        if (theSchemaResource != null) {
            final SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            schemaFactory.setResourceResolver(new ClasspathResourceResolver());
            final Schema schema = schemaFactory.newSchema(new StreamSource(theSchemaResource.getInputStream()));
            marshaller.setSchema(schema);
        }
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper",
                new com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper() {

                    @Override
                    public String getPreferredPrefix(final String namespaceUri, final String suggestion,
                            final boolean requirePrefix) {
                        final String subpackage = namespaceUri.replaceFirst("http://www.mymita.com/vaadlets/",
                                "");
                        if (subpackage.equals("1.0.0")) {
                            return "";
                        }
                        return Iterables.getFirst(newArrayList(Splitter.on("/").split(subpackage).iterator()),
                                "");
                    }
                });
        marshaller.marshal(
                new JAXBElement<Vaadlets>(new QName("http://www.mymita.com/vaadlets/1.0.0", "vaadlets", ""),
                        Vaadlets.class, vaadlets),
                aWriter);
    } catch (final JAXBException | SAXException | FactoryConfigurationError | IOException e) {
        throw new RuntimeException("Can't marschal", e);
    }
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getTestcaseString(String urlServer, String projectAreaAlias, String encoding, String name,
        String steps, Testcase currentTestCase) throws JAXBException {

    Richtext textDesgin = new Richtext();
    textDesgin.getContent().add(escapeHTMLForAlm(steps));

    currentTestCase.setTitle(name);/*  w w  w.  j  a v  a2  s  .co m*/
    currentTestCase.setSuspect(false);
    currentTestCase.setWeight(100);
    currentTestCase.setComIbmRqmPlanningEditorSectionTestCaseDesign(textDesgin);

    // Valor da Categoria
    String categoryTipoExecucao = BehaveConfig.getIntegration_CategoryTipoExecucao();

    // Verifica se no caso de teste vindo da ALM existe a categoria
    // "Tipo de Execuo", se no existe cria.
    boolean objExists = false;
    for (Testcase.Category c : currentTestCase.getCategory()) {
        if (c.getTerm().toLowerCase().trim().equals("tipo de execuo")) {
            objExists = true;
            // Altera para "Automtica"
            c.setValue(categoryTipoExecucao);
            break;
        }
    }

    if (!objExists) {
        Testcase.Category newC = new Testcase.Category();
        newC.setTerm("Tipo de Execuo");
        newC.setValue(categoryTipoExecucao);
        currentTestCase.getCategory().add(newC);
    }

    JAXBContext jaxb = JAXBContext.newInstance(Testcase.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter testCaseString = new StringWriter();
    marshaller.marshal(currentTestCase, testCaseString);

    return testCaseString.toString();
}

From source file:dk.dma.epd.common.prototype.communication.webservice.ShoreHttp.java

public void setXmlMarshalContent(String contextPath, Object obj)
        throws JAXBException, UnsupportedEncodingException {
    JAXBContext jc = JAXBContext.newInstance(contextPath);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    m.setProperty(Marshaller.JAXB_ENCODING, ENCODING);
    StringWriter sw = new StringWriter();
    m.marshal(obj, sw);// w  w w. jav  a 2 s  .c o  m
    String req = sw.toString();
    LOG.debug("XML request: " + req);
    setRequestBody(sw.toString().getBytes(ENCODING), ENCODING);
}

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

public void testJaxbManual() {
    System.out.println("start of test:testJaxb()");
    try {/*ww w.  j a va 2 s.co m*/
        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());

        JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model");
        // TODO these classes are listed in jaxb.index file
        //         JAXBContext jaxbContext = JAXBContext.newInstance(               
        //               PmatrixSpecificationImpl.class,
        //               DataPointDefinitionImpl.class,
        //               PmatrixSpecificationListImpl.class,
        //               NameValuePair.class,
        //               PmatrixDpdCalculatorConfigImpl.class);

        // **********************
        // marshal test file
        // **********************

        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");

        // manual create process
        PmatrixSpecificationImpl newspec1 = createNewSpecification();
        newspec1.setPmatrixName("spec1");
        PmatrixSpecificationImpl newspec2 = createNewSpecification();
        newspec2.setPmatrixName("spec2");

        //create new specfication list
        PmatrixSpecificationListImpl pmatrixSpecificationList = new PmatrixSpecificationListImpl();
        pmatrixSpecificationList.setRefreshRate(1000);

        //create and add new DpdCalculator specification
        PmatrixDpdCalculatorConfig pmatrixDpdCalculatorConfig = new PmatrixDpdCalculatorConfigImpl();
        pmatrixDpdCalculatorConfig
                .setPmatrixDpdCalculatorClassName(PmatrixDpdCalculatorEmaImpl.class.getName());

        List<NameValuePair> configuration = new ArrayList<NameValuePair>();
        configuration.add(new NameValuePair("file", "fred.txt"));
        pmatrixDpdCalculatorConfig.setConfiguration(configuration);

        pmatrixSpecificationList.setPmatrixDpdCalculatorConfig(pmatrixDpdCalculatorConfig);

        //add specifications of each matrix
        List<PmatrixSpecification> pmsl = new ArrayList<PmatrixSpecification>();

        pmsl.add(newspec1);
        pmsl.add(newspec2);
        pmatrixSpecificationList.setPmatrixSpecificationList(pmsl);

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

        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, 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:testJaxb()");
}

From source file:cz.zcu.kiv.eegdatabase.logic.xml.XMLTransformer.java

public OutputStream transform(Experiment meas, MetadataCommand mc, Set<DataFile> datas)
        throws JAXBException, IOException {

    if (meas == null) {
        return null;
    }/*from   www .  j  a  va  2 s. c  om*/
    jc = JAXBContext.newInstance(objects);
    of = new ObjectFactory();
    log.debug("Creating JAXB context");
    MeasurationType measType = of.createMeasurationType();
    XMLMeasuration mea = new XMLMeasuration(measType);
    if (mc.isTimes()) {
        mea.writeStartAndEndTime(meas.getStartTime().toString(), meas.getEndTime().toString());
        log.debug("Written start and end time: " + measType.getStartTime() + ", " + measType.getEndTime());
    }
    Scenario scenario = meas.getScenario();
    ScenarioType scType = of.createScenarioType();
    XMLScenario scen = new XMLScenario(scType);
    if (mc.isTitle()) {
        scen.writeTitle(scenario.getTitle());
    }
    if (mc.isLength() && scenario.getScenarioLength() >= 0) {
        scen.writeLength("" + scenario.getScenarioLength()
                + ResourceUtils.getString("valueTable.scenarioLength.minutes"));
    }
    if (mc.isDescription()) {
        scen.writeDescription(scenario.getDescription());
    }
    measType.setScenario(scType);
    log.debug("Written Scenario metadata: " + scType);
    if (mc.isTemperature()) {
        measType.setTemperature(meas.getTemperature());
    }
    if (mc.isHardware()) {
        List<HardwareType> hwType = measType.getHardware();
        for (Hardware hw : meas.getHardwares()) {
            hwType.add(mea.writeHardware(hw, of));
            log.debug("Written hardware: " + hw);
        }
    }
    if (mc.isMeasurationAddParams()) {
        List<MeasurationAddParam> param = measType.getAddParam();
        for (ExperimentOptParamVal measAddParam : meas.getExperimentOptParamVals()) {
            param.add(mea.writeAdditionalParams(measAddParam, of));
            log.debug("Written measured additional params: " + measAddParam);
        }
    }

    if (mc.isWeather() && meas.getWeather() != null) {
        WeatherType wType = of.createWeatherType();
        wType.setTitle(meas.getWeather().getTitle());
        wType.setDescription(meas.getWeather().getDescription());
        measType.setWeather(wType);
        log.debug("Written weather: " + wType);
    }
    if (mc.isWeatherNote()) {
        measType.setEnvironmentNote(meas.getEnvironmentNote());
    }
    List<PersonType> perType = measType.getPerson();
    writePerson(perType, meas.getPersonBySubjectPersonId(), measured, mc, meas.getStartTime());
    for (Person person : meas.getPersons()) {
        writePerson(perType, person, experimenter, mc, null);
        log.debug("Written Person metadata: " + person);
    }

    List<DataType> dataType = measType.getData();
    if (meas.getDataFiles() != null) {
        for (DataFile data : datas) {
            log.debug("creating data into output xml: " + data.getFilename());
            DataType datat = of.createDataType();
            datat.setFileName(data.getFilename());
            if (mc.isSamplingRate()) {
                datat.setDescription(data.getDescription());
            }
            log.debug("Written file description: " + datat.getDescription());
            if (data.getFileMetadataParamVals() != null) {
                List<FileMetadataType> metType = datat.getFileMetadata();
                for (FileMetadataParamVal fileMetadata : data.getFileMetadataParamVals()) {
                    metType.add(mea.writeFileMetadata(fileMetadata, of));
                    log.debug("Written sampling rate and file metadata: " + fileMetadata);
                }
            }
            dataType.add(datat);
        }
    }

    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_ENCODING, encoding);
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    //        m.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, XSDSchema);
    JAXBElement<MeasurationType> me = of.createMeasuration(measType);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    m.marshal(me, baos);
    log.debug("Written XML document into a ByteArrayOutputStream ");
    return baos;
}

From source file:com.bluexml.side.build.tools.reader.MavenProjectReader.java

/**
 * @return/* w  w w  . j  a  v a2s. c  o m*/
 * @throws JAXBException
 * @throws PropertyException
 */

private static Unmarshaller getUnmarshaller(String packageName) throws JAXBException, PropertyException {
    JAXBContext jaxbContext = JAXBContext.newInstance(packageName);

    Marshaller alfrescoMarshaller = jaxbContext.createMarshaller();
    alfrescoMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    alfrescoMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    Unmarshaller alfrescoUnmarshaller = jaxbContext.createUnmarshaller();

    return alfrescoUnmarshaller;
}

From source file:org.javelin.sws.ext.bind.SweJaxbMarshaller.java

@Override
public void setProperty(String name, Object value) throws PropertyException {
    if (Marshaller.JAXB_FORMATTED_OUTPUT.equals(name))
        this.formatting = (Boolean) value;
    else if (Marshaller.JAXB_FRAGMENT.equals(name))
        this.fragment = (Boolean) value;
    else if (Marshaller.JAXB_ENCODING.equals(name))
        this.encoding = (String) value;
    else if (SweJaxbConstants.SWE_MARSHALLER_PROPERTY_JAXB_MULTIREFS.equals(name))
        this.multiRefEncoding = (Boolean) value;
    else if (SweJaxbConstants.SWE_MARSHALLER_PROPERTY_SEND_TYPES.equals(name))
        this.sendTypes = (Boolean) value;
    else/*from   ww w .  ja v  a 2 s .c  o  m*/
        this.properties.put(name, value);
}

From source file:br.gov.frameworkdemoiselle.behave.integration.alm.objects.util.GenerateXMLString.java

public static String getExecutionworkitemString(String urlServer, String projectAreaAlias, String encoding,
        String testCaseId, String testPlanId) throws JAXBException {

    // Workitem/*  ww w  . j a v  a  2 s .c o m*/
    com.ibm.rqm.xml.bind.Executionworkitem.Testcase workTest = new com.ibm.rqm.xml.bind.Executionworkitem.Testcase();
    workTest.setHref(urlServer + "resources/" + projectAreaAlias + "/testcase/" + testCaseId);

    // Testplan
    com.ibm.rqm.xml.bind.Executionworkitem.Testplan testPlan = new com.ibm.rqm.xml.bind.Executionworkitem.Testplan();
    testPlan.setHref(
            urlServer + "resources/" + projectAreaAlias + "/testplan/urn:com.ibm.rqm:testplan:" + testPlanId);

    // Criao do Execution Work Item
    Executionworkitem work = new Executionworkitem();
    work.setFrequency("Once");
    work.setRegression(false);
    work.setTitle("Registro de Execuo Automatizado - Plano de Teste " + testPlanId);
    work.setWeight(100);
    work.setTestcase(workTest);
    work.setTestplan(testPlan);

    JAXBContext jaxb = JAXBContext.newInstance(Executionworkitem.class);
    Marshaller marshaller = jaxb.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
    StringWriter resourceString = new StringWriter();
    marshaller.marshal(work, resourceString);

    return resourceString.toString();
}

From source file:de.intevation.test.irixservice.UploadReportTest.java

@Test(expected = UploadReportException.class)
public void testInvalidDokpool() throws UploadReportException, JAXBException {
    ReportType report = getReportFromFile(VALID_REPORT);
    DokpoolMeta meta = new DokpoolMeta();
    meta.setDokpoolContentType("Invalid doc");
    DOMResult res = new DOMResult();
    Element ele = null;//from w w w.j av a 2  s .co  m
    JAXBContext jaxbContext = JAXBContext.newInstance(DokpoolMeta.class);
    Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
    jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
    jaxbMarshaller.marshal(meta, res);
    ele = ((Document) res.getNode()).getDocumentElement();

    report.getAnnexes().getAnnotation().get(0).getAny().add(ele);
    testObj.uploadReport(report);
}