Example usage for org.dom4j.io XMLWriter flush

List of usage examples for org.dom4j.io XMLWriter flush

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the underlying Writer

Usage

From source file:org.pentaho.platform.util.xml.dom4j.XmlDom4JHelper.java

License:Open Source License

public static void saveDom(final Document doc, final OutputStream outputStream, String encoding,
        boolean suppressDeclaration, boolean prettyPrint) throws IOException {
    OutputFormat format = prettyPrint ? OutputFormat.createPrettyPrint() : OutputFormat.createCompactFormat();
    format.setSuppressDeclaration(suppressDeclaration);
    if (encoding != null) {
        format.setEncoding(encoding.toLowerCase());
        if (!suppressDeclaration) {
            doc.setXMLEncoding(encoding.toUpperCase());
        }/*from   ww  w  .  ja v a2 s.c  o m*/
    }
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(doc);
    writer.flush();
}

From source file:org.pentaho.platform.web.http.api.resources.XactionUtil.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String executeXml(RepositoryFile file, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse, IPentahoSession userSession) throws Exception {
    try {/*from  www .  ja  v  a  2  s.  c om*/
        HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider(userSession);
        HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider(httpServletRequest);
        Map parameterProviders = new HashMap();
        parameterProviders.put("request", requestParameters); //$NON-NLS-1$
        parameterProviders.put("session", sessionParameters); //$NON-NLS-1$
        List messages = new ArrayList();
        IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest);
        httpServletResponse.setContentType("text/xml"); //$NON-NLS-1$
        httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding());
        boolean forcePrompt = "true".equalsIgnoreCase(requestParams.getStringParameter("prompt", "false")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$

        OutputStream contentStream = new ByteArrayOutputStream();
        SimpleOutputHandler outputHandler = new SimpleOutputHandler(contentStream, false);
        IRuntimeContext runtime = null;
        try {
            runtime = executeInternal(file, requestParams, httpServletRequest, outputHandler,
                    parameterProviders, userSession, forcePrompt, messages);
            Document responseDoc = SoapHelper.createSoapResponseDocument(runtime, outputHandler, contentStream,
                    messages);
            OutputFormat format = OutputFormat.createCompactFormat();
            format.setSuppressDeclaration(true);
            format.setEncoding("utf-8"); //$NON-NLS-1$
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            XMLWriter writer = new XMLWriter(outputStream, format);
            writer.write(responseDoc);
            writer.flush();
            return outputStream.toString("utf-8"); //$NON-NLS-1$
        } finally {
            if (runtime != null) {
                runtime.dispose();
            }
        }
    } catch (Exception e) {
        logger.warn(Messages.getInstance().getString("XactionUtil.XML_OUTPUT_NOT_SUPPORTED")); //$NON-NLS-1$
        throw e;
    }
}

From source file:org.pentaho.platform.web.http.api.resources.XactionUtil.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String doParameter(final RepositoryFile file, IParameterProvider parameterProvider,
        final IPentahoSession userSession) throws IOException {
    ActionSequenceJCRHelper helper = new ActionSequenceJCRHelper();
    final IActionSequence actionSequence = helper.getActionSequence(file.getPath(), PentahoSystem.loggingLevel,
            RepositoryFilePermission.READ);
    final Document document = DocumentHelper.createDocument();
    try {/*from   w w  w . java2 s. c om*/
        final Element parametersElement = document.addElement("parameters");

        // noinspection unchecked
        final Map<String, IActionParameter> params = actionSequence
                .getInputDefinitionsForParameterProvider(IParameterProvider.SCOPE_REQUEST);
        for (final Map.Entry<String, IActionParameter> entry : params.entrySet()) {
            final String paramName = entry.getKey();
            final IActionParameter paramDef = entry.getValue();
            final String value = paramDef.getStringValue();
            final Class type;
            // yes, the actual type-code uses equals-ignore-case and thus allows the user
            // to specify type information in a random case. sTrInG is equal to STRING is equal to the value
            // defined as constant (string)
            if (IActionParameter.TYPE_LIST.equalsIgnoreCase(paramDef.getType())) {
                type = String[].class;
            } else {
                type = String.class;
            }
            final String label = paramDef.getSelectionDisplayName();

            final String[] values;
            if (StringUtils.isEmpty(value)) {
                values = new String[0];
            } else {
                values = new String[] { value };
            }

            createParameterElement(parametersElement, paramName, type, label, "user", "parameters", values);
        }

        createParameterElement(parametersElement, "path", String.class, null, "system", "system",
                new String[] { file.getPath() });
        createParameterElement(parametersElement, "prompt", String.class, null, "system", "system",
                new String[] { "yes", "no" });
        createParameterElement(parametersElement, "instance-id", String.class, null, "system", "system",
                new String[] { parameterProvider.getStringParameter("instance-id", null) });
        // no close, as far as I know tomcat does not like it that much ..
        OutputFormat format = OutputFormat.createCompactFormat();
        format.setSuppressDeclaration(true);
        format.setEncoding("utf-8"); //$NON-NLS-1$
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.write(document);
        writer.flush();
        return outputStream.toString("utf-8");
    } catch (Exception e) {
        logger.warn(Messages.getInstance().getString("HttpWebService.ERROR_0003_UNEXPECTED"), e);
        return null;
    }
}

