Example usage for javax.xml.bind Marshaller JAXB_FORMATTED_OUTPUT

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

Introduction

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

Prototype

String JAXB_FORMATTED_OUTPUT

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

Click Source Link

Document

The name of the property used to specify whether or not the marshalled XML data is formatted with linefeeds and indentation.

Usage

From source file:at.gv.egovernment.moa.id.configuration.struts.action.ImportExportAction.java

public String downloadXMLConfig() {
    try {//  ww w .  j a v a  2 s .  c o  m
        populateBasicInformations();

    } catch (BasicActionException e) {
        return Constants.STRUTS_ERROR;

    }

    Object formidobj = session.getAttribute(Constants.SESSION_FORMID);
    if (formidobj != null && formidobj instanceof String) {
        String formid = (String) formidobj;
        if (!formid.equals(formID)) {
            log.warn("FormIDs does not match. Some suspect Form is received from user "
                    + authUser.getFamilyName() + authUser.getGivenName() + authUser.getUserID());
            return Constants.STRUTS_ERROR;
        }
    } else {
        log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName()
                + authUser.getGivenName() + authUser.getUserID());
        return Constants.STRUTS_ERROR;
    }
    session.setAttribute(Constants.SESSION_FORMID, null);

    if (authUser.isAdmin()) {

        log.info("Write MOA-ID 2.x xml config");
        JAXBContext jc;
        try {
            jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config");

            Marshaller m = jc.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            //               File test = new File(xmlconfigout);
            //               m.marshal(moaidconfig, test);
            MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration();

            if (moaidconfig == null) {
                log.info("No MOA-ID 2.x configruation available");
                addActionError(LanguageHelper.getErrorString("errors.importexport.export.noconfig", request));

                formID = Random.nextRandom();
                session.setAttribute(Constants.SESSION_FORMID, formID);
                return Constants.STRUTS_ERROR_VALIDATION;
            }

            List<OnlineApplication> oaconfigs = ConfigurationDBRead.getAllOnlineApplications();
            moaidconfig.setOnlineApplication(oaconfigs);

            StringWriter writer = new StringWriter();
            m.marshal(moaidconfig, writer);
            fileInputStream = IOUtils.toInputStream(writer.toString(), "UTF-8");

        } catch (JAXBException e) {
            log.info("MOA-ID 2.x configruation could not be exported into a XML file.", e);
            addActionError(LanguageHelper.getErrorString("errors.importexport.export",
                    new Object[] { e.getMessage() }, request));

            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);
            return Constants.STRUTS_ERROR_VALIDATION;
        } catch (IOException e) {
            log.info("MOA-ID 2.x configruation could not be exported into a XML file.", e);
            addActionError(LanguageHelper.getErrorString("errors.importexport.export",
                    new Object[] { e.getMessage() }, request));

            formID = Random.nextRandom();
            session.setAttribute(Constants.SESSION_FORMID, formID);
            return Constants.STRUTS_ERROR_VALIDATION;
        }

        finally {
            ConfigurationDBUtils.closeSession();
        }

        //set new formID
        formID = Random.nextRandom();
        session.setAttribute(Constants.SESSION_FORMID, formID);

        return Constants.STRUTS_SUCCESS;
    } else {
        log.info("No access to Import/Export for User with ID" + authUser.getUserID());
        addActionError(LanguageHelper.getErrorString("errors.notallowed", request));
        return Constants.STRUTS_NOTALLOWED;
    }
}

From source file:com.t2tierp.controller.nfe.CancelaNfe.java

