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.operations.NDVIStatisticsOperation.java

@Override
public Object getBlob(Object inputParam) {

    @SuppressWarnings("unchecked")
    Map<String, String[]> parameters = (Map<String, String[]>) inputParam;
    RESTRunInfo runInfo = null;//from  ww w .j a  v  a 2 s. co  m

    {

        //model.addAttribute("messageType", "POSTED");

        //@SuppressWarnings("unchecked")
        //Map<String, String[]> parameters = request.getParameterMap();

        // create statsBean to create XML
        StatsBean sb = new StatsBean();

        //String message = "Received: ";

        String granule_month = "";
        String granule_dekad = "";

        for (String key : parameters.keySet()) {

            String[] vals = parameters.get(key);

            //for(String val : vals)
            //    message = message.concat(key + " -> "+val+ " \n ");

            if (key.equalsIgnoreCase("region")) {
                if (vals[0].equalsIgnoreCase("default:Province")) {
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.PROVINCE);
                } else if (vals[0].equalsIgnoreCase("default:Districts")) {
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.DISTRICT);
                } else if (vals[0].equalsIgnoreCase("file")) {
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.CUSTOM);
                    // TODO: get the file from the values
                    sb.setClassifierFullPath("/this/is/a/full/path");
                }
            } else if (key.equalsIgnoreCase("mask")) {
                if (vals[0].equalsIgnoreCase("default:CropMask")) {
                    sb.setForestMask(StatsBean.MASK_TYPE.STANDARD);
                } else if (vals[0].equalsIgnoreCase("file")) {
                    sb.setForestMask(StatsBean.MASK_TYPE.CUSTOM);
                    // TODO: get the file from the values
                    sb.setForestMaskFullPath("/a/full/path/for/forest/mask");
                }
            } else if (key.equalsIgnoreCase("month")) {
                // TODO: do this filtering client side
                granule_month = vals[0].substring(2).replace("-", "");
            } else if (key.equalsIgnoreCase("dekad")) {
                granule_dekad = vals[0];
            }
        }

        if (granule_month.length() == 4 && granule_dekad.length() == 1) {
            sb.setNdviFileName(granule_month.concat(granule_dekad));
        } else {
            // TODO throw catch exception
            sb.setNdviFileName("00000");
        }

        JAXB.marshal(sb, System.out);

        try {

            File outputFile = File.createTempFile("input_", ".xml", new File(getGbinputdirString()));
            JAXB.marshal(sb, outputFile);
            runInfo = new RESTRunInfo();
            List<String> fList = new ArrayList<String>();
            // TODO: absolute or relative?
            fList.add(outputFile.getAbsolutePath());
            runInfo.setFileList(fList);

        } catch (IOException e) {
            e.printStackTrace();
        }

        //model.addAttribute("notLocalizedMessage", message);
        //return "common/messages";
    }

    // TODO: create the input xml from a template
    //parameters.get("param1")
    //parameters.get("param2")
    //parameters.get("param3")
    //runInfo.setFileList( List 1,2,3 );

    return runInfo;
}

From source file:it.geosolutions.opensdi.operations.NDVIStatisticsOperation.java

