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:de.tu_dortmund.ub.api.daia.DaiaOpenUrlEndpoint.java

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

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

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

    try {//w  w w .j  a va  2 s  .co m
        if (ip != null) {

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

                if (ip.matches(range)) {

                    isTUintern = true;
                    break;
                }
            }

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

                for (String exception : exceptions) {

                    if (ip.matches(exception)) {

                        isTUintern = false;
                        break;
                    }
                }
            }

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

                if (ip.matches(range)) {

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

                for (String exception : exceptions) {

                    if (ip.matches(exception)) {

                        isUBintern = false;
                        break;
                    }
                }
            }

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

                if (ip.matches(range)) {

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

        this.logger.error(e.getMessage(), e.getCause());
    }
    this.logger.debug("Where is it from? " + request.getHeader("X-Forwarded-For") + ", " + isTUintern + ", "
            + isUBintern);

    // read query
    StringBuffer jb = new StringBuffer();
    String line = null;
    try {
        BufferedReader reader = request.getReader();

        while ((line = reader.readLine()) != null) {

            jb.append(line);
        }

        this.logger.debug("POST-INPUT: \n\t" + jb);

    } catch (Exception e) {

        this.logger.error(e.getMessage(), e.getCause());
    }

    // 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
    String queryString = null;

    if (jb.length() == 0) {

        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 (jb.toString().contains("__char_set=latin1") || jb.toString().contains("sid=semantics")
                || jb.toString().contains("sid=GBI:wiwi")) {
            this.logger.debug("TEST 'getQueryString': " + URLDecoder.decode(jb.toString(), "ISO-8859-1"));

            queryString = URLDecoder.decode(jb.toString(), "ISO-8859-1");

        } else {
            queryString = URLDecoder.decode(jb.toString(), "UTF-8");
        }

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

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

            String[] tmp = param.split("=");
            try {
                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("")) {

            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No valid {FORMAT} requested.");
        } else {

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

From source file:edu.duke.cabig.c3pr.webservice.helpers.WebServiceRelatedTestCase.java

public static void main(String[] args) throws JAXBException {
    JAXBContext jc = JAXBContext.newInstance(StudyProtocolVersion.class, CD.class);
    Marshaller m = jc.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    final StudyProtocolVersion study = new StudyUtilityImplTest().createStudy();
    JAXBElement<StudyProtocolVersion> jaxbElement = new JAXBElement<StudyProtocolVersion>(
            new QName("http://enterpriseservices.nci.nih.gov/Common", "study"), StudyProtocolVersion.class,
            study);//from w ww  .  j a  va 2  s .  co m
    m.marshal(jaxbElement, System.out);
}

From source file:de.avanux.smartapplianceenabler.semp.webservice.SempController.java

private String marshall(Device2EM device2EM) {
    StringWriter writer = new StringWriter();
    try {// w ww  .j a  va 2s. c  o m
        JAXBContext context = JAXBContext.newInstance(Device2EM.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(device2EM, writer);
        return writer.toString();
    } catch (JAXBException e) {
        logger.error("Error marshalling", e);
    }
    return null;
}

From source file:edu.vt.cs.cnd2xsd.Cnd2XsdConverter.java

private void convert(OutputStream stream) {
    OutputStream fout = stream;/*  www .  j  av a2 s  . c o  m*/
    try {

        SchemaElement schemaRoot = new SchemaElement();

        schemaRoot.setElementFormDefault(FormChoice.QUALIFIED);
        schemaRoot.setTargetNamespace(this.namespace);
        JAXBContext jc = JAXBContext.newInstance(SchemaElement.class);
        Marshaller m = jc.createMarshaller();
        List<OpenAttrs> rootAttrList = schemaRoot.getIncludesAndImportsAndRedefines();
        ElementElement rootElement = new ElementElement();
        QName qname = new QName(this.namespace, this.rootType);
        rootElement.setType(qname);
        rootElement.setName(this.root);
        rootAttrList.add(rootElement);

        //the first level nodes that are children of rsrRoot are those nodes that
        //do not have any parent nodes in the cnd.

        for (NodeType nt : ntypes) {

            log.debug("NodeType:" + nt.getName());

            //check if we already have that node - if we have then update it

            QName name = getQualifiedName(nt.getName());

            ComplexTypeElement ctype = (ComplexTypeElement) getComplexType(rootAttrList, name.getLocalPart(),
                    attrMap.containsKey(nt.getName()) ? attrMap.get(nt.getName()) : null);

            for (NodeType pt : nt.getDeclaredSupertypes()) {
                log.debug("  DeclaredSuperType:" + pt.getName());
                //based on the supertypes we will have to make decisions
                if (attrMap.containsKey(pt.getName())) {
                    //check if we have to create a node
                    String[] attrs = attrMap.get(pt.getName());
                    if (attrs != null) {
                        //get the qualified name
                        QName ename = getQualifiedName(pt.getName());
                        //create a complex type
                        //check if the complex type already there in the rootAttrList
                        ComplexType ctf = findComplexType(rootAttrList, ename.getLocalPart());

                        if (ctf == null) {
                            ctf = new ComplexTypeElement();
                            ctf.setName(ename.getLocalPart());
                            //add the attributes
                            for (String attr : attrs) {
                                Attribute attribute = new Attribute();
                                QName type = new QName(Constants.XML_NAMESPACE, Constants.STRING);
                                attribute.setType(type);
                                attribute.setName(attr);
                                ctf.getAttributesAndAttributeGroups().add(attribute);
                            }

                            //add this complex type to the attribute list of the root element
                            rootAttrList.add(ctf);
                        }

                        //create an element of the above complex type and add as element
                        ElementElement element = new ElementElement();
                        element.setName(ename.getLocalPart());
                        element.setType(new QName(this.namespace, ctf.getName()));
                        element.setMinOccurs(BigInteger.ONE);
                        element.setMaxOccurs("1");
                        //element.setType(new QName(ctf.));
                        //now add this element to the top level complex type's sequence
                        ctype.getSequence().getElementsAndGroupsAndAlls().add(element);

                    }
                }
                //the supertype is not a pre-define type - we then have to add it as an element
                else {

                    QName qn = getQualifiedName(pt.getName());
                    ComplexType ctf = getComplexType(rootAttrList, qn.getLocalPart(),
                            attrMap.containsKey(nt.getName()) ? attrMap.get(nt.getName()) : null);

                    //create an element of the above type and add as element
                    ElementElement element = new ElementElement();
                    element.setName(qn.getLocalPart());
                    element.setType(new QName(this.namespace, ctf.getName()));
                    element.setMinOccurs(BigInteger.ONE);
                    element.setMaxOccurs("1");

                    //element.setType(new QName(ctf.));
                    //now add this element to the top level complex type's sequence
                    ctype.getSequence().getElementsAndGroupsAndAlls().add(element);

                }
            }

            for (NodeDefinition nd : nt.getDeclaredChildNodeDefinitions()) {
                log.debug("  Declared ChildNode Definition:" + nd.getName());
                //check default primary type
                NodeType defaultNT = nd.getDefaultPrimaryType();
                if (defaultNT == null) {
                    log.debug("Default Primary Type for the node:" + nd.getName() + " is null");
                    //look for the primary type
                    NodeType[] nts = nd.getRequiredPrimaryTypes();
                    if (ntypes == null) {
                        log.debug("No required primary type for node:" + nd.getName());
                    } else {
                        defaultNT = nts[0];
                        log.debug("Assuming first primary  type:" + defaultNT.getName() + " for node:"
                                + nd.getName());
                    }

                }
                log.debug("  Default Primary Type Name:" + defaultNT.getName());
                ElementElement element = new ElementElement();
                if (nd.getName().equals("*")) {
                    QName qn = getQualifiedName(defaultNT.getName());
                    ComplexType ct = getComplexType(rootAttrList, qn.getLocalPart(),
                            attrMap.containsKey(nt.getName()) ? attrMap.get(nt.getName()) : null);

                    //QName ename = getQualifiedName(ct.getName());
                    element.setName(ct.getName());
                    element.setType(new QName(this.namespace, ct.getName()));
                    element.setMinOccurs(nd.isMandatory() ? BigInteger.ONE : BigInteger.ZERO);
                    //add an attribute called nodename so that it can be used to identify the node
                    QName type = new QName(Constants.XML_NAMESPACE, Constants.STRING);
                    Attribute attribute = new Attribute();
                    attribute.setType(type);
                    attribute.setName("nodename");
                    ct.getAttributesAndAttributeGroups().add(attribute);

                    if (nd.allowsSameNameSiblings()) {
                        element.setMaxOccurs(Constants.UNBOUNDED);
                    }

                } else {

                    QName qn = getQualifiedName(defaultNT.getName());
                    ComplexType ct = getComplexType(rootAttrList, qn.getLocalPart(),
                            attrMap.containsKey(nt.getName()) ? attrMap.get(nt.getName()) : null);

                    QName ename = getQualifiedName(nd.getName());
                    element.setName(ename.getLocalPart());
                    element.setType(new QName(this.namespace, ct.getName()));
                    element.setMinOccurs(nd.isMandatory() ? BigInteger.ONE : BigInteger.ZERO);

                    if (nd.allowsSameNameSiblings()) {
                        element.setMaxOccurs(Constants.UNBOUNDED);
                    }

                }
                ctype.getSequence().getElementsAndGroupsAndAlls().add(element);

            }

            for (PropertyDefinition pDef : nt.getPropertyDefinitions()) {
                log.debug("    Attr Name:" + pDef.getName());
                log.debug("    Req type:" + pDef.getRequiredType());
                log.debug("    Declaring Node type:" + pDef.getDeclaringNodeType().getName());
                if (pDef.getDeclaringNodeType().getName().equals(nt.getName())) {

                    QName qn = getQualifiedName(pDef.getName());
                    if (!pDef.isMultiple()) {
                        Attribute attr = new Attribute();
                        if (isUnsupportedType(pDef.getRequiredType())) {
                            attr.setType(new QName(Constants.XML_NAMESPACE, Constants.STRING));

                        } else {
                            attr.setType(new QName(Constants.XML_NAMESPACE,
                                    PropertyType.nameFromValue(pDef.getRequiredType()).toLowerCase()));
                        }
                        attr.setName(qn.getLocalPart());
                        //handle default value
                        Value[] defaultValues = pDef.getDefaultValues();
                        if (defaultValues != null && defaultValues.length > 0) {
                            attr.setDefault(defaultValues[0].getString());
                        }

                        ctype.getAttributesAndAttributeGroups().add(attr);
                    } else {
                        ComplexType ctf = getComplexType(rootAttrList, qn.getLocalPart(),
                                attrMap.containsKey(nt.getName()) ? attrMap.get(nt.getName()) : null);
                        if (ctf != null) {
                            ElementElement element = new ElementElement();
                            element.setName(qn.getLocalPart());
                            element.setMinOccurs(BigInteger.ZERO);
                            element.setMaxOccurs(Constants.UNBOUNDED);
                            if (isUnsupportedType(pDef.getRequiredType())) {
                                element.setType(new QName(Constants.XML_NAMESPACE, Constants.STRING));

                            } else {
                                element.setType(new QName(Constants.XML_NAMESPACE,
                                        PropertyType.nameFromValue(pDef.getRequiredType()).toLowerCase()));
                            }
                            ctf.getSequence().getElementsAndGroupsAndAlls().add(element);

                        }

                        //now create an element of the above type
                        ElementElement element = new ElementElement();
                        element.setName(qn.getLocalPart());
                        element.setType(new QName(this.namespace, ctf.getName()));
                        ctype.getSequence().getElementsAndGroupsAndAlls().add(element);

                    }

                }

            }

        }
        //decide what to put under rootNode

        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        //fout = new FileOutputStream(fileName);
        m.marshal(schemaRoot, fout);

    } catch (Exception ex) {
        log.debug("Exception:" + ex.getMessage());
        ex.printStackTrace();
    } finally {
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException ex) {
                log.error("Exception caught: {}", ex.getMessage());
            }
        }
    }

}

From source file:ca.phon.ipamap.IpaMap.java

/**
 * Saves the favorites data/*w w  w.j  a  v a  2  s.  c  om*/
 * 
 */
private static void saveFavData() throws IOException {
    final ObjectFactory factory = new ObjectFactory();
    final IpaGrids favMap = getFavData();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
        final JAXBContext ctx = JAXBContext.newInstance(factory.getClass());
        final Marshaller marshaller = ctx.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);

        marshaller.marshal(favMap, bos);

        PrefHelper.getUserPreferences().put(FAVORITES_PROP, bos.toString("UTF-8"));
    } catch (JAXBException e) {
        e.printStackTrace();
        throw new IOException(e);
    }
}

