Example usage for org.dom4j.io OutputFormat createPrettyPrint

List of usage examples for org.dom4j.io OutputFormat createPrettyPrint

Introduction

In this page you can find the example usage for org.dom4j.io OutputFormat createPrettyPrint.

Prototype

public static OutputFormat createPrettyPrint() 

Source Link

Document

A static helper method to create the default pretty printing format.

Usage

From source file:org.pentaho.platform.plugin.adhoc.AdhocWebService.java

License:Open Source License

/**
 * Create the JFreeReport file./*from  w  w w . j  ava 2  s. c om*/
 * 
 * NOTE on the merge precedence: this method should use properties set by the 
 * WAQR UI. If the waqr UI did not set the property, then the property 
 * should be set by the metadata. If the metadata did not set a property,
 * then the property should be set by the template. If the template
 * did not set the property, then use the default.
 * 
 * NOTE on the merge algorithm: 
 * For each of the attributes in the fields (aka columns) of the reportspec,
 * if the attribute is present in the reportspec that comes in from the client
 * (ie reportXML param), and the attribute has a non-default value, do not change it.
 * If the attribute is not present or has a default value, and if there is metadata
 * for that attribute, merge the metadata attribute. This take place inline in the 
 * main loop of this method. If after the metadata merge the attribute 
 * still does not have a value, merge the template value. This takes place
 * in the AdhocWebService.applyTemplate() method.
 * If the template does not have a value, do nothing (the default will be used).
 * 
 * @param reportDoc
 * @param reportXML
 * @param templatePath
 * @param mqlNode
 * @param userSession
 * @return
 * @throws IOException
 * @throws AdhocWebServiceException
 * @throws PentahoMetadataException
 */
