Example usage for javax.xml.stream XMLStreamWriter flush

List of usage examples for javax.xml.stream XMLStreamWriter flush

Introduction

In this page you can find the example usage for javax.xml.stream XMLStreamWriter flush.

Prototype

public void flush() throws XMLStreamException;

Source Link

Document

Write any cached data to the underlying output mechanism.

Usage

From source file:org.activiti.bpmn.converter.BpmnXMLConverter.java

public byte[] convertToXML(BpmnModel model, String encoding) {
    try {// w w w  .  ja v  a2 s .  c om

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStreamWriter out = new OutputStreamWriter(outputStream, encoding);

        XMLStreamWriter writer = xof.createXMLStreamWriter(out);
        XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

        DefinitionsRootExport.writeRootElement(model, xtw, encoding);
        SignalAndMessageDefinitionExport.writeSignalsAndMessages(model, xtw);
        PoolExport.writePools(model, xtw);

        for (Process process : model.getProcesses()) {

            if (process.getFlowElements().size() == 0 && process.getLanes().size() == 0) {
                // empty process, ignore it 
                continue;
            }

            ProcessExport.writeProcess(process, xtw);

            for (FlowElement flowElement : process.getFlowElements()) {
                createXML(flowElement, model, xtw);
            }

            for (Artifact artifact : process.getArtifacts()) {
                createXML(artifact, model, xtw);
            }

            // end process element
            xtw.writeEndElement();
        }

        BPMNDIExport.writeBPMNDI(model, xtw);

        // end definitions root element
        xtw.writeEndElement();
        xtw.writeEndDocument();

        xtw.flush();

        outputStream.close();

        xtw.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        LOGGER.error("Error writing BPMN XML", e);
        throw new XMLException("Error writing BPMN XML", e);
    }
}

From source file:org.activiti.dmn.xml.converter.DmnXMLConverter.java

