Example usage for org.dom4j.io OutputFormat setEncoding

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

Introduction

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

Prototype

public void setEncoding(String encoding) 

Source Link

Document

DOCUMENT ME!

Usage

From source file:org.pentaho.actionsequence.dom.ActionSequenceDocument.java

License:Open Source License

public static Document prettyPrint(Document document) {
    try {//from   w w w  .  j  a  v  a2s . 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.actionsequence.dom.ActionSequenceDocument.java

License:Open Source License

public String toString() {
    String string = null;/*from w  w  w  . j  av  a  2 s  . co  m*/
    try {
        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 tempDocument = DocumentHelper.parseText(stringWriter.toString());
        string = tempDocument.getRootElement().asXML();
    } catch (Exception e) {
        string = super.toString();
    }
    return string;
}

From source file:org.pentaho.di.trans.steps.rssoutput.RssOutput.java

License:Apache License

public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (RssOutputMeta) smi;/*from  w  w w  . jav a  2s. c  o  m*/
    data = (RssOutputData) sdi;

    Object[] r = getRow(); // this also waits for a previous step to be finished.

    if (r == null) { // no more input to be expected...

        if (!first) {
            if (!meta.isCustomRss()) {
                // No more input..so write and close the file.
                WriteToFile(data.channeltitlevalue, data.channellinkvalue, data.channeldescriptionvalue,
                        data.channelpubdatevalue, data.channelcopyrightvalue, data.channelimagelinkvalue,
                        data.channelimagedescriptionvalue, data.channelimagelinkvalue,
                        data.channelimageurlvalue, data.channellanguagevalue, data.channelauthorvalue);
            } else {

                // Write to document
                OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint();
                // Set encoding ...
                if (Utils.isEmpty(meta.getEncoding())) {
                    format.setEncoding("iso-8859-1");
                } else {
                    format.setEncoding(meta.getEncoding());
                }

                try {
                    XMLWriter writer = new XMLWriter(new FileWriter(new File(data.filename)), format);
                    writer.write(data.document);
                    writer.close();
                } catch (Exception e) {
                    // Ignore errors
                } finally {
                    data.document = null;
                }

            }
        }
        setOutputDone();
        return false;
    }

    if (first) {
        first = false;
        data.inputRowMeta = getInputRowMeta();
        data.outputRowMeta = data.inputRowMeta.clone();
        meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);
        // Let's check for filename...

        if (meta.isFilenameInField()) {
            if (Utils.isEmpty(meta.getFileNameField())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameFieldMissing"));
                setErrors(1);
                stopAll();
                return false;
            }

            // get filename field index
            data.indexOfFieldfilename = data.inputRowMeta.indexOfValue(meta.getFileNameField());
            if (data.indexOfFieldfilename < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getFileNameField()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getFileNameField()));
            }

        } else {
            data.filename = buildFilename();
        }

        // Check if filename is empty..
        if (Utils.isEmpty(data.filename)) {
            logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty"));
            throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty"));
        }

        // Do we need to create parent folder ?
        if (meta.isCreateParentFolder()) {
            // Check for parent folder
            FileObject parentfolder = null;
            try {
                // Get parent folder
                parentfolder = KettleVFS.getFileObject(data.filename, getTransMeta()).getParent();
                if (!parentfolder.exists()) {
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.ParentFolderExists",
                                parentfolder.getName().toString()));
                    }
                    parentfolder.createFolder();
                    if (log.isDetailed()) {
                        logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                                parentfolder.getName().toString()));
                    }
                }
            } catch (Exception e) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                        parentfolder.getName().toString()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder",
                        parentfolder.getName().toString()));

            } finally {
                if (parentfolder != null) {
                    try {
                        parentfolder.close();
                    } catch (Exception ex) { /* Ignore */
                    }
                }
            }
        }

        if (!meta.isCustomRss()) {
            // Let's check for mandatory fields ...
            if (Utils.isEmpty(meta.getChannelTitle())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelTitleMissing"));
                setErrors(1);
                stopAll();
                return false;
            }
            if (Utils.isEmpty(meta.getChannelDescription())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelDescription"));
                setErrors(1);
                stopAll();
                return false;
            }
            if (Utils.isEmpty(meta.getChannelLink())) {
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelLink"));
                setErrors(1);
                stopAll();
                return false;
            }

            // Let's take the index of channel title field ...
            data.indexOfFieldchanneltitle = data.inputRowMeta.indexOfValue(meta.getChannelTitle());
            if (data.indexOfFieldchanneltitle < 0) {
                // The field is unreachable !
                logError(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle()));
                throw new KettleException(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle()));
            }
            data.channeltitlevalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneltitle);

            // Let's take the index of channel description field ...
            data.indexOfFieldchanneldescription = data.inputRowMeta.indexOfValue(meta.getChannelDescription());
            if (data.indexOfFieldchanneldescription < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getChannelDescription()));
                throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                        meta.getChannelDescription()));
            }

            data.channeldescriptionvalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneldescription);

            // Let's take the index of channel link field ...
            data.indexOfFieldchannellink = data.inputRowMeta.indexOfValue(meta.getChannelLink());
            if (data.indexOfFieldchannellink < 0) {
                // The field is unreachable !
                logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink()));
                throw new KettleException(
                        BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink()));
            }

            data.channellinkvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellink);

            if (!Utils.isEmpty(meta.getItemTitle())) {
                // Let's take the index of item title field ...
                data.indexOfFielditemtitle = data.inputRowMeta.indexOfValue(meta.getItemTitle());
                if (data.indexOfFielditemtitle < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemTitle()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemTitle()));
                }
            }

            if (!Utils.isEmpty(meta.getItemDescription())) {
                // Let's take the index of item description field ...
                data.indexOfFielditemdescription = data.inputRowMeta.indexOfValue(meta.getItemDescription());
                if (data.indexOfFielditemdescription < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemDescription()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemDescription()));
                }
            }
            if (meta.AddGeoRSS()) {
                if (Utils.isEmpty(meta.getGeoPointLong())) {
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLatEmpty"));
                }
                if (Utils.isEmpty(meta.getGeoPointLong())) {
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLongEmpty"));
                }

                // Let's take the index of item geopointX field ...
                data.indexOfFielditempointx = data.inputRowMeta.indexOfValue(meta.getGeoPointLat());
                if (data.indexOfFielditempointx < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLat()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLat()));
                }
                // Let's take the index of item geopointY field ...
                data.indexOfFielditempointy = data.inputRowMeta.indexOfValue(meta.getGeoPointLong());
                if (data.indexOfFielditempointy < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLong()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getGeoPointLong()));
                }
            }

            // It's time to check non empty fields !
            // Channel PubDate field ...
            if (!Utils.isEmpty(meta.getChannelPubDate())) {
                data.indexOfFieldchannelpubdate = data.inputRowMeta.indexOfValue(meta.getChannelPubDate());
                if (data.indexOfFieldchannelpubdate < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelPubDate()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelPubDate()));
                }

                data.channelpubdatevalue = data.inputRowMeta.getDate(r, data.indexOfFieldchannelpubdate);
            }
            // Channel Language field ...
            if (!Utils.isEmpty(meta.getChannelLanguage())) {
                data.indexOfFieldchannellanguage = data.inputRowMeta.indexOfValue(meta.getChannelLanguage());
                if (data.indexOfFieldchannellanguage < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelLanguage()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelLanguage()));
                }

                data.channellanguagevalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellanguage);
            }

            // Channel Copyright field ...
            if (!Utils.isEmpty(meta.getChannelCopyright())) {
                data.indexOfFieldchannelcopyright = data.inputRowMeta.indexOfValue(meta.getChannelCopyright());
                if (data.indexOfFieldchannelcopyright < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelCopyright()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelCopyright()));
                }

                data.channelcopyrightvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelcopyright);
            }

            // Channel Author field ...
            if (!Utils.isEmpty(meta.getChannelAuthor())) {
                data.indexOfFieldchannelauthor = data.inputRowMeta.indexOfValue(meta.getChannelAuthor());
                if (data.indexOfFieldchannelauthor < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelAuthor()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getChannelAuthor()));
                }

                data.channelauthorvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelauthor);
            }

            // Channel Image field ...
            if (meta.AddImage()) {
                // Channel image title
                if (!Utils.isEmpty(meta.getChannelImageTitle())) {
                    data.indexOfFieldchannelimagetitle = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageTitle());
                    if (data.indexOfFieldchannelimagetitle < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageTitle()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageTitle()));
                    }

                    data.channelimagetitlevalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagetitle);
                }

                // Channel link title
                if (!Utils.isEmpty(meta.getChannelImageLink())) {
                    data.indexOfFieldchannelimagelink = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageLink());
                    if (data.indexOfFieldchannelimagelink < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageLink()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageLink()));
                    }

                    data.channelimagelinkvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagelink);
                }

                // Channel url title
                if (!Utils.isEmpty(meta.getChannelImageUrl())) {
                    data.indexOfFieldchannelimageurl = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageUrl());
                    if (data.indexOfFieldchannelimageurl < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageUrl()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageUrl()));
                    }

                    data.channelimageurlvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimageurl);
                }

                // Channel description title
                if (!Utils.isEmpty(meta.getChannelImageDescription())) {
                    data.indexOfFieldchannelimagedescription = data.inputRowMeta
                            .indexOfValue(meta.getChannelImageDescription());
                    if (data.indexOfFieldchannelimagedescription < 0) {
                        // The field is unreachable !
                        logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageDescription()));
                        throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                                meta.getChannelImageDescription()));
                    }

                    data.channelimagedescriptionvalue = data.inputRowMeta.getString(r,
                            data.indexOfFieldchannelimagedescription);
                }

            }

            // Item link field ...
            if (!Utils.isEmpty(meta.getItemLink())) {
                data.indexOfFielditemlink = data.inputRowMeta.indexOfValue(meta.getItemLink());
                if (data.indexOfFielditemlink < 0) {
                    // The field is unreachable !
                    logError(
                            BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink()));
                    throw new KettleException(
                            BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink()));
                }

            }

            // Item pubdate field ...
            if (!Utils.isEmpty(meta.getItemPubDate())) {
                data.indexOfFielditempubdate = data.inputRowMeta.indexOfValue(meta.getItemPubDate());
                if (data.indexOfFielditempubdate < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemPubDate()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemPubDate()));
                }
            }

            // Item author field ...
            if (!Utils.isEmpty(meta.getItemAuthor())) {
                data.indexOfFielditemauthor = data.inputRowMeta.indexOfValue(meta.getItemAuthor());
                if (data.indexOfFielditemauthor < 0) {
                    // The field is unreachable !
                    logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemAuthor()));
                    throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField",
                            meta.getItemAuthor()));
                }
            }
        } else {
            // Custom RSS
            // Check Custom channel fields
            data.customchannels = new int[meta.getChannelCustomFields().length];
            for (int i = 0; i < meta.getChannelCustomFields().length; i++) {
                data.customchannels[i] = data.inputRowMeta.indexOfValue(meta.getChannelCustomFields()[i]);
                if (data.customchannels[i] < 0) { // couldn't find field!

                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "RssOutput.Exception.FieldRequired", meta.getChannelCustomFields()[i]));
                }
            }
            // Check Custom channel fields
            data.customitems = new int[meta.getItemCustomFields().length];
            for (int i = 0; i < meta.getItemCustomFields().length; i++) {
                data.customitems[i] = data.inputRowMeta.indexOfValue(meta.getItemCustomFields()[i]);
                if (data.customitems[i] < 0) { // couldn't find field!

                    throw new KettleStepException(BaseMessages.getString(PKG,
                            "RssOutput.Exception.FieldRequired", meta.getItemCustomFields()[i]));
                }
            }
            // Prepare Output RSS Custom document
            data.document = DocumentHelper.createDocument();
            data.rssElement = data.document.addElement("rss");
            data.rssElement.addAttribute("version", "2.0");
            // add namespaces here ...
            for (int i = 0; i < meta.getNameSpaces().length; i++) {
                data.rssElement.addNamespace(environmentSubstitute(meta.getNameSpacesTitle()[i]),
                        environmentSubstitute(meta.getNameSpaces()[i]));
            }

            // Add channel
            data.channel = data.rssElement.addElement("channel");

            // Set channel Only the first time ...
            for (int i = 0; i < data.customchannels.length; i++) {
                String channelname = environmentSubstitute(meta.getChannelCustomTags()[i]);
                String channelvalue = data.inputRowMeta.getString(r, data.customchannels[i]);

                if (log.isDetailed()) {
                    logDetailed("outputting channel value <" + channelname + ">" + channelvalue + "<"
                            + channelname + "/>");
                }

                // add Channel
                Element channeltag = data.channel.addElement(channelname);
                channeltag.setText(channelvalue);

            }
        }
    } // end test first time

    // Let's get value for each item...
    if (!meta.isCustomRss()) {
        String itemtitlevalue = null;
        String itemauthorvalue = null;
        String itemlinkvalue = null;
        Date itemdatevalue = null;
        String itemdescvalue = null;
        String itemgeopointx = null;
        String itemgeopointy = null;

        if (data.indexOfFielditemtitle > -1) {
            itemtitlevalue = data.inputRowMeta.getString(r, data.indexOfFielditemtitle);
        }
        if (data.indexOfFielditemauthor > -1) {
            itemauthorvalue = data.inputRowMeta.getString(r, data.indexOfFielditemauthor);
        }
        if (data.indexOfFielditemlink > -1) {
            itemlinkvalue = data.inputRowMeta.getString(r, data.indexOfFielditemlink);
        }
        if (data.indexOfFielditempubdate > -1) {
            itemdatevalue = data.inputRowMeta.getDate(r, data.indexOfFielditempubdate);
        }
        if (data.indexOfFielditemdescription > -1) {
            itemdescvalue = data.inputRowMeta.getString(r, data.indexOfFielditemdescription);
        }
        if (data.indexOfFielditempointx > -1) {
            itemgeopointx = data.inputRowMeta.getString(r, data.indexOfFielditempointx);
        }
        if (data.indexOfFielditempointy > -1) {
            itemgeopointy = data.inputRowMeta.getString(r, data.indexOfFielditempointy);
        }

        // Now add entry ..
        if (!createEntry(itemauthorvalue, itemtitlevalue, itemlinkvalue, itemdatevalue, itemdescvalue,
                itemgeopointx, itemgeopointy)) {
            throw new KettleException("Error adding item to feed");
        }
    } else {

        // Set item tag at each row received
        if (meta.isDisplayItem()) {
            data.itemtag = data.channel.addElement("item");
        }
        for (int i = 0; i < data.customitems.length; i++) {
            // get item value and name
            String itemname = environmentSubstitute(meta.getItemCustomTags()[i]);
            String itemvalue = data.inputRowMeta.getString(r, data.customitems[i]);

            if (log.isDetailed()) {
                logDetailed("outputting item value <" + itemname + ">" + itemvalue + "<" + itemname + "/>");
            }

            // add Item
            if (meta.isDisplayItem()) {
                Element itemtagsub = data.itemtag.addElement(itemname);
                itemtagsub.setText(itemvalue);
            } else {
                // display item at channel level
                Element temp = data.channel.addElement(itemname);
                temp.setText(itemvalue);
            }
        }
    }

    try {
        putRow(data.outputRowMeta, r); // in case we want it to go further...
        incrementLinesOutput();

        if (checkFeedback(getLinesOutput())) {
            if (log.isDebug()) {
                logDebug(BaseMessages.getString(PKG, "RssOutput.Log.Linenr", "" + getLinesOutput()));
            }
        }

    } catch (KettleStepException e) {
        logError(BaseMessages.getString(PKG, "RssOutputMeta.Log.ErrorInStep") + e.getMessage());
        setErrors(1);
        stopAll();
        setOutputDone(); // signal end to receiver(s)
        return false;
    }

    return true;
}

