Example usage for javax.xml.bind JAXB marshal

List of usage examples for javax.xml.bind JAXB marshal

Introduction

In this page you can find the example usage for javax.xml.bind JAXB marshal.

Prototype

public static void marshal(Object jaxbObject, Result xml) 

Source Link

Document

Writes a Java object tree to XML and store it to the specified location.

Usage

From source file:it.geosolutions.geobatch.destination.ingestion.gate.GateIngestionMemoryTest.java

/**
 * Generate a test file with the content tested on
 * {@link TransitBeanTest#TEST_XML}/*from   w w  w  .ja v  a  2  s .c  o  m*/
 * 
 * @return
 * @throws IOException
 */
private File getTestFile(long idGate, int transitNumbers) throws IOException {
    File file = new File(FileUtils.getTempDirectory() + SEPARATOR + "A00_20131016-180030.xml");

    if (!file.exists())
        file.createNewFile();

    ExportData exportData = generateTestData(idGate, transitNumbers);

    JAXB.marshal(exportData, file);

    return file;
}

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

@Override
public void saveAnnotations(String qh1, SelectionListModel ssModel) throws IOException {
    // convert to jaxb
    RegionList rl = new RegionList();
    List<Region> regions = rl.getRegion();
    for (Annotation a : ssModel) {
        System.out.println("saving annotation: " + a);

        Region r = new Region();
        regions.add(r);/*from   w ww .  j av a 2 s .co  m*/

        r.setPath(SlideAnnotation.shapeToString(a.getShape()));

        if (a instanceof SlideAnnotation) {
            SlideAnnotation sa = (SlideAnnotation) a;

            r.setId(sa.getId());

            NoteList nl = new NoteList();
            r.setNotes(nl);
            List<Note> notes = nl.getNote();

            for (SlideAnnotationNote n : sa.getNotes()) {
                Note nn = new Note();
                nn.setId(n.getId());
                nn.setText(n.getText());

                notes.add(nn);
            }
        }
    }

    // marshal it to a string to post
    StringWriter sw = new StringWriter();
    JAXB.marshal(new ObjectFactory().createRegions(rl), sw);

    try {
        String u = new URI(uriPrefix + qh1 + "/").toString();
        System.out.println(u);

        PostMethod post = new PostMethod(u);
        try {
            post.addRequestHeader("Referer", u);
            NameValuePair params[] = { new NameValuePair("xml", sw.toString()),
                    new NameValuePair("csrfmiddlewaretoken", csrftoken) };
            System.out.println(Arrays.toString(params));
            post.setRequestBody(params);

            int code = httpClient.executeMethod(post);
            code = maybeAuthenticate(post, code);

            System.out.println("post code: " + code);
            System.out.println(post.getResponseBodyAsString());
        } finally {
            post.releaseConnection();
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:bigbluej.Client.java

private String toXml(Config config) {
    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(config, stringWriter);
    return stringWriter.getBuffer().toString();
}

From source file:cz.cas.lib.proarc.common.workflow.profile.WorkflowProfilesTest.java

@Test
public void testWriteXml() {
    WorkflowDefinition wf = new WorkflowDefinition();

    MaterialDefinition material1 = new MaterialDefinition().setName("material1");
    material1.getTitles().put("cs", "csMaterialTitle");
    material1.getHints().put("cs", "csMaterialDescription");

    TaskDefinition task1 = new TaskDefinition().setName("task.id1");
    task1.getTitles().put("cs", "kol 1");
    task1.getTitles().put("en", "Task 1");
    task1.getMaterialSetters().add(new SetMaterialDefinition().setMaterial(material1).setWay(Way.INPUT));

    ParamDefinition param1 = new ParamDefinition().setName("param.id1").setRequired(true);
    task1.getParams().add(param1);//w ww.j  a  v a 2s . c  o m

    TaskDefinition task2 = new TaskDefinition().setName("task.id2");

    JobDefinition job = new JobDefinition().setName("job0")
            .setWorker(new WorkerDefinition().setUsername("worker")).setPriority(3).setDisabled(true);
    job.getTitles().put("cs", "csTitle");
    job.getTitles().put("en", "enTitle");
    job.getTitles().put(null, "defaultTitle");
    StepDefinition step1 = new StepDefinition().setTask(task1)
            .setWorker(new WorkerDefinition().setActual(true));
    step1.getParamSetters().add(new SetParamDefinition().setParam(param1).setValue("param1.value"));
    job.getSteps().add(step1);
    StepDefinition step2 = new StepDefinition().setTask(task2)
            .setWorker(new WorkerDefinition().setActual(true));
    step2.getBlockers().add(new BlockerDefinition().setTask(task1));
    job.getSteps().add(step2);
    wf.getJobs().add(job);

    wf.getMaterials().add(material1);

    wf.getTasks().add(task1);
    wf.getTasks().add(task2);

    ValueMapDefinition vmap = new ValueMapDefinition().setId("workflow.valuemap.id1");
    vmap.getItems().add(new ValueMapItemDefinition().setKey("grey").setValue("v edi"));
    wf.getValueMaps().add(vmap);

    JAXB.marshal(wf, System.out);
}

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

@Test
public void testXmlWrite() 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 w w  w  .  j  av  a 2 s.co  m
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);

    // write modification
    String expectedContent = "changed test content";
    resultContent.data = expectedContent;
    editorResult = editor.createResult();
    JAXB.marshal(resultContent, editorResult);
    long lastModified = editor.getLastModified();
    assertEquals(format, editor.getProfile().getDsFormatURI());
    editor.write(editorResult, lastModified, null);
    remote.flush();

    // test current editor
    assertTrue(lastModified < editor.getLastModified());
    long expectLastModified = editor.getLastModified();
    resultContent = JAXB.unmarshal(editor.read(), TestXml.class);
    assertEquals(new TestXml(expectedContent), resultContent);
    assertEquals(format, editor.getProfile().getDsFormatURI());

    // test new editor
    remote = fedora.find(local.getPid());
    editor = new RemoteXmlStreamEditor(remote, dsId);
    src = editor.read();
    assertNotNull(src);
    resultContent = JAXB.unmarshal(src, TestXml.class);
    assertEquals(new TestXml(expectedContent), resultContent);
    long resultLastModified = editor.getLastModified();
    assertEquals(expectLastModified, resultLastModified);
    assertEquals(format, editor.getProfile().getDsFormatURI());
}

From source file:no.digipost.api.useragreements.client.ApiService.java

private static HttpEntity marshallJaxbEntity(final Object obj) {
    ByteArrayOutputStream bao = new ByteArrayOutputStream(1024);
    JAXB.marshal(obj, bao);
    return new ByteArrayEntity(bao.toByteArray());
}

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

@Test(expected = DigitalObjectConcurrentModificationException.class)
public void testXmlWriteConcurrent() throws Exception {
    String dsId = "testId";
    LocalObject local = new LocalStorage().create();
    local.setLabel(test.getMethodName());
    XmlStreamEditor leditor = local.getEditor(FoxmlUtils.inlineProfile(dsId, "testns", "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  av  a 2s  . c o m
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);

    // concurrent write
    RemoteObject concurrentRemote = fedora.find(local.getPid());
    RemoteXmlStreamEditor concurrentEditor = new RemoteXmlStreamEditor(concurrentRemote, dsId);
    TestXml concurrentContent = JAXB.unmarshal(concurrentEditor.read(), TestXml.class);
    concurrentContent.data = "concurrent change";
    EditorResult concurrentResult = concurrentEditor.createResult();
    JAXB.marshal(concurrentContent, concurrentResult);
    concurrentEditor.write(concurrentResult, editor.getLastModified(), null);
    concurrentRemote.flush();

    // write out of date modification
    String expectedContent = "changed test content";
    resultContent.data = expectedContent;
    editorResult = editor.createResult();
    JAXB.marshal(resultContent, editorResult);
    long lastModified = editor.getLastModified();
    editor.write(editorResult, lastModified, null);

    remote.flush();
}

From source file:ca.uhn.hl7v2.testpanel.model.msg.Hl7V2MessageCollection.java

private String exportWrite(XmlFormat xml) {
    StringWriter stringWriter = new StringWriter();
    JAXB.marshal(xml, stringWriter);
    String string = stringWriter.toString();
    return string;
}

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

@Test
public void testGetStreamProfile() 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, support.getTestUser());

    RemoteObject remote = fedora.find(local.getPid());
    List<DatastreamProfile> resultProfiles = remote.getStreamProfile(null);
    assertNotNull(resultProfiles);//from w  w  w .j ava 2  s. co m
    assertEquals(2, resultProfiles.size()); // + DC
    assertEquals(dsId, resultProfiles.get(0).getDsID());
}