private String xmlCancelamento(br.inf.portalfiscal.nfe.retevento.TRetEnvEvento retorno, String versaoDados,
        String codigoUf, String ambiente, String chaveAcesso, String numeroProtocolo, String justificativa,
        String cnpj, String dataHoraEvento) throws Exception {
    TProcEvento xml = new TProcEvento();
    xml.setVersao(versaoDados);/*from   w w  w .ja  v  a2 s  .  c  o  m*/

    TEvento evento = new TEvento();
    xml.setEvento(evento);
    TEvento.InfEvento infEvento = new TEvento.InfEvento();
    evento.setInfEvento(infEvento);
    evento.setVersao(versaoDados);
    TEvento.InfEvento.DetEvento detEvento = new TEvento.InfEvento.DetEvento();
    infEvento.setDetEvento(detEvento);

    infEvento.setCNPJ(cnpj);
    infEvento.setCOrgao(codigoUf);
    infEvento.setChNFe(chaveAcesso);
    infEvento.setDhEvento(dataHoraEvento);
    infEvento.setId("ID" + "110111" + chaveAcesso + "01");
    infEvento.setNSeqEvento("1");
    infEvento.setTpAmb(ambiente);
    infEvento.setTpEvento("110111");
    infEvento.setVerEvento(versaoDados);

    detEvento.setDescEvento("Cancelamento");
    detEvento.setNProt(numeroProtocolo);
    detEvento.setVersao(versaoDados);
    detEvento.setXJust(justificativa);

    br.inf.portalfiscal.nfe.procevento.TRetEvento retEvento = new br.inf.portalfiscal.nfe.procevento.TRetEvento();
    xml.setRetEvento(retEvento);
    br.inf.portalfiscal.nfe.procevento.TRetEvento.InfEvento retInfEvento = new br.inf.portalfiscal.nfe.procevento.TRetEvento.InfEvento();
    retEvento.setInfEvento(retInfEvento);

    retEvento.setVersao(retorno.getVersao());
    retInfEvento.setCPFDest(retorno.getRetEvento().get(0).getInfEvento().getCPFDest());
    retInfEvento.setCNPJDest(retorno.getRetEvento().get(0).getInfEvento().getCNPJDest());
    retInfEvento.setCOrgao(retorno.getRetEvento().get(0).getInfEvento().getCOrgao());
    retInfEvento.setCStat(retorno.getRetEvento().get(0).getInfEvento().getCStat());
    retInfEvento.setChNFe(retorno.getRetEvento().get(0).getInfEvento().getChNFe());
    retInfEvento.setDhRegEvento(retorno.getRetEvento().get(0).getInfEvento().getDhRegEvento());
    retInfEvento.setEmailDest(retorno.getRetEvento().get(0).getInfEvento().getEmailDest());
    retInfEvento.setId(retorno.getRetEvento().get(0).getInfEvento().getId());
    retInfEvento.setNProt(retorno.getRetEvento().get(0).getInfEvento().getNProt());
    retInfEvento.setNSeqEvento(retorno.getRetEvento().get(0).getInfEvento().getNSeqEvento());
    retInfEvento.setTpAmb(retorno.getRetEvento().get(0).getInfEvento().getTpAmb());
    retInfEvento.setTpEvento(retorno.getRetEvento().get(0).getInfEvento().getTpEvento());
    retInfEvento.setVerAplic(retorno.getRetEvento().get(0).getInfEvento().getVerAplic());
    retInfEvento.setXEvento(retorno.getRetEvento().get(0).getInfEvento().getXEvento());
    retInfEvento.setXMotivo(retorno.getRetEvento().get(0).getInfEvento().getXMotivo());

    JAXBContext jc = JAXBContext.newInstance("br.inf.portalfiscal.nfe.procevento");
    Marshaller marshaller = jc.createMarshaller();

    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, false);
    JAXBElement<TProcEvento> element = new br.inf.portalfiscal.nfe.procevento.ObjectFactory()
            .createProcEventoNFe(xml);

    StringWriter writer = new StringWriter();
    marshaller.marshal(element, writer);

    return writer.toString();
}

From source file:hydrograph.ui.graph.debugconverter.DebugConverter.java