public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode,
        IPentahoSession userSession, OutputStream jfreeMergedOutputStream)
        throws IOException, AdhocWebServiceException, PentahoMetadataException {

    Map reportSpecTypeToElement = null;
    Document templateDoc = null;
    Element templateItems = null;
    boolean bUseTemplate = !StringUtils.isEmpty(templatePath);

    if (bUseTemplate) {
        templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath;
        try {
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            templateDoc = reader
                    .read(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }

        templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List nodes = templateItems.elements();
        Iterator it = nodes.iterator();
        reportSpecTypeToElement = new HashMap();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            reportSpecTypeToElement.put(element.getName(), element);
        }
    }

    // get the business model from the mql statement
    String xml = mqlNode.asXML();

    // first see if it's a thin model...
    QueryXmlHelper helper = new QueryXmlHelper();
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    Query queryObject = null;
    try {
        queryObject = helper.fromXML(repo, xml);
    } catch (Exception e) {
        String msg = Messages.getInstance()
                .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    LogicalModel model = null;
    if (queryObject != null) {
        model = queryObject.getLogicalModel();
    }
    if (model == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$
    }

    String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(),
            queryObject.getDomain().getLocaleCodes());

    String reportXMLEncoding = XmlHelper.getEncoding(reportXML);
    ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream(
            reportXML.getBytes(reportXMLEncoding));
    ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream,
            ReportSpec.class, reportXMLEncoding);
    if (reportSpec == null) {
        throw new AdhocWebServiceException(
                Messages.getInstance().getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$
    }

    // ========== begin column width stuff

    // make copies of the business columns; in the next step we're going to fill out any missing column widths
    LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length];
    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        String name = field.getName();
        LogicalColumn column = model.findLogicalColumn(name);
        columns[i] = (LogicalColumn) column.clone();
    }

    boolean columnWidthUnitsConsistent = AdhocWebService.areMetadataColumnUnitsConsistent(reportSpec, model);

    if (!columnWidthUnitsConsistent) {
        logger.error(Messages.getInstance()
                .getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$
    } else {
        double columnWidthScaleFactor = 1.0;
        int missingColumnWidthCount = 0;
        int columnWidthSumOfPercents;
        double defaultWidth;
        columnWidthSumOfPercents = AdhocWebService.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocWebService.getMissingColumnWidthCount(reportSpec, model);

        // if there are columns with no column width specified, figure out what percent we should use for them
        if (missingColumnWidthCount > 0) {
            if (columnWidthSumOfPercents < 100) {
                int remainingPercent = 100 - columnWidthSumOfPercents;
                defaultWidth = remainingPercent / missingColumnWidthCount;
                columnWidthSumOfPercents = 100;
            } else {
                defaultWidth = 10;
                columnWidthSumOfPercents += (missingColumnWidthCount * 10);
            }

            // fill in columns without column widths
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                if (property == null) {
                    property = new ColumnWidth(WidthType.PERCENT, defaultWidth);
                    columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property);
                }
            }
        }

        if (columnWidthSumOfPercents > 100) {
            columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents;
        }

        // now scale down if necessary
        if (columnWidthScaleFactor < 1.0) {
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                ColumnWidth newProperty = new ColumnWidth(property.getType(),
                        columnWidthScaleFactor * property.getWidth());
                columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty);
            }
        }

    }

    // ========== end column width stuff

    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        LogicalColumn column = columns[i];

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

        // Template properties have the lowest priority, merge them last
        if (bUseTemplate) {
            Element templateDefaults = null;
            if (column.getDataType() != null) {
                templateDefaults = (Element) reportSpecTypeToElement
                        .get(AdhocWebService.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell
            }
            /*
             * NOTE: this merge of the template with the node's properties only sets the following properties:
             * format, fontname, fontsize, color, alignment, vertical-alignment, 
             */
            AdhocWebService.applyTemplate(field, templateDefaults);
        }
        AdhocWebService.applyDefaults(field);
    } // end for

    /*
     * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using
     * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it,
     * and some of the template.
     */
    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding,
            (OutputStream) jfreeOutputStream);
    String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding);
    Document generatedJFreeDoc = null;
    try {
        generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, new PentahoEntityResolver());
    } catch (XmlParseException e) {
        String msg = Messages.getInstance()
                .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    /*
     * Merge template's /report/items element's attributes into the
     * generated document's /report/items element's attributes. There should not be any
     * conflict with the metadata, or the xreportspec in the reportXML param
     */
    if (bUseTemplate) {
        Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List templateAttrs = templateItems.attributes(); // from the template's /report/items element
        Iterator templateAttrsIt = templateAttrs.iterator();

        while (templateAttrsIt.hasNext()) {
            Attribute attr = (Attribute) templateAttrsIt.next();
            String name = attr.getName();
            String value = attr.getText();

            Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$
            if (node != null) {
                node.setText(value);
            } else {
                reportItems.addAttribute(name, value);
            }
        }
        List templateElements = templateItems.elements();
        Iterator templateElementsIt = templateElements.iterator();
        while (templateElementsIt.hasNext()) {
            Element element = (Element) templateElementsIt.next();
            element.detach();
            reportItems.add(element);
        }
        /*
         * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate())
         * with the generated document can wait until last because none of the 
         * properties involved in this merge are settable by the metadata or the WAQR UI
         */
        ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream);
    } else {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(reportXMLEncoding);
        XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format);
        writer.write(generatedJFreeDoc);
        writer.close();
    }
}

From source file:org.pentaho.platform.plugin.adhoc.AdhocWebService.java

License:Open Source License

public static void main(String args[]) throws Exception {
    XMLWriter writer = new XMLWriter(System.out, OutputFormat.createPrettyPrint());
    Document doc = new AdhocWebService().createSolutionTree(new File("package-res/resources/templates"));

    Element folderElement = AdhocWebService.getFolderElement(doc, "/system/waqr/resources");
    Document systemDoc = null;//from   w  ww  .jav  a  2s  .c  o m
    if (folderElement != null) {
        Element clonedFolderElement = (Element) folderElement.clone();
        AdhocWebService.removeChildElements(clonedFolderElement);
        systemDoc = DocumentHelper.createDocument((Element) clonedFolderElement.detach());
        systemDoc.setXMLEncoding(LocaleHelper.getSystemEncoding());
    } else {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0011_FAILED_TO_LOCATE_PATH", "/"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }

    writer.write(systemDoc);
    writer.flush();
    //    System.out.println(XmlDom4JHelper.docToString();
}

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 w  w w  .  ja va2 s  .c  om
    }
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(doc);
    writer.flush();
}

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