public byte[] convertToXML(DmnDefinition model, String encoding) {
    try {//w  w  w  .  j a  v  a  2  s  .  c  o  m

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        XMLOutputFactory xof = XMLOutputFactory.newInstance();
        OutputStreamWriter out = new OutputStreamWriter(outputStream, encoding);

        XMLStreamWriter writer = xof.createXMLStreamWriter(out);
        XMLStreamWriter xtw = new IndentingXMLStreamWriter(writer);

        xtw.writeStartElement(ELEMENT_DEFINITIONS);
        xtw.writeDefaultNamespace(DMN_NAMESPACE);
        xtw.writeAttribute(ATTRIBUTE_ID, model.getId());
        if (StringUtils.isNotEmpty(model.getName())) {
            xtw.writeAttribute(ATTRIBUTE_NAME, model.getName());
        }
        xtw.writeAttribute(ATTRIBUTE_NAMESPACE, MODEL_NAMESPACE);

        DmnXMLUtil.writeElementDescription(model, xtw);
        DmnXMLUtil.writeExtensionElements(model, xtw);

        for (ItemDefinition itemDefinition : model.getItemDefinitions()) {
            xtw.writeStartElement(ELEMENT_ITEM_DEFINITION);
            xtw.writeAttribute(ATTRIBUTE_ID, itemDefinition.getId());
            if (StringUtils.isNotEmpty(itemDefinition.getName())) {
                xtw.writeAttribute(ATTRIBUTE_NAME, itemDefinition.getName());
            }

            DmnXMLUtil.writeElementDescription(itemDefinition, xtw);
            DmnXMLUtil.writeExtensionElements(itemDefinition, xtw);

            xtw.writeStartElement(ELEMENT_TYPE_DEFINITION);
            xtw.writeCharacters(itemDefinition.getTypeDefinition());
            xtw.writeEndElement();

            xtw.writeEndElement();
        }

        for (Decision decision : model.getDrgElements()) {
            xtw.writeStartElement(ELEMENT_DECISION);
            xtw.writeAttribute(ATTRIBUTE_ID, decision.getId());
            if (StringUtils.isNotEmpty(decision.getName())) {
                xtw.writeAttribute(ATTRIBUTE_NAME, decision.getName());
            }

            DmnXMLUtil.writeElementDescription(decision, xtw);
            DmnXMLUtil.writeExtensionElements(decision, xtw);

            DecisionTable decisionTable = decision.getDecisionTable();
            xtw.writeStartElement(ELEMENT_DECISION_TABLE);
            xtw.writeAttribute(ATTRIBUTE_ID, decisionTable.getId());

            if (decisionTable.getHitPolicy() != null) {
                xtw.writeAttribute(ATTRIBUTE_HIT_POLICY, decisionTable.getHitPolicy().toString());
            }

            DmnXMLUtil.writeElementDescription(decisionTable, xtw);
            DmnXMLUtil.writeExtensionElements(decisionTable, xtw);

            for (InputClause clause : decisionTable.getInputs()) {
                xtw.writeStartElement(ELEMENT_INPUT_CLAUSE);
                if (StringUtils.isNotEmpty(clause.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getId());
                }
                if (StringUtils.isNotEmpty(clause.getLabel())) {
                    xtw.writeAttribute(ATTRIBUTE_LABEL, clause.getLabel());
                }

                DmnXMLUtil.writeElementDescription(clause, xtw);
                DmnXMLUtil.writeExtensionElements(clause, xtw);

                if (clause.getInputExpression() != null) {
                    xtw.writeStartElement(ELEMENT_INPUT_EXPRESSION);
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getInputExpression().getId());

                    if (StringUtils.isNotEmpty(clause.getInputExpression().getTypeRef())) {
                        xtw.writeAttribute(ATTRIBUTE_TYPE_REF, clause.getInputExpression().getTypeRef());
                    }

                    if (StringUtils.isNotEmpty(clause.getInputExpression().getText())) {
                        xtw.writeStartElement(ELEMENT_TEXT);
                        xtw.writeCharacters(clause.getInputExpression().getText());
                        xtw.writeEndElement();
                    }

                    xtw.writeEndElement();
                }

                xtw.writeEndElement();
            }

            for (OutputClause clause : decisionTable.getOutputs()) {
                xtw.writeStartElement(ELEMENT_OUTPUT_CLAUSE);
                if (StringUtils.isNotEmpty(clause.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, clause.getId());
                }
                if (StringUtils.isNotEmpty(clause.getLabel())) {
                    xtw.writeAttribute(ATTRIBUTE_LABEL, clause.getLabel());
                }
                if (StringUtils.isNotEmpty(clause.getName())) {
                    xtw.writeAttribute(ATTRIBUTE_NAME, clause.getName());
                }
                if (StringUtils.isNotEmpty(clause.getTypeRef())) {
                    xtw.writeAttribute(ATTRIBUTE_TYPE_REF, clause.getTypeRef());
                }

                DmnXMLUtil.writeElementDescription(clause, xtw);
                DmnXMLUtil.writeExtensionElements(clause, xtw);

                xtw.writeEndElement();
            }

            for (DecisionRule rule : decisionTable.getRules()) {
                xtw.writeStartElement(ELEMENT_RULE);
                if (StringUtils.isNotEmpty(rule.getId())) {
                    xtw.writeAttribute(ATTRIBUTE_ID, rule.getId());
                }

                DmnXMLUtil.writeElementDescription(rule, xtw);
                DmnXMLUtil.writeExtensionElements(rule, xtw);

                for (RuleInputClauseContainer container : rule.getInputEntries()) {
                    xtw.writeStartElement(ELEMENT_INPUT_ENTRY);
                    xtw.writeAttribute(ATTRIBUTE_ID, container.getInputEntry().getId());

                    xtw.writeStartElement(ELEMENT_TEXT);
                    xtw.writeCharacters(container.getInputEntry().getText());
                    xtw.writeEndElement();

                    xtw.writeEndElement();
                }

                for (RuleOutputClauseContainer container : rule.getOutputEntries()) {
                    xtw.writeStartElement(ELEMENT_OUTPUT_ENTRY);
                    xtw.writeAttribute(ATTRIBUTE_ID, container.getOutputEntry().getId());

                    xtw.writeStartElement(ELEMENT_TEXT);
                    xtw.writeCharacters(container.getOutputEntry().getText());
                    xtw.writeEndElement();

                    xtw.writeEndElement();
                }

                xtw.writeEndElement();
            }

            xtw.writeEndElement();

            xtw.writeEndElement();
        }

        // end definitions root element
        xtw.writeEndElement();
        xtw.writeEndDocument();

        xtw.flush();

        outputStream.close();

        xtw.close();

        return outputStream.toByteArray();

    } catch (Exception e) {
        LOGGER.error("Error writing BPMN XML", e);
        throw new DmnXMLException("Error writing BPMN XML", e);
    }
}