public void marshall(Debug debug, IFile outPutFile) throws JAXBException, IOException, CoreException {

    JAXBContext jaxbContext = JAXBContext.newInstance(Debug.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    marshaller.marshal(debug, out);//from w  ww  .j  a va2 s  .  co  m

    if (outPutFile.exists())
        outPutFile.setContents(new ByteArrayInputStream(out.toByteArray()), true, false, null);
    else
        outPutFile.create(new ByteArrayInputStream(out.toByteArray()), true, null);
    out.close();
}

From source file:esg.node.components.registry.RegistrationGleaner.java

public synchronized boolean saveRegistration(Registration registration, boolean doChecks) {
    boolean success = false;
    if (registration == null) {
        log.error("Registration is null ? [" + registration + "]");
        return success;
    }/*from   w ww.j av  a 2s. co m*/
    log.info("Saving registration information to " + registrationPath + this.registrationFile);
    try {
        JAXBContext jc = JAXBContext.newInstance(Registration.class);
        Marshaller m = jc.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        m.marshal(registration, new FileOutputStream(registrationPath + this.registrationFile));
        success = true;
        dirty = false;
    } catch (Exception e) {
        log.error(e);
    }

    //-----------------------------------------------
    //Derivative xml file generation... (NOTE: should be refactored, but in brody mode right now)
    //-----------------------------------------------

    //pull from registry to create las sisters file.
    try {
        String endpoint = null;
        if ((null != (endpoint = props.getProperty("las.service.endpoint")))
                && (new File(props.getProperty("las.service.app.home"))).exists()) {
            LasSistersGleaner lasSisterGleaner = new LasSistersGleaner(props);
            log.trace("My LAS endpoint = [" + endpoint + "]");
            log.trace("Current Registration = [" + registration + "]");
            log.trace("registration has (" + registration.getNode().size() + ") nodes");
            log.trace("lasSisterGleaner=" + lasSisterGleaner);
            lasSisterGleaner.appendToMyLasServersFromRegistration(registration).saveLasServers();
        } else {
            log.warn("Could not get las information to save for some reason");
        }
    } catch (Exception e) {
        log.error(e);
        log.trace("props=" + props);
        if (log.isTraceEnabled())
            e.printStackTrace();
    }

    //pull from registry to create idp whilelist file.
    try {
        IdpWhitelistGleaner idpWhitelistGleaner = new IdpWhitelistGleaner(props);
        log.trace("registration=" + registration);
        log.trace("idpWhitelistGleaner=" + idpWhitelistGleaner);
        idpWhitelistGleaner.appendToMyIdpWhitelistFromRegistration(registration).saveIdpWhitelist();
    } catch (Exception e) {
        log.error(e);
        log.trace("props=" + props);
        if (log.isTraceEnabled())
            e.printStackTrace();
    }

    //pull from registry to create azs whilelist file.
    try {
        AzsWhitelistGleaner azsWhitelistGleaner = new AzsWhitelistGleaner(props);
        log.trace("registration=" + registration);
        log.trace("azsWhitelistGleaner=" + azsWhitelistGleaner);
        azsWhitelistGleaner.appendToMyAzsWhitelistFromRegistration(registration).saveAzsWhitelist();
    } catch (Exception e) {
        log.error(e);
        log.trace("props=" + props);
        if (log.isTraceEnabled())
            e.printStackTrace();
    }

    //pull from registry to create ats whilelist file.
    try {
        AtsWhitelistGleaner atsWhitelistGleaner = new AtsWhitelistGleaner(props);
        log.trace("registration=" + registration);
        log.trace("atsWhitelistGleaner=" + atsWhitelistGleaner);
        atsWhitelistGleaner.appendToMyAtsWhitelistFromRegistration(registration).saveAtsWhitelist();
    } catch (Exception e) {
        log.error(e);
        log.trace("props=" + props);
        if (log.isTraceEnabled())
            e.printStackTrace();
    }

    //pull from registry to create index shards list file.
    try {
        ShardsListGleaner shardsListGleaner = new ShardsListGleaner(props);
        log.trace("registration=" + registration);
        log.trace("shardsListGleaner=" + shardsListGleaner);
        shardsListGleaner.appendToMyShardsListFromRegistration(registration, doChecks).saveShardsList();
    } catch (Exception e) {
        log.error(e);
        log.trace("props=" + props);
        if (log.isTraceEnabled())
            e.printStackTrace();
    }

    return success;
}

From source file:org.finra.dm.tools.common.databridge.DataBridgeWebClient.java

/**
 * Registers business object data with the Data Management Service.
 *
 * @param manifest the uploader input manifest file
 * @param s3FileTransferRequestParamsDto the S3 file transfer request parameters to be used to retrieve local path and S3 key prefix values
 * @param storageName the storage name//from w w w.j a  va  2  s  . c o m
 * @param createNewVersion if not set, only initial version of the business object data is allowed to be created
 *
 * @return the business object data returned by the Data Management Service.
 * @throws IOException if an I/O error was encountered.
 * @throws JAXBException if a JAXB error was encountered.
 * @throws URISyntaxException if a URI syntax error was encountered.
 */
@SuppressFBWarnings(value = "VA_FORMAT_STRING_USES_NEWLINE", justification = "We will use the standard carriage return character.")
public BusinessObjectData registerBusinessObjectData(UploaderInputManifestDto manifest,
        S3FileTransferRequestParamsDto s3FileTransferRequestParamsDto, String storageName,
        Boolean createNewVersion) throws IOException, JAXBException, URISyntaxException {
    LOGGER.info("Registering business object data with the Data Management Service...");

    StorageUnitCreateRequest storageUnit = new StorageUnitCreateRequest();
    storageUnit.setStorageName(storageName);

    List<StorageFile> storageFiles = new ArrayList<>();
    storageUnit.setStorageFiles(storageFiles);

    String localPath = s3FileTransferRequestParamsDto.getLocalPath();
    String s3KeyPrefix = s3FileTransferRequestParamsDto.getS3KeyPrefix();
    List<ManifestFile> localFiles = manifest.getManifestFiles();

    for (ManifestFile manifestFile : localFiles) {
        StorageFile storageFile = new StorageFile();
        storageFiles.add(storageFile);
        // Since the S3 key prefix represents a directory it is expected to contain a trailing '/' character.
        storageFile.setFilePath((s3KeyPrefix + manifestFile.getFileName()).replaceAll("\\\\", "/"));
        storageFile.setFileSizeBytes(Paths.get(localPath, manifestFile.getFileName()).toFile().length());
        storageFile.setRowCount(manifestFile.getRowCount());
    }

    BusinessObjectDataCreateRequest request = new BusinessObjectDataCreateRequest();
    request.setNamespace(manifest.getNamespace());
    request.setBusinessObjectDefinitionName(manifest.getBusinessObjectDefinitionName());
    request.setBusinessObjectFormatUsage(manifest.getBusinessObjectFormatUsage());
    request.setBusinessObjectFormatFileType(manifest.getBusinessObjectFormatFileType());
    request.setBusinessObjectFormatVersion(Integer.parseInt(manifest.getBusinessObjectFormatVersion()));
    request.setPartitionKey(manifest.getPartitionKey());
    request.setPartitionValue(manifest.getPartitionValue());
    request.setSubPartitionValues(manifest.getSubPartitionValues());
    request.setCreateNewVersion(createNewVersion);

    List<StorageUnitCreateRequest> storageUnits = new ArrayList<>();
    request.setStorageUnits(storageUnits);
    storageUnits.add(storageUnit);

    // Add business object data attributes, if any.
    if (manifest.getAttributes() != null) {
        List<Attribute> attributes = new ArrayList<>();
        request.setAttributes(attributes);

        for (Map.Entry<String, String> entry : manifest.getAttributes().entrySet()) {
            Attribute attribute = new Attribute();
            attributes.add(attribute);
            attribute.setName(entry.getKey());
            attribute.setValue(entry.getValue());
        }
    }

    // Add business object data parents, if any.
    request.setBusinessObjectDataParents(manifest.getBusinessObjectDataParents());

    // Create a JAXB context and marshaller
    JAXBContext requestContext = JAXBContext.newInstance(BusinessObjectDataCreateRequest.class);
    Marshaller requestMarshaller = requestContext.createMarshaller();
    requestMarshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
    requestMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    StringWriter sw = new StringWriter();
    requestMarshaller.marshal(request, sw);

    BusinessObjectData businessObjectData;
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        URI uri = new URIBuilder().setScheme(getUriScheme())
                .setHost(dmRegServerAccessParamsDto.getDmRegServerHost())
                .setPort(dmRegServerAccessParamsDto.getDmRegServerPort())
                .setPath(DM_APP_REST_URI_PREFIX + "/businessObjectData").build();
        HttpPost post = new HttpPost(uri);

        post.addHeader("Content-Type", "application/xml");
        post.addHeader("Accepts", "application/xml");

        // If SSL is enabled, set the client authentication header.
        if (dmRegServerAccessParamsDto.getUseSsl()) {
            post.addHeader(getAuthorizationHeader());
        }

        post.setEntity(new StringEntity(sw.toString()));

        LOGGER.info(String.format("    HTTP POST URI: %s", post.getURI().toString()));
        LOGGER.info(String.format("    HTTP POST Headers: %s", Arrays.toString(post.getAllHeaders())));
        LOGGER.info(String.format("    HTTP POST Entity Content:\n%s", sw.toString()));

        businessObjectData = getBusinessObjectData(httpClientOperations.execute(client, post),
                "register business object data with the Data Management Service");
    }

    LOGGER.info("Successfully registered business object data with the Data Management Service.");

    // getBusinessObjectData() might return a null. That happens when the web client gets status code 200 back from
    // the service (data registration is a success), but it fails to retrieve or deserialize the actual HTTP response.
    // Please note that processXmlHttpResponse() is responsible for logging the exception info as a warning.
    if (businessObjectData != null) {
        LOGGER.info("    ID: " + businessObjectData.getId());
    }

    return businessObjectData;
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.LicenseModuleRestWSTester.java

@SuppressWarnings("all")
private static void testGetUsersGroups() throws Exception {

    GetUserGroupsInputDTO input = new GetUserGroupsInputDTO();
    input.setAttributes(createUserObjAttributeDTO());
    input.setLocale("da");
    JAXBContext context = JAXBContext.newInstance(GetUserGroupsInputDTO.class);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(input, outputStream);/*from   w  ww .  j  a v a  2 s .c  om*/

    // serialize to XML
    String inputXML = outputStream.toString();
    System.out.println("input xml:\n" + inputXML);

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    WebResource service = client
            .resource(UriBuilder.fromUri("http://localhost:8080/licensemodule/services/").build());
    // Call with XML
    //GetUsersLicensesOutputDTO output = service.path("getUserLicenses").type(MediaType.TEXT_XML).accept(MediaType.TEXT_XML).entity(inputXML).post(GetUsersLicensesOutputDTO.class);

    // Call with @XmlRootElement
    GetUserGroupsOutputDTO output = service.path("getUserGroups").type(MediaType.TEXT_XML)
            .accept(MediaType.TEXT_XML).entity(input).post(GetUserGroupsOutputDTO.class);

    context = JAXBContext.newInstance(GetUserGroupsOutputDTO.class);
    outputStream = new ByteArrayOutputStream();
    m = context.createMarshaller();

    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    m.marshal(output, outputStream);

    // serialize to XML
    String outputXML = outputStream.toString();
    System.out.println(outputXML);

    System.out.println("output, groups:" + output.getGroups());
}

From source file:edu.kit.dama.rest.util.RestClientUtils.java

/**
 * Deserializes an entity from a stream provided by a ClientResponse.
 * <b>Attention:</b>May throw a DeserializationException if the
 * deserialization fails for some reason.
 *
 * @param <C> entity class//w w w  .  java  2  s  . c o m
 * @param pEntityClass An array of classes needed to deserialize the entity.
 * @param pResponse The response which provides the entity input stream.
 *
 * @return The object.
 */
public static <C> C createObjectFromStream(final Class[] pEntityClass, final ClientResponse pResponse) {
    C returnValue = null;
    if (pEntityClass != null) {
        LOGGER.debug("createObjectFromStream");
        try {
            Unmarshaller unmarshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass)
                    .createUnmarshaller();
            returnValue = (C) unmarshaller.unmarshal(getInputStream(pResponse.getEntityInputStream()));
            if (LOGGER.isDebugEnabled()) {
                Marshaller marshaller = org.eclipse.persistence.jaxb.JAXBContext.newInstance(pEntityClass)
                        .createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                StringWriter sw = new StringWriter();
                marshaller.marshal(returnValue, sw);
                LOGGER.debug("createObjectFromStream: " + sw.toString());
            }
        } catch (JAXBException ex) {
            throw new DeserializationException("Failed to deserialize object from response " + pResponse, ex);
        }
    } else {
        LOGGER.debug("No response expected!");
    }
    return returnValue;
}