From source file:io.fabric8.cxf.endpoint.ManagedApi.java

@ManagedOperation(description = "get xml payload from json payload", currencyTimeLimit = 60)
public String jsonToXml(String jsonText, String pojoType) {
    ObjectMapper objectMapper = new ObjectMapper();
    StringWriter sw = new StringWriter();
    try {//from  www  . ja  va2 s  . co  m
        Object pojo = objectMapper.readValue(jsonText, findClass(pojoType));
        JAXBContext jc = JAXBContext.newInstance(findClass(pojoType));
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(pojo, sw);
    } catch (Exception e) {
        LOG.log(Level.WARNING, "jsonToXml failed.", e);
    }

    return sw.toString();
}

From source file:it.cnr.icar.eric.server.interfaces.rest.URLHandler.java

/**
 * Writes XML RepositoryItems as a RepositoryItemList. Ignores any other
 * type of RepositoryItem.s/*ww  w  .  j  a  v  a 2s.co  m*/
 */
void writeRepositoryItems(List<?> eos) throws IOException, RegistryException, ObjectNotFoundException {
    ServerRequestContext context = new ServerRequestContext("URLHandler.writeRepositoryItem", null);
    ServletOutputStream sout = response.getOutputStream();
    boolean doCommit = false;
    try {
        RepositoryItemListType ebRepositoryItemListType = bu.lcmFac.createRepositoryItemListType();

        Iterator<?> iter = eos.iterator();
        while (iter.hasNext()) {
            ExtrinsicObjectType eo = (ExtrinsicObjectType) iter.next();
            String id = eo.getId();

            RepositoryItem ri = QueryManagerFactory.getInstance().getQueryManager().getRepositoryItem(context,
                    id);

            if (ri == null) {
                throw new ObjectNotFoundException(id,
                        ServerResourceBundle.getInstance().getString("message.repositoryItem"));
            } else {
                if (eo.getMimeType().equals("text/xml")) {
                    DataHandler dataHandler = ri.getDataHandler();
                    InputStream fStream = dataHandler.getInputStream();

                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                    factory.setNamespaceAware(true);
                    DocumentBuilder builder = factory.newDocumentBuilder();
                    Document document = builder.parse(fStream);
                    Element rootElement = document.getDocumentElement();

                    ebRepositoryItemListType.getAny().add(rootElement);
                }
            }
        }
        // javax.xml.bind.Marshaller marshaller =
        // bu.lcmFac.createMarshaller();
        javax.xml.bind.Marshaller marshaller = bu.getJAXBContext().createMarshaller();
        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        JAXBElement<RepositoryItemListType> ebRepositoryItemList = bu.lcmFac
                .createRepositoryItemList(ebRepositoryItemListType);
        marshaller.marshal(ebRepositoryItemList, sout);
        doCommit = true;

    } catch (JAXBException e) {
        throw new RegistryException(e);
    } catch (ParserConfigurationException e) {
        throw new RegistryException(e);
    } catch (SAXException e) {
        throw new RegistryException(e);
    } finally {
        if (sout != null) {
            sout.close();
            sout = null;
        }
        try {
            closeContext(context, doCommit);
        } catch (Exception ex) {
            log.error(ex, ex);
        }
    }
}