From source file:org.apache.axiom.om.impl.llom.OMElementImpl.java

public String toStringWithConsume() throws XMLStreamException {
    StringWriter writer = new StringWriter();
    XMLStreamWriter writer2 = StAXUtils.createXMLStreamWriter(writer);
    try {/*from  ww w . j a  v  a 2s .co  m*/
        this.serializeAndConsume(writer2);
        writer2.flush();
    } finally {
        writer2.close();
    }
    return writer.toString();
}

From source file:org.apache.axiom.om.impl.llom.OMElementImpl.java

public String toString() {
    StringWriter writer = new StringWriter();
    try {/*from  w ww  . ja  v a2s  . c  o m*/
        XMLStreamWriter writer2 = StAXUtils.createXMLStreamWriter(writer);
        try {
            this.serialize(writer2);
            writer2.flush();
        } finally {
            writer2.close();
        }
    } catch (XMLStreamException e) {
        throw new RuntimeException("Can not serialize OM Element " + this.getLocalName(), e);
    }
    return writer.toString();
}

From source file:org.apache.axiom.om.impl.llom.OMSourcedElementImpl.java

public String toStringWithConsume() throws XMLStreamException {
    if (isExpanded()) {
        return super.toStringWithConsume();
    } else {/*from  w  w w  . j a v  a  2  s  . co m*/
        StringWriter writer = new StringWriter();
        XMLStreamWriter writer2 = StAXUtils.createXMLStreamWriter(writer);
        dataSource.serialize(writer2); // dataSource.serialize consumes the data
        writer2.flush();
        return writer.toString();
    }
}

From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java

/**
 * Preferred way to marshal objects.//from   ww w .  j a  v a  2s  . co  m
 * 
 * @param b Object that can be rendered as an element and the element name is known by the
 * Marshaller
 * @param m Marshaller
 * @param writer XMLStreamWriter
 */
private static void marshalByElement(final Object b, final Marshaller m, final XMLStreamWriter writer,
        final boolean optimize) {
    AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            // Marshalling directly to the output stream is faster than marshalling through the
            // XMLStreamWriter. 
            // Take advantage of this optimization if there is an output stream.
            try {
                OutputStream os = (optimize) ? getOutputStream(writer, m) : null;
                if (os != null) {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByElement.  " + "Marshaling to an OutputStream. "
                                + "Object is " + getDebugName(b));
                    }
                    writer.flush();
                    m.marshal(b, os);
                } else {
                    if (DEBUG_ENABLED) {
                        log.debug("Invoking marshalByElement.  " + "Marshaling to an XMLStreamWriter. "
                                + "Object is " + getDebugName(b));
                    }
                    m.marshal(b, writer);
                }
            } catch (OMException e) {
                throw e;
            } catch (Throwable t) {
                throw new OMException(t);
            }
            return null;
        }
    });
}

From source file:org.apache.axis2.jaxws.message.util.Reader2Writer.java