From source file:org.pentaho.jfreereport.wizard.utility.report.ReportGenerationUtility.java

License:Open Source License

/**
 * From the report description in the <param>reportSpec</param> parameter, create 
 * a JFree Report report definition in XML format, and return the XML via
 * the <param>outputStream</param> parameter.
 * //www  .ja v  a  2 s.c  o m
 * @param reportSpec
 * @param outputStream
 * @param encoding
 * @param pageWidth
 * @param pageHeight
 * @param createTotalColumn
 * @param totalColumnName
 * @param totalColumnWidth
 * @param spacerWidth
 */
public static void createJFreeReportXML(ReportSpec reportSpec, OutputStream outputStream, String encoding,
        int pageWidth, int pageHeight, boolean createTotalColumn, String totalColumnName, int totalColumnWidth,
        int spacerWidth) {

    Field fields[] = reportSpec.getField();
    Field details[] = ReportSpecUtility.getDetails(fields);
    Field groups[] = ReportSpecUtility.getGroups(fields);
    List spaceFields = setupSpaceFields(fields);
    try {
        boolean expressionExists = ReportSpecUtility.doesExpressionExist(fields);
        setupDetailFieldWidths(reportSpec, details);
        int itemRowHeight = ReportSpecUtility.getRowHeight(reportSpec, details);
        // dom4j
        Document document = DOMDocumentFactory.getInstance().createDocument();

        document.addDocType("report", "-//JFreeReport//DTD report definition//EN//simple/version 0.8.5", //$NON-NLS-1$//$NON-NLS-2$
                "http://jfreereport.sourceforge.net/report-085.dtd"); //$NON-NLS-1$
        org.dom4j.Element reportNode = document.addElement("report"); //$NON-NLS-1$
        Element configuration = reportNode.addElement(CONFIGURATION_ELEMENT_NAME);

        if (null != encoding) {
            document.setXMLEncoding(encoding);
            addEncoding(configuration, encoding);
        }

        // reportNode.addAttribute("xmlns", "http://jfreereport.sourceforge.net/namespaces/reports/legacy/simple");
        // add parser-config to generated report
        addParserConfig(reportSpec, reportNode);
        // set report name
        reportNode.addAttribute(NAME_ATTRIBUTE_NAME, StringEscapeUtils.escapeXml(reportSpec.getReportName()));
        // set orientation
        reportNode.addAttribute("orientation", reportSpec.getOrientation()); //$NON-NLS-1$
        // set page-format or page width/height
        setPageFormat(reportSpec, reportNode, pageWidth, pageHeight);
        // set margins
        setMargins(reportSpec, reportNode);
        if (reportSpec.getIncludeSrc() != null && !"".equalsIgnoreCase(reportSpec.getIncludeSrc())) { //$NON-NLS-1$
            org.dom4j.Element includeElement = reportNode.addElement("include"); //$NON-NLS-1$
            includeElement.addAttribute("src", "file://" + reportSpec.getIncludeSrc().replace('\\', '/')); //$NON-NLS-1$ //$NON-NLS-2$
        }
        // set watermark
        setWatermark(reportSpec, reportNode);
        Element groupsNode = reportNode.addElement("groups"); //$NON-NLS-1$
        Element itemsNode = reportNode.addElement("items"); //$NON-NLS-1$
        Element functionNode = reportNode.addElement("functions"); //$NON-NLS-1$
        if (reportSpec.getChart() != null && reportSpec.getUseChart()) {
            Element reportHeaderElement = reportNode.addElement("reportheader"); //$NON-NLS-1$
            addChartElement(reportSpec, null, functionNode, reportHeaderElement, 0);
        }
        setItemsFont(reportSpec, itemsNode);
        // create banding rectangle if banding is turned on
        createRowBanding(reportSpec, details, itemsNode, functionNode, itemRowHeight);
        // programatically create details section
        processDetailsSection(reportSpec, details, groups, itemsNode, functionNode, itemRowHeight);
        // programatically create groups section
        processGroupsSection(reportSpec, details, groups, groupsNode, functionNode, itemRowHeight,
                expressionExists, spacerWidth);

        // spit out report xml definition
        OutputFormat format = OutputFormat.createPrettyPrint();
        if (null != encoding) {
            format.setEncoding(encoding); // TODO sbarkull, not sure this is necessary
        }
        XMLWriter writer = new XMLWriter(outputStream, format);
        writer.write(document);
        writer.close();
        // put _SPACE_ fields back in place as they were
        for (int i = 0; i < spaceFields.size(); i++) {
            Field f = (Field) spaceFields.get(i);
            f.setName("_SPACE_" + (i + 1)); //$NON-NLS-1$
            f.setDisplayName("_SPACE_" + (i + 1)); //$NON-NLS-1$
        }
    } catch (Exception e) {
        getLogger().error(e.getMessage(), e);
    }
}

