Example usage for org.dom4j.io XMLWriter close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying Writer

Usage

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

License:Open Source License

/**
 * Create the JFreeReport file.//from  w  w w . j a  v a 2 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.pms.ui.QueryBuilderDialog.java

License:Open Source License

public Document prettyPrint(Document document) {
    try {/*from  w  w  w .  j  a v a 2  s . co  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
 * /*from w  w w .j a v  a2s  . c o 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//from   www  . j av  a 2 s  . c om
 * 
 * @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);//w w  w .  ja  va  2s .  c o  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();
        }

    }

}

From source file:org.powermock.examples.dom4j.AbstractXMLRequestCreatorBase.java

License:Apache License

/**
 * Convert a dom4j xml document to a byte[].
 * /*from  ww w  .j a  v a 2  s  .  c  om*/
 * @param document
 *            The document to convert.
 * @return A <code>byte[]</code> representation of the xml document.
 * @throws IOException
 *             If an exception occurs when converting the document.
 */
public byte[] convertDocumentToByteArray(Document document) throws IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    XMLWriter writer = new XMLWriter(stream);
    byte[] documentAsByteArray = null;
    try {
        writer.write(document);
    } finally {
        writer.close();
        stream.flush();
        stream.close();
    }
    documentAsByteArray = stream.toByteArray();
    return documentAsByteArray;
}

From source file:org.projectforge.business.task.TaskTree.java

License:Open Source License

@Override
public String toString() {
    if (root == null) {
        return "<empty/>";
    }/* w  w  w  .  jav a  2 s. c  om*/
    final Document document = DocumentHelper.createDocument();
    final Element root = document.addElement("root");
    this.root.addXMLElement(root);
    // Pretty print the document to System.out
    final StringWriter sw = new StringWriter();
    String result = "";
    final XMLWriter writer = new XMLWriter(sw, OutputFormat.createPrettyPrint());
    try {
        writer.write(document);
        result = sw.toString();
    } catch (final IOException ex) {
        log.error(ex.getMessage(), ex);
    } finally {
        try {
            writer.close();
        } catch (final IOException ex) {
            log.error("Error while closing xml writer: " + ex.getMessage(), ex);
        }
    }
    return result;
}

From source file:org.projectforge.framework.xstream.XmlHelper.java

License:Open Source License

public static String toString(final Element el, final boolean prettyFormat) {
    if (el == null) {
        return "";
    }//from w w w  .  j a  v a2s.  com
    final StringWriter out = new StringWriter();
    final OutputFormat format = new OutputFormat();
    if (prettyFormat == true) {
        format.setNewlines(true);
        format.setIndentSize(2);
    }
    final XMLWriter writer = new XMLWriter(out, format);
    String result = null;
    try {
        writer.write(el);
        result = out.toString();
        writer.close();
    } catch (final IOException ex) {
        log.error(ex.getMessage(), ex);
    }
    return result;
}

From source file:org.ranji.longan.skeleton.ParentSkeleton.java

private static void createPomXmlFile(String projectName, String projectSimpleName, File projectDir) {
    File pomFile = new File(projectDir, "pom.xml");
    URL url = ParentSkeleton.class.getClassLoader().getResource("parent/pom.rj");
    SAXReader reader = new SAXReader();
    try {// w  w w  .  j a  v a  2 s. c o  m
        Document doc = reader.read(url);
        Element rootElm = doc.getRootElement();
        //-- 1. groupId
        Element groupIdElm = rootElm.element("groupId");
        groupIdElm.setText(projectName.trim());
        //-- 2. artifactId
        Element artifactIdElm = rootElm.element("artifactId");
        artifactIdElm.setText(projectSimpleName);
        //-- 3. name
        Element nameElm = rootElm.element("name");
        nameElm.setText(projectSimpleName);

        //-- 4. ?
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        try {
            XMLWriter writer = new XMLWriter(new FileWriter(pomFile), format);
            writer.write(doc);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

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

From source file:org.richfaces.cdk.generate.taglib.TaglibWriter.java

License:Open Source License

@Override
public void render(ComponentLibrary library) throws CdkException {
    TaglibGeneratorVisitor visitor = new TaglibGeneratorVisitor();
    library.accept(visitor, library);/*from  w  w w . j  a va2  s  .  com*/
    if (!visitor.isEmpty()) {
        Document document = visitor.getDocument();
        try {
            OutputFormat format1 = OutputFormat.createPrettyPrint();
            format1.setIndentSize(4);

            XMLWriter writer = new XMLWriter(getOutput(library), format1);
            writer.write(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace(); // TODO
        }
    }
}