License:Open Source License

/**
 * Create the JFreeReport file.//from  www  .  j  a v  a2  s  .c  o m
 * 
 * NOTE on the merge precedence: this method should use properties set by the 
 * WAQR UI. If the waqr UI did not set the property, then the property 
 * should be set by the metadata. If the metadata did not set a property,
 * then the property should be set by the template. If the template
 * did not set the property, then use the default.
 * 
 * NOTE on the merge algorithm: 
 * For each of the attributes in the fields (aka columns) of the reportspec,
 * if the attribute is present in the reportspec that comes in from the client
 * (ie reportXML param), and the attribute has a non-default value, do not change it.
 * If the attribute is not present or has a default value, and if there is metadata
 * for that attribute, merge the metadata attribute. This take place inline in the 
 * main loop of this method. If after the metadata merge the attribute 
 * still does not have a value, merge the template value. This takes place
 * in the AdhocWebService.applyTemplate() method.
 * If the template does not have a value, do nothing (the default will be used).
 * 
 * @param reportDoc
 * @param reportXML
 * @param templatePath
 * @param mqlNode
 * @param repository
 * @param userSession
 * @return
 * @throws IOException
 * @throws AdhocWebServiceException
 * @throws PentahoMetadataException
 */
public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode,
        ISolutionRepository repository, IPentahoSession userSession, OutputStream jfreeMergedOutputStream)
        throws IOException, AdhocWebServiceException, PentahoMetadataException {

    Map reportSpecTypeToElement = null;
    Document templateDoc = null;
    Element templateItems = null;
    boolean bUseTemplate = !StringUtils.isEmpty(templatePath);

    if (bUseTemplate) {
        templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath;
        templateDoc = repository.getResourceAsDocument(templatePath, ISolutionRepository.ACTION_EXECUTE);

        templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List nodes = templateItems.elements();
        Iterator it = nodes.iterator();
        reportSpecTypeToElement = new HashMap();
        while (it.hasNext()) {
            Element element = (Element) it.next();
            reportSpecTypeToElement.put(element.getName(), element);
        }
    }

    // get the business model from the mql statement
    String xml = mqlNode.asXML();

    // first see if it's a thin model...
    QueryXmlHelper helper = new QueryXmlHelper();
    IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null);
    Query queryObject = null;
    try {
        queryObject = helper.fromXML(repo, xml);
    } catch (Exception e) {
        String msg = Messages.getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    LogicalModel model = null;
    if (queryObject != null) {
        model = queryObject.getLogicalModel();
    }
    if (model == null) {
        throw new AdhocWebServiceException(
                Messages.getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$
    }

    String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(),
            queryObject.getDomain().getLocaleCodes());

    String reportXMLEncoding = XmlHelper.getEncoding(reportXML);
    ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream(
            reportXML.getBytes(reportXMLEncoding));
    ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream,
            ReportSpec.class, reportXMLEncoding);
    if (reportSpec == null) {
        throw new AdhocWebServiceException(
                Messages.getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$
    }

    // ========== begin column width stuff

    // make copies of the business columns; in the next step we're going to fill out any missing column widths
    LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length];
    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        String name = field.getName();
        LogicalColumn column = model.findLogicalColumn(name);
        columns[i] = (LogicalColumn) column.clone();
    }

    boolean columnWidthUnitsConsistent = AdhocWebService.areMetadataColumnUnitsConsistent(reportSpec, model);

    if (!columnWidthUnitsConsistent) {
        logger.error(Messages.getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$
    } else {
        double columnWidthScaleFactor = 1.0;
        int missingColumnWidthCount = 0;
        int columnWidthSumOfPercents;
        double defaultWidth;
        columnWidthSumOfPercents = AdhocWebService.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocWebService.getMissingColumnWidthCount(reportSpec, model);

        // if there are columns with no column width specified, figure out what percent we should use for them
        if (missingColumnWidthCount > 0) {
            if (columnWidthSumOfPercents < 100) {
                int remainingPercent = 100 - columnWidthSumOfPercents;
                defaultWidth = remainingPercent / missingColumnWidthCount;
                columnWidthSumOfPercents = 100;
            } else {
                defaultWidth = 10;
                columnWidthSumOfPercents += (missingColumnWidthCount * 10);
            }

            // fill in columns without column widths
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                if (property == null) {
                    property = new ColumnWidth(WidthType.PERCENT, defaultWidth);
                    columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property);
                }
            }
        }

        if (columnWidthSumOfPercents > 100) {
            columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents;
        }

        // now scale down if necessary
        if (columnWidthScaleFactor < 1.0) {
            for (int i = 0; i < columns.length; i++) {
                ColumnWidth property = (ColumnWidth) columns[i]
                        .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId());
                ColumnWidth newProperty = new ColumnWidth(property.getType(),
                        columnWidthScaleFactor * property.getWidth());
                columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty);
            }
        }

    }

    // ========== end column width stuff

    for (int i = 0; i < reportSpec.getField().length; i++) {
        Field field = reportSpec.getField()[i];
        LogicalColumn column = columns[i];

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

        // Template properties have the lowest priority, merge them last
        if (bUseTemplate) {
            Element templateDefaults = null;
            if (column.getDataType() != null) {
                templateDefaults = (Element) reportSpecTypeToElement
                        .get(AdhocWebService.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell
            }
            /*
             * NOTE: this merge of the template with the node's properties only sets the following properties:
             * format, fontname, fontsize, color, alignment, vertical-alignment, 
             */
            AdhocWebService.applyTemplate(field, templateDefaults);
        }
        AdhocWebService.applyDefaults(field);
    } // end for

    /*
     * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using
     * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it,
     * and some of the template.
     */
    ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream();
    ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding,
            (OutputStream) jfreeOutputStream);
    String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding);
    Document generatedJFreeDoc = null;
    try {
        generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, new PentahoEntityResolver());
    } catch (XmlParseException e) {
        String msg = Messages.getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$
        error(msg, e);
        throw new AdhocWebServiceException(msg, e);
    }

    /*
     * Merge template's /report/items element's attributes into the
     * generated document's /report/items element's attributes. There should not be any
     * conflict with the metadata, or the xreportspec in the reportXML param
     */
    if (bUseTemplate) {
        Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$
        List templateAttrs = templateItems.attributes(); // from the template's /report/items element
        Iterator templateAttrsIt = templateAttrs.iterator();

        while (templateAttrsIt.hasNext()) {
            Attribute attr = (Attribute) templateAttrsIt.next();
            String name = attr.getName();
            String value = attr.getText();

            Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$
            if (node != null) {
                node.setText(value);
            } else {
                reportItems.addAttribute(name, value);
            }
        }
        List templateElements = templateItems.elements();
        Iterator templateElementsIt = templateElements.iterator();
        while (templateElementsIt.hasNext()) {
            Element element = (Element) templateElementsIt.next();
            element.detach();
            reportItems.add(element);
        }
        /*
         * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate())
         * with the generated document can wait until last because none of the 
         * properties involved in this merge are settable by the metadata or the WAQR UI
         */
        ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream);
    } else {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(reportXMLEncoding);
        XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format);
        writer.write(generatedJFreeDoc);
        writer.close();
    }
}

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  .ja v a 2 s. com
    }

    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.pentaho.pms.ui.QueryBuilderDialog.java