From source file:com.hpe.application.automation.tools.octane.executor.UFTTestDetectionService.java

/**
 * Serialize detectionResult to file in XML format
 *
 * @param fileToWriteTo/*from  w w w  .j  a  va  2 s.  co m*/
 * @param taskListenerLog
 * @param detectionResult
 */
public static void publishDetectionResults(File fileToWriteTo, TaskListener taskListenerLog,
        UFTTestDetectionResult detectionResult) {

    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(UFTTestDetectionResult.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        jaxbMarshaller.marshal(detectionResult, fileToWriteTo);

    } catch (JAXBException e) {
        if (taskListenerLog != null) {
            taskListenerLog.error("Failed to persist detection results: " + e.getMessage());
        }
        logger.error("Failed to persist detection results: " + e.getMessage());
    }
}

From source file:gov.va.isaac.config.profiles.UserProfile.java

protected void store(File fileToWrite) throws IOException {
    try {//from www. j  a  va  2 s .  c  o  m
        JAXBContext jaxbContext = JAXBContext.newInstance(UserProfile.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

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

        jaxbMarshaller.marshal(this, fileToWrite);
    } catch (Exception e) {
        throw new IOException("Problem storings UserProfile to " + fileToWrite.getAbsolutePath(), e);
    }
}

From source file:ca.phon.session.io.xml.v12.XMLSessionWriter_v12.java

@Override
public void writeSession(Session session, OutputStream out) throws IOException {
    final JAXBElement<SessionType> ele = toSessionType(session);

    try {//from   w  ww  . ja v a  2s .  com
        final JAXBContext context = JAXBContext.newInstance(ObjectFactory.class);
        final Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        marshaller.marshal(ele, out);
    } catch (JAXBException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
}