@Override
public Object getBlob(Object inputParam, HttpServletRequest request) {

    @SuppressWarnings("unchecked")
    Map<String, String[]> parameters = (Map<String, String[]>) inputParam;
    RESTRunInfo runInfo = null;// w w  w  .ja v  a2s.  co m

    {
        StatsBean sb = new StatsBean();
        String granule_dekad = "";
        String year = "";
        String month = "";

        for (String key : parameters.keySet()) {

            String[] vals = parameters.get(key);

            if (key.equalsIgnoreCase("region")) {
                if (vals[0].equalsIgnoreCase("default:Province")) {
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.PROVINCE);
                } else if (vals[0].equalsIgnoreCase("default:Districts")) {
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.DISTRICT);
                } else if (vals[0].equalsIgnoreCase("file")) {
                    // TODO: get the file from the values
                    sb.setClassifier(StatsBean.CLASSIFIER_TYPE.CUSTOM);
                    sb.setClassifierFullPath("/this/is/a/full/path");
                }
            } else if (key.equalsIgnoreCase("mask")) {
                if (vals[0].equalsIgnoreCase("default:CropMask")) {
                    sb.setForestMask(StatsBean.MASK_TYPE.STANDARD);
                } else if (vals[0].equalsIgnoreCase("file")) {
                    sb.setForestMask(StatsBean.MASK_TYPE.CUSTOM);
                } else {
                    sb.setForestMask(StatsBean.MASK_TYPE.DISABLED);
                }
            } else if (key.equalsIgnoreCase("month")) {
                month = vals[0];
            } else if (key.equalsIgnoreCase("year")) {
                year = vals[0];
            } else if (key.equalsIgnoreCase("dekad")) {
                granule_dekad = vals[0];
            } else if (key.equalsIgnoreCase("mask_file")) {
                // Get the file from the values and default baseDir
                sb.setForestMaskFullPath("file:" + defaultBaseDir + vals[0]);
            }
        }

        if (year != null && month != null && granule_dekad.length() == 1) {
            sb.setNdviFileName(getNDVIFileName(year, month, granule_dekad));
        } else {
            // TODO throw catch exception
            sb.setNdviFileName("00000");
        }

        JAXB.marshal(sb, System.out);

        try {

            File outputFile = File.createTempFile("input_", ".xml", new File(getGbinputdirString()));
            JAXB.marshal(sb, outputFile);
            runInfo = new RESTRunInfo();
            List<String> fList = new ArrayList<String>();
            // TODO: absolute or relative?
            fList.add(outputFile.getAbsolutePath());
            runInfo.setFileList(fList);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return runInfo;
}

From source file:org.perfrepo.client.PerfRepoClient.java

private void setPostEntity(HttpPost req, Object obj) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    JAXB.marshal(obj, bos);//  www  . j a  v a2s  . co  m
    req.setEntity(new ByteArrayEntity(bos.toByteArray()));
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java

private static String generateSuccess(User user, boolean isNew) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ServiceResponseType value = factory.createServiceResponseType();

    AuthenticationSuccessType success = factory.createAuthenticationSuccessType();
    success.setUser("" + user.getId());
    AttributesType attrs = factory.createAttributesType();
    attrs.setIsFromNewLogin(isNew);//from  w  w w . j  a v  a2s .  co m
    attrs.getAny().add(createElement("name", user.getName()));
    attrs.getAny().add(createElement("surname", user.getSurname()));
    if (user.getAttributeEntities() != null) {
        for (Attribute a : user.getAttributeEntities()) {
            attrs.getAny().add(createElement(a.getKey(), a.getValue()));
        }
    }
    success.setAttributes(attrs);
    value.setAuthenticationSuccess(success);

    JAXBElement<ServiceResponseType> createServiceResponse = factory.createServiceResponse(value);

    JAXB.marshal(createServiceResponse, os);
    return os.toString();
}

From source file:cz.cas.lib.proarc.common.export.archive.PackageBuilder.java

public void build() {
    JAXB.marshal(mets, new File(pkgFolder, METS_FILENAME));
}

From source file:cz.cas.lib.proarc.common.export.desa.DesaServices.java