From source file:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String ips = request.getHeader("X-Forwarded-For");

    boolean isTUintern = false;
    boolean isUBintern = false;
    boolean is52bIBA = false;

    try {/* w  ww. java  2  s  . c  om*/
        if (ips != null) {

            String[] ranges = config.getProperty("service.iprange.tu").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isTUintern = true;
                    break;
                }
            }

            String[] exceptions = config.getProperty("service.iprange.tu.exceptions").split("\\|");
            if (isTUintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isTUintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub").split("\\|");
            for (String range : ranges) {

                if (ips.matches(range)) {

                    isUBintern = true;
                    break;
                }
            }
            exceptions = config.getProperty("service.iprange.ub.exceptions").split("\\|");
            if (isUBintern) {

                for (String exception : exceptions) {

                    if (ips.matches(exception)) {

                        isUBintern = false;
                        break;
                    }
                }
            }

            ranges = config.getProperty("service.iprange.ub.52bIBAs").split("\\|");
            exceptions = config.getProperty("service.iprange.ub.52bIBAs.exceptions").split("\\|");
            String tmp[] = ips.split(", ");

            for (int i = 1; i < 3; i++) {

                try {
                    String ip = tmp[tmp.length - i];

                    for (String range : ranges) {

                        if (ip.matches(range)) {

                            is52bIBA = true;
                            break;
                        }
                    }

                    if (exceptions.length > 0) {

                        if (is52bIBA) {

                            for (String exception : exceptions) {

                                if (ip.matches(exception)) {

                                    is52bIBA = false;
                                    break;
                                }
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }

        }
    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }
    this.logger.info("[" + this.config.getProperty("service.name") + "] " + "Where is it from? "
            + request.getHeader("X-Forwarded-For") + ", " + isTUintern + ", " + isUBintern + ", " + is52bIBA);

    // format
    String format = "html";

    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerNameKey = headerNames.nextElement();

        if (headerNameKey.equals("Accept")) {

            if (request.getHeader(headerNameKey).contains("text/html")) {
                format = "html";
            } else if (request.getHeader(headerNameKey).contains("application/xml")) {
                format = "xml";
            } else if (request.getHeader(headerNameKey).contains("application/json")) {
                format = "json";
            }
        }
    }

    // read query
    this.logger.debug("TEST 'getQueryString': " + request.getQueryString());

    String queryString = null;
    if (request.getQueryString() == null || request.getQueryString().equals("")) {

        if (format.equals("html")) {

            try {

                JAXBContext context = JAXBContext.newInstance(Daia.class);
                Marshaller m = context.createMarshaller();
                m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                // Write to HttpResponse
                org.jdom2.Document doc = new org.jdom2.Document();
                doc.setRootElement(new Element("daia"));

                HashMap<String, String> parameters = new HashMap<String, String>();
                parameters.put("lang", "de");
                parameters.put("isTUintern", Boolean.toString(isTUintern));
                parameters.put("isUBintern", Boolean.toString(isUBintern));
                parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"), parameters);

                response.setContentType("text/html;charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().println(html);
            } catch (PropertyException e) {
                this.logger.error(e.getMessage(), e.getCause());
            } catch (JAXBException e) {
                this.logger.error(e.getMessage(), e.getCause());
            }
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Query is empty.");
        }
    } else {

        if (request.getQueryString().contains("%26")) {
            this.logger.debug("TEST 'getQueryString': " + request.getQueryString());

            queryString = request.getQueryString().replaceAll("%26", "xXx");
            this.logger.debug("TEST 'getQueryString': " + queryString);

        } else {
            queryString = request.getQueryString();
        }

        if (queryString.contains("%0A")) {

            queryString = queryString.replaceAll("%0A", "");
            this.logger.debug("TEST 'queryString': " + queryString);
        }

        if ((queryString.contains("__char_set=latin1") && !queryString.contains("sid=semantics"))
                || queryString.contains("sid=GBI:wiwi")) {

            queryString = URLDecoder.decode(queryString, "ISO-8859-1");
        } else if (queryString.contains("__char_set=latin1") && queryString.contains("sid=semantics")) {

            // Tue erstmal nix
            this.logger.debug("semantics?");
        } else {
            queryString = URLDecoder.decode(queryString, "UTF-8");
        }

        HashMap<String, String> latinParameters = new HashMap<String, String>();

        for (String param : queryString.split("&")) {

            String[] tmp = param.split("=");
            try {

                if (tmp[1].contains("xXx")) {
                    latinParameters.put(tmp[0], tmp[1].replaceAll("xXx", "&"));
                } else {
                    latinParameters.put(tmp[0], tmp[1]);
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                latinParameters.put(tmp[0], "");
            }

        }

        if (latinParameters.get("format") != null && !latinParameters.get("format").equals("")) {

            format = latinParameters.get("format");
        }

        this.logger.debug("format = " + format);

        // build response
        response.setHeader("Access-Control-Allow-Origin", config.getProperty("Access-Control-Allow-Origin"));

        if (format.equals("")) {

            if (format.equals("html")) {

                try {

                    JAXBContext context = JAXBContext.newInstance(Daia.class);
                    Marshaller m = context.createMarshaller();
                    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

                    // Write to HttpResponse
                    org.jdom2.Document doc = new org.jdom2.Document();
                    doc.setRootElement(new Element("daia"));

                    HashMap<String, String> parameters = new HashMap<String, String>();
                    parameters.put("lang", "de");
                    parameters.put("isTUintern", Boolean.toString(isTUintern));
                    parameters.put("isUBintern", Boolean.toString(isUBintern));
                    parameters.put("is52bIBA", Boolean.toString(is52bIBA));

                    String html = htmlOutputter(doc, this.config.getProperty("linkresolver.html.xslt"),
                            parameters);

                    response.setContentType("text/html;charset=UTF-8");
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.getWriter().println(html);
                } catch (PropertyException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                } catch (JAXBException e) {
                    this.logger.error(e.getMessage(), e.getCause());
                }
            } else {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {FORMAT} requested.");
            }

        } else {

            this.provideService(request, response, format, latinParameters, isTUintern, isUBintern, is52bIBA);
        }
    }
}

From source file:com.prowidesoftware.swift.model.mx.BusinessHeader.java

/**
 * Gets the header as an Element object.
 *  //from w w  w .  j  a va2  s . co  m
 * @return Element this header parsed into Element or null if header is null
 * @since 7.8
 */
public Element element() {
    Object header = null;
    if (this.businessApplicationHeader != null) {
        header = this.businessApplicationHeader;
    } else if (this.applicationHeader != null) {
        header = this.applicationHeader;
    } else {
        return null;
    }
    try {
        JAXBContext context = JAXBContext.newInstance(header.getClass());
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        DOMResult res = new DOMResult();
        marshaller.marshal(_element(header), res);
        Document doc = (Document) res.getNode();
        return (Element) doc.getFirstChild();

    } catch (JAXBException e) {
        log.log(Level.SEVERE, "Error writing XML:" + e + "\n for header: " + header);
    }
    return null;
}

From source file:com.ikon.util.impexp.RepositoryExporter.java

/**
 * Export mail from openkm repository to filesystem.
 *///from ww w  . ja v  a  2 s  .c  o  m
public static ImpExpStats exportMail(String token, String mailPath, String destPath, String metadata,
        Writer out, InfoDecorator deco) throws PathNotFoundException, RepositoryException, DatabaseException,
        IOException, AccessDeniedException, ParseException, NoSuchGroupException, MessagingException {
    MailModule mm = ModuleManager.getMailModule();
    MetadataAdapter ma = MetadataAdapter.getInstance(token);
    Mail mailChild = mm.getProperties(token, mailPath);
    Gson gson = new Gson();
    ImpExpStats stats = new ImpExpStats();
    MimeMessage msg = MailUtils.create(token, mailChild);
    FileOutputStream fos = new FileOutputStream(destPath);
    msg.writeTo(fos);
    IOUtils.closeQuietly(fos);
    FileLogger.info(BASE_NAME, "Created document ''{0}''", mailChild.getPath());

    // Metadata
    if (metadata.equals("JSON")) {
        MailMetadata mmd = ma.getMetadata(mailChild);
        String json = gson.toJson(mmd);
        fos = new FileOutputStream(destPath + Config.EXPORT_METADATA_EXT);
        IOUtils.write(json, fos);
        IOUtils.closeQuietly(fos);
    } else if (metadata.equals("XML")) {
        fos = new FileOutputStream(destPath + ".xml");

        MailMetadata mmd = ma.getMetadata(mailChild);
        JAXBContext jaxbContext;
        try {
            jaxbContext = JAXBContext.newInstance(MailMetadata.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

            // output pretty printed
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(mmd, fos);
        } catch (JAXBException e) {
            log.error(e.getMessage(), e);
            FileLogger.error(BASE_NAME, "XMLException ''{0}''", e.getMessage());
        }
    }

    if (out != null) {
        out.write(deco.print(mailChild.getPath(), mailChild.getSize(), null));
        out.flush();
    }

    // Stats
    stats.setSize(stats.getSize() + mailChild.getSize());
    stats.setMails(stats.getMails() + 1);

    return stats;
}