From source file:org.pentaho.platform.web.servlet.HttpWebService.java

License:Open Source License

private void doParameter(final String solutionName, final String actionPath, final String actionName,
        final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final HttpServletResponse response) throws IOException {

    final IActionSequence actionSequence = new ActionSequenceJCRHelper().getActionSequence(
            ActionInfo.buildSolutionPath(solutionName, actionPath, actionName), PentahoSystem.loggingLevel,
            RepositoryFilePermission.READ);
    if (actionSequence == null) {
        logger.debug(Messages.getInstance().getString("HttpWebService.ERROR_0002_NOTFOUND", solutionName,
                actionPath, actionName));
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;/*from  w w w .j  a v a2s  . c  om*/
    }

    final Document document = DocumentHelper.createDocument();
    try {
        final Element parametersElement = document.addElement("parameters");

        // noinspection unchecked
        final Map<String, IActionParameter> params = actionSequence
                .getInputDefinitionsForParameterProvider(IParameterProvider.SCOPE_REQUEST);
        for (final Map.Entry<String, IActionParameter> entry : params.entrySet()) {
            final String paramName = entry.getKey();
            final IActionParameter paramDef = entry.getValue();
            final String value = paramDef.getStringValue();
            final Class type;
            // yes, the actual type-code uses equals-ignore-case and thus allows the user
            // to specify type information in a random case. sTrInG is equal to STRING is equal to the value
            // defined as constant (string)
            if (IActionParameter.TYPE_LIST.equalsIgnoreCase(paramDef.getType())) {
                type = String[].class;
            } else {
                type = String.class;
            }
            final String label = paramDef.getSelectionDisplayName();

            final String[] values;
            if (StringUtils.isEmpty(value)) {
                values = new String[0];
            } else {
                values = new String[] { value };
            }

            createParameterElement(parametersElement, paramName, type, label, "user", "parameters", values);
        }

        // built in parameters: solution, path, action, prompt, instance-id
        createParameterElement(parametersElement, "solution", String.class, null, "system", "system",
                new String[] { solutionName });
        createParameterElement(parametersElement, "path", String.class, null, "system", "system",
                new String[] { actionPath });
        createParameterElement(parametersElement, "action", String.class, null, "system", "system",
                new String[] { actionName });
        createParameterElement(parametersElement, "prompt", String.class, null, "system", "system",
                new String[] { "yes", "no" });
        createParameterElement(parametersElement, "instance-id", String.class, null, "system", "system",
                new String[] { parameterProvider.getStringParameter("instance-id", null) });

    } catch (Exception e) {
        logger.warn(Messages.getInstance().getString("HttpWebService.ERROR_0003_UNEXPECTED"), e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return;
    }
    // no close, as far as I know tomcat does not like it that much ..
    final XMLWriter writer = new XMLWriter(outputStream, OutputFormat.createPrettyPrint());
    writer.write(document);
    writer.flush();
}

From source file:org.sitemap4j.dom4j.Dom4jWriterHelper.java

License:Apache License

static void writeDocument(final OutputStream stream, final Document document) {
    final XMLWriter xmlWriter;

    try {//from ww  w.j a  va2  s .c o m
        xmlWriter = new XMLWriter(stream, OutputFormat.createPrettyPrint());
        xmlWriter.write(document);
        xmlWriter.flush();
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.snipsnap.jsp.ContentTag.java

License:Open Source License

public int doStartTag() throws JspException {
    if (null != snip) {
        String content = snip.getXMLContent();
        if (removeHtml) {
            Filter filter = new HtmlRemoveFilter();
            content = filter.filter(content, null);
            if (extract) {
                if (content.length() > 40) {
                    content = content.substring(0, 40);
                    int ampIndex = content.lastIndexOf("&");
                    int colonIndex = content.lastIndexOf(";");
                    // did we cut a entity like &x1212; ?
                    if (ampIndex > colonIndex) {
                        content = content.substring(0, ampIndex - 1);
                    }//w  w  w .j  av a2s .c  o m
                    content = content + " ...";
                }
            }
        }
        if (encodeHtml) {
            StringWriter stringWriter = new StringWriter();
            try {
                OutputFormat outputFormat = new OutputFormat();
                outputFormat.setNewlines(true);
                XMLWriter xmlWriter = new XMLWriter(stringWriter, outputFormat);
                xmlWriter.write(content);
                xmlWriter.flush();
            } catch (IOException e) {
                Logger.warn("ContentTag: unable to write encoded content: " + e);
            }
            content = stringWriter.toString();
        }
        try {
            JspWriter out = pageContext.getOut();
            out.print(content);
        } catch (IOException e) {
            Logger.warn("doStartTag in ContentTag", e);
        }
    }
    return super.doStartTag();
}

From source file:org.snipsnap.snip.attachment.Attachments.java

License:Open Source License

private String toString(Element attElement) {
    OutputFormat outputFormat = OutputFormat.createCompactFormat();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {//  ww w.j a va 2 s .co m
        XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
        xmlWriter.write(attElement);
        xmlWriter.flush();
    } catch (IOException e) {
        Logger.warn("Attachments: unable to serialize", e);
    }

    try {
        String enc = Application.get().getConfiguration().getEncoding();
        return out.toString(enc == null ? "UTF-8" : enc);
    } catch (UnsupportedEncodingException e) {
        return out.toString();
    }
}

From source file:org.snipsnap.snip.storage.XMLFileSnipStorage.java

License:Open Source License

protected void storeSnip(snipsnap.api.snip.Snip snip, OutputStream out) {
    Document snipDocument = DocumentHelper.createDocument();
    snipDocument.add(serializer.serialize(snip));

    try {/* ww  w .java  2  s.c o  m*/
        OutputFormat outputFormat = new OutputFormat();
        outputFormat.setEncoding("UTF-8");
        XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
        xmlWriter.write(snipDocument);
        xmlWriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.snipsnap.snip.XMLSnipExport.java

License:Open Source License

public static void store(OutputStream out, List snips, List users, String filter, List ignoreElements,
        File fileStore) {/*from  w w  w .  j  a v a 2  s.  c  om*/
    try {
        OutputFormat outputFormat = new OutputFormat();
        outputFormat.setEncoding("UTF-8");
        outputFormat.setNewlines(true);
        XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
        Element root = DocumentHelper.createElement("snipspace");
        xmlWriter.writeOpen(root);
        storeUsers(xmlWriter, users);
        storeSnips(xmlWriter, snips, filter, ignoreElements, fileStore);
        xmlWriter.writeClose(root);
        xmlWriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.snipsnap.util.JDBCDatabaseExport.java

License:Open Source License

/**
 * Store snips and users from the SnipSpace to an xml document into a stream.
 * @param out outputstream to write to//  www.  j a  va  2  s . co m
 */
public static void store(OutputStream out, String appOid, Connection connection) {
    try {
        OutputFormat outputFormat = new OutputFormat();
        outputFormat.setEncoding("UTF-8");
        outputFormat.setNewlines(true);

        XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
        xmlWriter.startDocument();
        Element root = DocumentHelper.createElement("snipspace");
        xmlWriter.writeOpen(root);

        //      storeUsers(xmlWriter, connection);
        storeSnips(xmlWriter, appOid, connection);

        xmlWriter.writeClose(root);
        xmlWriter.endDocument();
        xmlWriter.flush();
        xmlWriter.close();
    } catch (Exception e) {
        System.err.println("JDBCDatabaseExport: error while writing document: " + e.getMessage());
    }
}