From source file:com.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
        throws InterruptedException, IOException {

    final List<OOArg> argsToUse = expand(getArgs(), (AbstractBuild<MatrixProject, MatrixBuild>) build,
            listener);/*from w ww.j ava  2 s  .c  o m*/

    Map<String, String> buildVariables = build.getBuildVariables();
    Set<String> keySet = buildVariables.keySet();

    OOServer selectedOOServer = getOOServer();
    String selectedFlowS = this.selectedFlow;
    for (String key : keySet) {

        if (key.startsWith("i_")) {
            argsToUse.add(new OOArg(key.substring(2), buildVariables.get(key)));
            listener.getLogger().println("adding input " + key.substring(2) + " with value "
                    + buildVariables.get(key) + " from the matrix axis");
        }

        if (key.startsWith("s_")) {
            selectedOOServer = OOAccessibilityLayer.getOOServer(buildVariables.get(key));
        }

        if (key.startsWith("f_")) {
            selectedFlowS = basepath + "/" + buildVariables.get(key);
        }
    }

    Assert.isTrue(selectedOOServer != null, "HP Operations Orchestration Server must be selected");

    listener.getLogger().println("Connected to central with label: [" + selectedOOServer.getUniqueLabel()
            + "], URL: [" + selectedOOServer.getUrl() + "]");
    URL url = new URL(selectedOOServer.getUrl());

    String urlString = StringUtils.slashify(selectedOOServer.getUrl().replace("PAS", "")) + "oo/rest/v1";

    final DescriptorImpl descriptor = getDescriptorStatically();

    if (selectedOOServer.getUsername() != null && selectedOOServer.getUsername().length() > 0) {
        listener.getLogger()
                .println("Authentication will be used, username: " + selectedOOServer.getUsername());
        setEncodedCredentials(selectedOOServer.getUsername(), selectedOOServer.getPassword());
    } else {
        setEncodedCredentials(null, null);
    }

    // get version from Central
    Boolean is9x = OOAccessibilityUtils.isOoVersionLowerThen1010(urlString + "/version");

    // log version
    //listener.getLogger().println("Central version: " + version);
    //listener.getLogger().println("Global Keystore: " + globalKeystore);

    listener.getLogger().println("Running " + selectedFlowS + " on " + selectedOOServer.getUniqueLabel()
            + " with parameters " + argsToUse);

    // legacy invoke of a flow
    if (is9x) {
        OORunRequest runRequest = null;
        OORunResponse ooBuildStepResult = null;
        try {
            runRequest = new OORunRequest(selectedOOServer, new OOFlow(selectedFlowS), argsToUse);

            ooBuildStepResult = OOAccessibilityLayer.run(runRequest);
        } catch (Exception e) {
            e.printStackTrace(listener.getLogger());
            if (abortBuildOnRunFailure) {
                throw new AbortException("build step failed: " + e.getMessage());
            }
        }

        if (ooBuildStepResult != null) {

            listener.getLogger().println("flow results:");
            JAXB.marshal(ooBuildStepResult, listener.getLogger());

            final EnvVars envVars = mapReturnValues(ooBuildStepResult, listener);
            build.addAction(new OOBuildStepResultsEnvironmentInjectionAction(envVars));

            if (ooBuildStepResult.hasReport()) {
                //                    build.addAction(new OOBuildStepResultReportAction(runRequest.getFlow().getId(), ooBuildStepResult.getReportUrl()));
                build.addAction(new OOBuildStepResultReportAction(ooBuildStepResult.getReportUrl()));
            }
            listener.getLogger().println("***" + getRetVariableToCheck() + "***");

            if (getRetVariableToCheck().length() > 0) {

                final String serverReturnedValue = envVars.get(getRetVariableToCheck());
                if (serverReturnedValue == null) {
                    throw new AbortException("could not check value of variable '" + getRetVariableToCheck()
                            + "' - flow execution returned no such variable from the server.\n");
                } else if (getMatchStrategy().matches(serverReturnedValue, getValueToCompareWith())) {
                    listener.getLogger()
                            .println("changing status of build to " + getDesiredResultType() + " because "
                                    + "value of " + getRetVariableToCheck() + " (=" + serverReturnedValue + ") "
                                    + getMatchStrategy() + " " + getValueToCompareWith() + "\n");

                    build.setResult(getDesiredResultType());

                    if (getDesiredResultType().equals(Result.FAILURE)) {
                        throw new AbortException(
                                "Aborting the build because flow failed and FAILURE was chosen.\n");
                    }
                }

            }

            //Set build status according to run status
            if (envVars.get("flowReturnCode").equals("Error")) {
                listener.annotate(new SimpleHtmlNote(
                        "<font color=\"red\"><b>Run ended with status [" + envVars.get("flowReturnCode")
                                + "] changing the build result to " + Result.FAILURE + "</b></font>\n"));
                build.setResult(Result.FAILURE);
            } else if (ExecutionResult.NO_ACTION_TAKEN
                    .equals(envVars.get("flowReturnCode").equals("No Action"))) {
                listener.annotate(new SimpleHtmlNote(
                        "<font color=\"yellow\"><b>Run ended with status [" + envVars.get("flowReturnCode")
                                + "] changing the build result to " + Result.UNSTABLE + "</b></font>\n"));
                build.setResult(Result.UNSTABLE);
            }

        }
    } else {

        // post 10.10 invoke of a flow
        // get UUID of the selected flow

        String selectedFlowUUID = OOAccessibilityUtils.getFlowID10x(selectedFlowS,
                urlString + "/flows/library");
        listener.getLogger()
                .println("The flow: " + selectedFlowS + " with UUID " + selectedFlowUUID + " is executing...");
        listener.getLogger().getClass();
        OOAccessibilityLayer ooAccessibilityLayer = new OOAccessibilityLayer();

        String runName = resolveParametersInString(build, listener, this.runName);

        //trigger the flow
        TriggeredExecutionDetailsVO triggeredExecutionDetailsVO = ooAccessibilityLayer.run10x(selectedFlowUUID,
                argsToUse, urlString, stepExecutionTimeout, listener, runName);

        //Create report with link to run on OO
        build.addAction(new OOBuildStepResultReportAction(ooAccessibilityLayer.runURL));

        //Wait for completion
        WaitExecutionResult waitExecutionResult = ooAccessibilityLayer
                .waitExecutionComplete(triggeredExecutionDetailsVO, stepExecutionTimeout, listener, urlString);

        //get step log
        List<StepLog> stepLog = ooAccessibilityLayer.getStepLog(waitExecutionResult.getStepCount(),
                triggeredExecutionDetailsVO.getFeedUrl());

        //Handle build result
        if (waitExecutionResult.isTimedOut()) {//if timed out
            listener.annotate(new SimpleHtmlNote(
                    "\n<font color=\"red\"><b>Timeout failure: The execution was not completed in the allotted time.\nLast status was: "
                            + waitExecutionResult.getLastExecutionStatus() + " </b></font> \n\n"));
            build.setResult(Result.FAILURE);
        } else {//No time out
            listener.getLogger()
                    .println("Run ended with status [" + waitExecutionResult.getFullStatusName() + "]");
            if (!ExecutionStatusState.COMPLETED.equals(waitExecutionResult.getLastExecutionStatus())) {//If flow wasn't completed
                listener.annotate(new SimpleHtmlNote(
                        "<font color=\"red\"><b>Run was not completed, changing the build result to "
                                + Result.FAILURE + "</b></font>\n"));

                build.setResult(Result.FAILURE);
            } else {//flow was completed
                    //Set build status according to run outputs
                if (stepLog.size() > 0) {
                    StepLog lastStep = stepLog.get(stepLog.size() - 1);
                    Map<String, String> lastRawResults = lastStep.getRawResult();
                    if (lastRawResults != null && lastRawResults.get(getRetVariableToCheck()) != null
                            && !getRetVariableToCheck().isEmpty()) { //if run has the expected output
                        if (getMatchStrategy().matches(lastRawResults.get(getRetVariableToCheck()),
                                getValueToCompareWith())) {
                            listener.getLogger().println("changing status of build to " + getDesiredResultType()
                                    + " because " + "value of " + getRetVariableToCheck() + " ("
                                    + lastRawResults.get(getRetVariableToCheck()) + ") " + getMatchStrategy()
                                    + " expected value of " + getValueToCompareWith());

                            build.setResult(getDesiredResultType());
                        }
                    } else if (!getRetVariableToCheck().isEmpty()) { //flow output is empty or output wasn't found
                        listener.annotate(
                                new SimpleHtmlNote("<font color=\"red\"><b>could not check value of variable '"
                                        + getRetVariableToCheck()
                                        + "' - flow execution returned no such variable from the server.</b></font>\n"));
                    }
                }
                //Set build status according to run status
                if (ExecutionResult.ERROR.equals(waitExecutionResult.getLastExecutionResult())) {
                    //Print stack trace
                    List<StepLog> stackTrace = ooAccessibilityLayer.createStackTrace(stepLog, "0");
                    listener.annotate(new SimpleHtmlNote(ooAccessibilityLayer.stackTraceAsString(stackTrace)));

                    listener.annotate(new SimpleHtmlNote("<font color=\"red\"><b>Run ended with status ["
                            + waitExecutionResult.getLastExecutionResult() + "] changing the build result to "
                            + Result.FAILURE + "</b></font>\n"));
                    build.setResult(Result.FAILURE);
                } else if (ExecutionResult.NO_ACTION_TAKEN
                        .equals(waitExecutionResult.getLastExecutionResult())) {
                    listener.annotate(new SimpleHtmlNote("<font color=\"yellow\"><b>Run ended with status ["
                            + waitExecutionResult.getLastExecutionResult() + "] changing the build result to "
                            + Result.UNSTABLE + "</b></font>\n"));
                    build.setResult(Result.UNSTABLE);
                }
            }
        }

        //print the steps (convert step log to json)
        //            listener.annotate(new SimpleHtmlNote(ooAccessibilityLayer.formatResult(jsonExecutionResult)));

    }

    return true;
}