From source file:org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper.java

License:Open Source License

@Deprecated
protected synchronized void writeDataSources(DataSources dataSources) {

    File dataSourcesFile;//from  w  w  w .  ja v a  2s .  co  m
    try {
        dataSourcesFile = new File(new URL(dataSourcesConfig).getFile()); // dataSourcesConfigResource.getFile();
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(Messages.getInstance()
                .getErrorString("MondrianCatalogHelper.ERROR_0005_RESOURCE_NOT_AVAILABLE"), e, Reason.GENERAL); //$NON-NLS-1$
    }

    Writer sxml;
    try {
        sxml = new FileWriter(dataSourcesFile);
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(e);
    }
    StringWriter sw = new StringWriter();
    XMLOutput pxml = new XMLOutput(sw);
    pxml.print("<?xml version=\"1.0\"?>\n"); //$NON-NLS-1$
    dataSources.displayXML(pxml, 0);
    Document doc = null;
    try {
        doc = XmlDom4JHelper.getDocFromString(sw.toString(), new PentahoEntityResolver());
    } catch (XmlParseException e) {
        throw new MondrianCatalogServiceException(e);
    }

    // pretty print
    try {
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding(doc.getXMLEncoding());
        XMLWriter writer = new XMLWriter(sxml, format);
        writer.write(doc);
        writer.close();
        // CleanXmlHelper.saveDomToWriter(doc, sxml);
    } catch (IOException e) {
        throw new MondrianCatalogServiceException(e);
    }

    IOUtils.closeQuietly(sxml);
}

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