License:Open Source License

public Document prettyPrint(Document document) {
    try {/*  www.j a  v a2 s  .  c  o m*/
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(document.getXMLEncoding());
        StringWriter stringWriter = new StringWriter();
        XMLWriter writer = new XMLWriter(stringWriter, format);
        // XMLWriter has a bug that is avoided if we reparse the document
        // prior to calling XMLWriter.write()
        writer.write(DocumentHelper.parseText(document.asXML()));
        writer.close();
        document = DocumentHelper.parseText(stringWriter.toString());
    } catch (Exception e) {
        e.printStackTrace();
        return (null);
    }
    return (document);
}

From source file:org.pentaho.supportutility.config.retriever.DataSourceRetriever.java

License:Open Source License

/**
 * writes fetched data to respective Xml
 * //ww  w  .  j  a  v a 2  s  . co  m
 * @param xml
 *            -string obtained from restful client
 * @param dirName
 *            -directory name of respective file
 * @param fileName
 *            -respective filename
 */
private void writeXml(String xml, String dirName, String fileName) {

    try {
        Document document = DocumentHelper.parseText(xml);
        OutputFormat format = OutputFormat.createPrettyPrint();

        XMLWriter writer = new XMLWriter(new FileWriter(dirName + File.separator + fileName), format);
        writer.write(document);
        writer.close();
    } catch (NullPointerException e) {
        e.getMessage();
    } catch (DocumentException e1) {
        e1.getMessage();
    } catch (IOException e) {
        e.getMessage();
    }

}