/**
 * Utility method to write the reader contents to a String
 * @return String/*from  w  ww . j a  v a2 s.  c o  m*/
 */
public String getAsString() throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter writer = StAXUtils.createXMLStreamWriter(sw);

    // Write the reader to the writer
    outputTo(writer);

    // Flush the writer and get the String
    writer.flush();
    sw.flush();
    String str = sw.toString();
    writer.close();
    return str;
}

From source file:org.apache.axis2.transport.http.ListingAgent.java

public void processListService(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException {

    String url;/*from ww  w .  ja  v a2 s  .c  o m*/
    try {
        url = req.getRequestURL().toString();
    } catch (Throwable t) {
        log.info("Old Servlet API (Fallback to HttpServletRequest.getRequestURI) :" + t);
        url = req.getRequestURI();
    }
    String serviceName = extractServiceName(url);
    HashMap services = configContext.getAxisConfiguration().getServices();
    String query = req.getQueryString();
    int wsdl2 = query.indexOf("wsdl2");
    int wsdl = query.indexOf("wsdl");
    int xsd = query.indexOf("xsd");
    int policy = query.indexOf("policy");

    if ((services != null) && !services.isEmpty()) {
        Object serviceObj = services.get(serviceName);
        if (serviceObj != null) {
            boolean isHttp = "http".equals(req.getScheme());
            if (wsdl2 >= 0) {
                res.setContentType("text/xml");
                String ip = extractHostAndPort(url, isHttp);
                String wsdlName = req.getParameter("wsdl2");
                if (wsdlName != null && wsdlName.length() > 0) {
                    InputStream in = ((AxisService) serviceObj).getClassLoader()
                            .getResourceAsStream(DeploymentConstants.META_INF + "/" + wsdlName);
                    if (in != null) {
                        OutputStream out = res.getOutputStream();
                        out.write(IOUtils.getStreamAsByteArray(in));
                        out.flush();
                        out.close();
                    } else {
                        res.sendError(HttpServletResponse.SC_NOT_FOUND);
                    }
                } else {
                    OutputStream out = res.getOutputStream();
                    ((AxisService) serviceObj).printWSDL2(out, ip);
                    out.flush();
                    out.close();
                }
                return;
            } else if (wsdl >= 0) {
                OutputStream out = res.getOutputStream();
                res.setContentType("text/xml");
                String ip = extractHostAndPort(url, isHttp);
                String wsdlName = req.getParameter("wsdl");

                if (wsdlName != null && wsdlName.length() > 0) {
                    AxisService axisServce = (AxisService) serviceObj;
                    axisServce.printUserWSDL(out, wsdlName);
                    out.flush();
                    out.close();
                } else {
                    ((AxisService) serviceObj).printWSDL(out, ip);
                    out.flush();
                    out.close();
                }
                return;
            } else if (xsd >= 0) {
                res.setContentType("text/xml");
                int ret = ((AxisService) serviceObj).printXSD(res.getOutputStream(), req.getParameter("xsd"));
                if (ret == 0) {
                    //multiple schemas are present and the user specified
                    //no name - in this case we cannot possibly pump a schema
                    //so redirect to the service root
                    res.sendRedirect("");
                } else if (ret == -1) {
                    res.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                return;
            } else if (policy >= 0) {

                ExternalPolicySerializer serializer = new ExternalPolicySerializer();
                serializer
                        .setAssertionsToFilter(configContext.getAxisConfiguration().getLocalPolicyAssertions());

                // check whether Id is set
                String idParam = req.getParameter("id");

                if (idParam != null) {
                    // Id is set

                    Policy targetPolicy = findPolicy(idParam, (AxisService) serviceObj);

                    if (targetPolicy != null) {
                        XMLStreamWriter writer;

                        try {
                            OutputStream out = res.getOutputStream();
                            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                            res.setContentType("application/wspolicy+xml");
                            targetPolicy.serialize(writer);
                            writer.flush();

                        } catch (XMLStreamException e) {
                            throw new ServletException("Error occured when serializing the Policy", e);

                        } catch (FactoryConfigurationError e) {
                            throw new ServletException("Error occured when serializing the Policy", e);
                        }

                    } else {

                        OutputStream out = res.getOutputStream();
                        res.setContentType("text/html");
                        String outStr = "<b>No policy found for id=" + idParam + "</b>";
                        out.write(outStr.getBytes());
                    }

                } else {

                    PolicyInclude policyInclude = ((AxisService) serviceObj).getPolicyInclude();
                    Policy effecPolicy = policyInclude.getEffectivePolicy();

                    if (effecPolicy != null) {
                        XMLStreamWriter writer;

                        try {
                            OutputStream out = res.getOutputStream();
                            writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out);

                            res.setContentType("application/wspolicy+xml");
                            effecPolicy.serialize(writer);
                            writer.flush();

                        } catch (XMLStreamException e) {
                            throw new ServletException("Error occured when serializing the Policy", e);

                        } catch (FactoryConfigurationError e) {
                            throw new ServletException("Error occured when serializing the Policy", e);
                        }
                    } else {

                        OutputStream out = res.getOutputStream();
                        res.setContentType("text/html");
                        String outStr = "<b>No effective policy for " + serviceName + " servcie</b>";
                        out.write(outStr.getBytes());
                    }
                }

                return;
            } else {
                try {
                    req.getSession().setAttribute(Constants.SINGLE_SERVICE, serviceObj);
                } catch (Throwable t) {
                    log.info("Old Servlet API :" + t);
                }
            }
        } else {
            try {
                req.getSession().setAttribute(Constants.SINGLE_SERVICE, null);
            } catch (Throwable t) {
                log.info("Old Servlet API :" + t);
            }

            res.sendError(HttpServletResponse.SC_NOT_FOUND, url);
        }
    }

    renderView(LIST_SINGLE_SERVICE_JSP_NAME, req, res);
}

From source file:org.apache.nifi.authorization.FileAccessPolicyProvider.java

@Override
public String getFingerprint() throws AuthorizationAccessException {
    final List<AccessPolicy> policies = new ArrayList<>(getAccessPolicies());
    Collections.sort(policies, Comparator.comparing(AccessPolicy::getIdentifier));

    XMLStreamWriter writer = null;
    final StringWriter out = new StringWriter();
    try {//from  ww  w  .  ja  v a 2 s . c  om
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        writer.writeStartElement("accessPolicies");

        for (AccessPolicy policy : policies) {
            writePolicy(writer, policy);
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
    } catch (XMLStreamException e) {
        throw new AuthorizationAccessException("Unable to generate fingerprint", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                // nothing to do here
            }
        }
    }

    return out.toString();
}

From source file:org.apache.nifi.authorization.FileUserGroupProvider.java

@Override
public String getFingerprint() throws AuthorizationAccessException {
    final UserGroupHolder usersAndGroups = userGroupHolder.get();

    final List<User> users = new ArrayList<>(usersAndGroups.getAllUsers());
    Collections.sort(users, Comparator.comparing(User::getIdentifier));

    final List<Group> groups = new ArrayList<>(usersAndGroups.getAllGroups());
    Collections.sort(groups, Comparator.comparing(Group::getIdentifier));

    XMLStreamWriter writer = null;
    final StringWriter out = new StringWriter();
    try {//from  ww w  .  j  a  v a  2  s  . com
        writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
        writer.writeStartDocument();
        writer.writeStartElement("tenants");

        for (User user : users) {
            writeUser(writer, user);
        }
        for (Group group : groups) {
            writeGroup(writer, group);
        }

        writer.writeEndElement();
        writer.writeEndDocument();
        writer.flush();
    } catch (XMLStreamException e) {
        throw new AuthorizationAccessException("Unable to generate fingerprint", e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (XMLStreamException e) {
                // nothing to do here
            }
        }
    }

    return out.toString();
}