private Nomenclatures getNomenclaturesCache(DesaConfiguration dc, UserProfile user) {
    File tmpFolder = FileUtils.getTempDirectory();
    File cache = null;/*from   w  w w  . j  av  a 2s  .  co m*/
    String operator = getOperatorName(user, dc);
    if (operator == null || operator.isEmpty()) {
        throw new IllegalStateException("Missing operator! id: " + dc.getServiceId() + ", user: "
                + (user == null ? null : user.getUserName()));
    }
    long expiration = dc.getNomenclatureExpiration();
    if (expiration != 0) {
        synchronized (DesaServices.this) {
            // ensure the filename is platform safe and unique for each operator
            String codeAsFilename = String.valueOf(operator.hashCode() & 0x00000000ffffffffL);
            cache = new File(tmpFolder,
                    String.format("%s.%s.nomenclatures.cache", dc.getServiceId(), codeAsFilename));
            if (cache.exists()
                    && (expiration < 0 || System.currentTimeMillis() - cache.lastModified() < expiration)) {
                return JAXB.unmarshal(cache, Nomenclatures.class);
            }
        }
    }
    String producerCode = getProducerCode(user, dc);
    if (producerCode == null || producerCode.isEmpty()) {
        throw new IllegalStateException("Missing producer code! id: " + dc.getServiceId() + ", user: "
                + (user == null ? null : user.getUserName()));
    }
    DesaClient desaClient = getDesaClient(dc);
    Nomenclatures nomenclatures = desaClient.getNomenclatures(operator, producerCode,
            dc.getNomenclatureAcronyms());
    if (cache != null) {
        synchronized (DesaServices.this) {
            JAXB.marshal(nomenclatures, cache);
        }
    }
    return nomenclatures;
}

From source file:org.sonatype.nexus.plugins.crowd.client.rest.RestClient.java

/**
 * Authenticates a user with crowd. If authentication failed, raises a <code>RemoteException</code>
 * /*  w w w  .  ja  va2  s.  co  m*/
 * @param username
 * @param password
 * @return session token
 * @throws RemoteException
 */
public void authenticate(String username, String password) throws RemoteException {
    HttpClientContext hc = HttpClientContext.create();
    HttpPost post = new HttpPost(crowdServer.resolve("authentication?username=" + urlEncode(username)));

    if (LOG.isDebugEnabled()) {
        LOG.debug("authentication attempt for '{}'", username);
        LOG.debug(post.getURI().toString());
    }

    AuthenticatePost creds = new AuthenticatePost();
    creds.value = password;
    try {
        acceptXmlResponse(post);
        StringWriter writer = new StringWriter();
        JAXB.marshal(creds, writer);
        post.setEntity(EntityBuilder.create().setText(writer.toString())
                .setContentType(ContentType.APPLICATION_XML).setContentEncoding("UTF-8").build());

        enablePreemptiveAuth(post, hc);
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            handleHTTPError(response);
        }

    } catch (IOException | AuthenticationException ioe) {
        handleError(ioe);
    } finally {
        post.releaseConnection();
    }
}

From source file:eu.trentorise.smartcampus.permissionprovider.controller.CASController.java

/**
 * @param string/*w  ww.ja v  a  2 s  . c  o  m*/
 * @return
 * @throws JAXBException 
 */
private static String generateFailure(String code, String codeValue) throws Exception {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ServiceResponseType value = factory.createServiceResponseType();

    AuthenticationFailureType failure = factory.createAuthenticationFailureType();
    failure.setValue(codeValue);
    failure.setCode(code);
    value.setAuthenticationFailure(failure);
    JAXBElement<ServiceResponseType> createServiceResponse = factory.createServiceResponse(value);

    JAXB.marshal(createServiceResponse, os);

    return os.toString();
}

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

@Test
public void testXmlRead() 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 ww  . ja v  a2 s  .c om*/
    assertNotNull(src);
    TestXml resultContent = JAXB.unmarshal(src, TestXml.class);
    assertEquals(content, resultContent);
    long lastModified = editor.getLastModified();
    assertTrue(String.valueOf(lastModified), lastModified != 0 && lastModified < System.currentTimeMillis());
    assertEquals(format, editor.getProfile().getDsFormatURI());
}

From source file:net.di2e.ddf.argo.probe.responder.ProbeHandler.java

/**
 * Generates a XML formatted list of services.
 *
 * @return XML formatted string/*from   ww w .  ja  va  2 s.  co  m*/
 */
private String getXMLServices(List<Service> serviceList, String probeId) {
    LOGGER.debug("Generating an XML-formatted list of services.");

    Services services = new Services();
    services.setProbeID(probeId);
    services.setResponseID("urn:uuid:" + UUID.randomUUID());
    services.getService().addAll(serviceList);

    StringWriter writer = new StringWriter();
    JAXB.marshal(services, writer);
    return writer.toString();
}