From source file:org.pentaho.supportutility.config.retriever.JackRabbitConfigRetriever.java

License:Open Source License

/**
 * reads jack-rabbit configurations//w w w .  j  av a2s  .c o m
 * 
 * @param dstPath
 * @param solutionPath
 */
public static void readJackRepository(File dstPath, String solutionPath) {

    File srcPath = new File(solutionPath + File.separator + SupportUtilConstant.PENTAHO_SYSTEM_DIR
            + File.separator + SupportUtilConstant.PENTAHO_JACKRABBIT + File.separator
            + SupportUtilConstant.JACK_REPOSITORY_XML);

    try {

        FileUtils.copyFileToDirectory(srcPath, dstPath);

        SAXReader reader = new SAXReader();
        Document document = reader.read(dstPath + File.separator + SupportUtilConstant.JACK_REPOSITORY_XML);

        Node fileSystem = document.selectSingleNode(SupportUtilConstant.JACK_FILESYSTEM);
        removeNode((Element) fileSystem);

        Node dataStore = document.selectSingleNode(SupportUtilConstant.JACK_DATASTORE);
        removeNode((Element) dataStore);

        Node workSpacefSystem = document.selectSingleNode(SupportUtilConstant.JACK_WORKSPACE_FILESYSTEM);
        removeNode((Element) workSpacefSystem);

        Node workSpacePManager = document.selectSingleNode(SupportUtilConstant.JACK_WORKSPACE_PERMANSGER);
        removeNode((Element) workSpacePManager);

        Node versioningfSystem = document.selectSingleNode(SupportUtilConstant.JACK_VERSIONING_FILESYSTEM);
        removeNode((Element) versioningfSystem);

        Node versioningfPManager = document.selectSingleNode(SupportUtilConstant.JACK_VERSIONING_PERMANSGER);
        removeNode((Element) versioningfPManager);

        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter output = new XMLWriter(
                new FileWriter(new File(dstPath + File.separator + SupportUtilConstant.JACK_REPOSITORY_XML)),
                format);
        output.write(document);
        output.close();

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

}

From source file:org.pentaho.supportutility.config.retriever.LicenseRetriever.java

License:Open Source License

@Override
protected void readConfiguration(Properties props) {

    String dirName = props.getProperty(SupportUtilConstant.SUPP_INFO_DEST_PATH) + File.separator
            + props.getProperty(SupportUtilConstant.SUPP_INF_DIR) + File.separator
            + SupportUtilConstant.LICENSE_DIR;

    if (createDestDirectory(dirName, null)) {
        // calls restful client to get license detail
        String licenseXml = RestFulClient.restFulService(getServerName(), SupportUtilConstant.LICENSE, props,
                webXMLPath);/*from  w  w  w.j  ava  2  s.co  m*/

        try {

            Document document = DocumentHelper.parseText(licenseXml);
            OutputFormat format = OutputFormat.createPrettyPrint();

            XMLWriter writer = new XMLWriter(
                    new FileWriter(dirName + File.separator + SupportUtilConstant.LICENSE_FILE_NAME), format);
            writer.write(document);

            writer.close();
        } catch (DocumentException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}