License:Open Source License

/**
 * Create the JFreeReport file./* www. ja  v  a  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 repository
 * @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 = AdhocContentGenerator.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 = AdhocContentGenerator.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 = AdhocContentGenerator.getSumOfMetadataColumnWidths(reportSpec, model);
        missingColumnWidthCount = AdhocContentGenerator.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(AdhocContentGenerator.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, 
             */
            AdhocContentGenerator.applyTemplate(field, templateDefaults);
        }
        AdhocContentGenerator.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.AdhocContentGenerator.java

License:Open Source License

public void createMQLQueryActionSequence(final String domainId, final String modelId, final String tableId,
        final String columnId, final String searchStr, final OutputStream outputStream,
        final String userSessionName) throws IOException {

    Document document = DOMDocumentFactory.getInstance().createDocument();
    document.setXMLEncoding(LocaleHelper.getSystemEncoding());
    Element actionSeqElement = document.addElement("action-sequence"); //$NON-NLS-1$
    actionSeqElement.addElement("version").setText("1"); //$NON-NLS-1$ //$NON-NLS-2$
    actionSeqElement.addElement("title").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$
    actionSeqElement.addElement("logging-level").setText("ERROR"); //$NON-NLS-1$ //$NON-NLS-2$
    Element documentationElement = actionSeqElement.addElement("documentation"); //$NON-NLS-1$
    Element authorElement = documentationElement.addElement("author"); //$NON-NLS-1$
    if (userSessionName != null) {
        authorElement.setText(userSessionName);
    } else {//from w  w  w .jav  a  2 s.  co  m
        authorElement.setText("Web Query & Reporting"); //$NON-NLS-1$
    }
    documentationElement.addElement("description") //$NON-NLS-1$
            .setText("Temporary action sequence used by Web Query & Reporting"); //$NON-NLS-1$
    documentationElement.addElement("result-type").setText("result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    Element outputsElement = actionSeqElement.addElement("outputs"); //$NON-NLS-1$
    Element reportTypeElement = outputsElement.addElement("query_result"); //$NON-NLS-1$
    reportTypeElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    Element destinationsElement = reportTypeElement.addElement("destinations"); //$NON-NLS-1$
    destinationsElement.addElement("response").setText("query_result"); //$NON-NLS-1$ //$NON-NLS-2$

    Element actionsElement = actionSeqElement.addElement("actions"); //$NON-NLS-1$
    Element actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$
    Element actionOutputsElement = actionDefinitionElement.addElement("action-outputs"); //$NON-NLS-1$
    Element ruleResultElement = actionOutputsElement.addElement("query-result"); //$NON-NLS-1$
    ruleResultElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$
    ruleResultElement.addAttribute("mapping", "query_result"); //$NON-NLS-1$ //$NON-NLS-2$
    actionDefinitionElement.addElement("component-name").setText("MQLRelationalDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$
    actionDefinitionElement.addElement("action-type").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$
    Element componentDefinitionElement = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$

    // log SQL flag
    if ("true".equals(PentahoSystem.getSystemSetting("adhoc-preview-log-sql", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        componentDefinitionElement.addElement("logSql").addCDATA("true"); //$NON-NLS-1$ //$NON-NLS-2$
    }
    // componentDefinitionElement.addElement("query").addCDATA(createMQLQueryXml(domainId, modelId, tableId, columnId, searchStr)); //$NON-NLS-1$
    addMQLQueryXml(componentDefinitionElement, domainId, modelId, tableId, columnId, searchStr);

    // end action-definition for JFreeReportComponent
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(LocaleHelper.getSystemEncoding());
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(document);
    writer.close();
}

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

License:Open Source License

protected ByteArrayOutputStream exportDocumentAsByteArrayOutputStream(Document document) throws IOException {
    ByteArrayOutputStream xactionOutputStream = new ByteArrayOutputStream();
    // end action-definition for JFreeReportComponent
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(LocaleHelper.getSystemEncoding());
    XMLWriter writer = new XMLWriter(xactionOutputStream, format);
    writer.write(document);/*from  www  .  j a  v a2  s.  co  m*/
    writer.close();
    return xactionOutputStream;
}

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

License:Open Source License

/**
 * Create the JFreeReport file.//from  www. j  ava  2  s.  co  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 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.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());
        }//  www.  j  a  v a2s .  c o  m
    }
    XMLWriter writer = new XMLWriter(outputStream, format);
    writer.write(doc);
    writer.flush();
}