Search in sources :

Example 1 with IApplicationContext

use of org.pentaho.platform.api.engine.IApplicationContext in project pentaho-platform by pentaho.

the class ChartComponent method executeAction.

@Override
protected boolean executeAction() {
    int height = -1;
    int width = -1;
    // $NON-NLS-1$
    String title = "";
    Node chartDocument = null;
    IPentahoResultSet data = (IPentahoResultSet) getInputValue(ChartComponent.CHART_DATA_PROP);
    if (!data.isScrollable()) {
        // $NON-NLS-1$
        getLogger().debug("ResultSet is not scrollable. Copying into memory");
        IPentahoResultSet memSet = data.memoryCopy();
        data.close();
        data = memSet;
    }
    String urlTemplate = (String) getInputValue(ChartComponent.URL_TEMPLATE);
    Node chartAttributes = null;
    String chartAttributeString = null;
    if (getInputNames().contains(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        chartAttributeString = getInputStringValue(ChartComponent.CHART_ATTRIBUTES_PROP);
    } else if (isDefinedResource(ChartComponent.CHART_ATTRIBUTES_PROP)) {
        IActionSequenceResource resource = getResource(ChartComponent.CHART_ATTRIBUTES_PROP);
        chartAttributeString = getResourceAsString(resource);
    }
    // Realize chart attributes as an XML document
    if (chartAttributeString != null) {
        try {
            chartDocument = XmlDom4JHelper.getDocFromString(chartAttributeString, new PentahoEntityResolver());
        } catch (XmlParseException e) {
            getLogger().error(Messages.getInstance().getString("ChartComponent.ERROR_0005_CANT_DOCUMENT_FROM_STRING"), // $NON-NLS-1$
            e);
            return false;
        }
        chartAttributes = chartDocument.selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);
        if (chartAttributes == null) {
            chartAttributes = chartDocument.selectSingleNode(ChartComponent.ALTERNATIVE_CHART_ATTRIBUTES_PROP);
        }
    }
    // Default chart attributes are in the component-definition section of the action definition.
    if (chartAttributes == null) {
        chartAttributes = getComponentDefinition(true).selectSingleNode(ChartComponent.CHART_ATTRIBUTES_PROP);
    }
    // have an urlTemplate attribute
    if ((urlTemplate == null) || (urlTemplate.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE) != null) {
            urlTemplate = chartAttributes.selectSingleNode(ChartComponent.URL_TEMPLATE).getText();
        }
    }
    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String parameterName = (String) getInputValue(ChartComponent.PARAMETER_NAME);
    if ((parameterName == null) || (parameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME) != null) {
            parameterName = chartAttributes.selectSingleNode(ChartComponent.PARAMETER_NAME).getText();
        }
    }
    // These parameters are replacement variables parsed into the
    // urlTemplate specifically when we have a URL that is a drill-through
    // link in a chart intended to drill down into the chart data.
    String outerParameterName = (String) getInputValue(ChartComponent.OUTER_PARAMETER_NAME);
    if ((outerParameterName == null) || (outerParameterName.length() == 0)) {
        if (chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME) != null) {
            outerParameterName = chartAttributes.selectSingleNode(ChartComponent.OUTER_PARAMETER_NAME).getText();
        }
    }
    String chartType = chartAttributes.selectSingleNode(ChartDefinition.TYPE_NODE_NAME).getText();
    // --------------- This code allows inputs to override the chartAttributes
    // of width, height, and title
    Object widthObj = getInputValue(ChartDefinition.WIDTH_NODE_NAME);
    if (widthObj != null) {
        width = Integer.parseInt(widthObj.toString());
        if (width != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.WIDTH_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.WIDTH_NODE_NAME).setText(Integer.toString(width));
        }
    }
    Object heightObj = getInputValue(ChartDefinition.HEIGHT_NODE_NAME);
    if (heightObj != null) {
        height = Integer.parseInt(heightObj.toString());
        if (height != -1) {
            if (chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME) == null) {
                ((Element) chartAttributes).addElement(ChartDefinition.HEIGHT_NODE_NAME);
            }
            chartAttributes.selectSingleNode(ChartDefinition.HEIGHT_NODE_NAME).setText(Integer.toString(height));
        }
    }
    Object titleObj = getInputValue(ChartDefinition.TITLE_NODE_NAME);
    if (titleObj != null) {
        if (chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME) == null) {
            ((Element) chartAttributes).addElement(ChartDefinition.TITLE_NODE_NAME);
        }
        chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME).setText(titleObj.toString());
    }
    // ----------------End of Override
    // ---------------Feed the Title and Subtitle information through the input substitution
    Node titleNode = chartAttributes.selectSingleNode(ChartDefinition.TITLE_NODE_NAME);
    if (titleNode != null) {
        String titleStr = titleNode.getText();
        if (titleStr != null) {
            title = titleStr;
            String newTitle = applyInputsToFormat(titleStr);
            titleNode.setText(newTitle);
        }
    }
    List subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);
    if ((subtitles == null) || (subtitles.isEmpty())) {
        Node subTitlesNode = chartAttributes.selectSingleNode(ChartDefinition.SUBTITLES_NODE_NAME);
        if (subTitlesNode != null) {
            subtitles = chartAttributes.selectNodes(ChartDefinition.SUBTITLE_NODE_NAME);
        }
    } else {
        // log a deprecation warning for this property...
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_DEPRECATED_CHILD", ChartDefinition.SUBTITLE_NODE_NAME, // $NON-NLS-1$
        ChartDefinition.SUBTITLES_NODE_NAME));
        getLogger().warn(Messages.getInstance().getString("CHART.WARN_PROPERTY_WILL_NOT_VALIDATE", // $NON-NLS-1$
        ChartDefinition.SUBTITLE_NODE_NAME));
    }
    if (subtitles != null) {
        for (Iterator iter = subtitles.iterator(); iter.hasNext(); ) {
            Node subtitleNode = (Node) iter.next();
            if (subtitleNode != null) {
                String subtitleStr = subtitleNode.getText();
                if (subtitleStr != null) {
                    String newSubtitle = applyInputsToFormat(subtitleStr);
                    subtitleNode.setText(newSubtitle);
                }
            }
        }
    }
    // ----------------End of Format
    // Determine if we are going to read the chart data set by row or by column
    boolean byRow = false;
    if (getInputStringValue(ChartComponent.BY_ROW_PROP) != null) {
        byRow = Boolean.valueOf(getInputStringValue(ChartComponent.BY_ROW_PROP)).booleanValue();
    }
    if (height == -1) {
        height = // $NON-NLS-1$
        (int) getInputLongValue(ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.HEIGHT_NODE_NAME, 50);
    }
    if (width == -1) {
        width = // $NON-NLS-1$
        (int) getInputLongValue(ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.WIDTH_NODE_NAME, 100);
    }
    if (title.length() <= 0) {
        // $NON-NLS-1$
        title = getInputStringValue(ChartComponent.CHART_ATTRIBUTES_PROP + "/" + ChartDefinition.TITLE_NODE_NAME);
    }
    // Select the right dataset to use based on the chart type
    // Default to category dataset
    String datasetType = ChartDefinition.CATEGORY_DATASET_STR;
    boolean isStacked = false;
    Node datasetTypeNode = chartAttributes.selectSingleNode(ChartDefinition.DATASET_TYPE_NODE_NAME);
    if (datasetTypeNode != null) {
        datasetType = datasetTypeNode.getText();
    }
    Dataset dataDefinition = null;
    if (ChartDefinition.XY_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
        dataDefinition = new XYSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.TIME_SERIES_COLLECTION_STR.equalsIgnoreCase(datasetType)) {
        Node stackedNode = chartAttributes.selectSingleNode(ChartDefinition.STACKED_NODE_NAME);
        if (stackedNode != null) {
            isStacked = Boolean.valueOf(stackedNode.getText()).booleanValue();
        }
        if ((isStacked) && (ChartDefinition.AREA_CHART_STR.equalsIgnoreCase(chartType))) {
            dataDefinition = new TimeTableXYDatasetChartDefinition(data, byRow, chartAttributes, getSession());
        } else {
            dataDefinition = new TimeSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
        }
    } else if (ChartDefinition.PIE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new PieDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.DIAL_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new DialWidgetDefinition(data, byRow, chartAttributes, width, height, getSession());
    } else if (ChartDefinition.BAR_LINE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new BarLineChartDefinition(data, byRow, chartAttributes, getSession());
    } else if (ChartDefinition.BUBBLE_CHART_STR.equalsIgnoreCase(chartType)) {
        dataDefinition = new XYZSeriesCollectionChartDefinition(data, byRow, chartAttributes, getSession());
    } else {
        dataDefinition = new CategoryDatasetChartDefinition(data, byRow, chartAttributes, getSession());
    }
    // Determine what we are sending back - Default to OUTPUT_PNG output
    // OUTPUT_PNG = the chart gets written to a file in .png format
    // OUTPUT_SVG = the chart gets written to a file in .svg (XML) format
    // OUTPUT_CHART = the chart in a byte stream gets stored as as an IContentItem
    // OUTPUT_PNG_BYTES = the chart gets sent as a byte stream in .png format
    int outputType = JFreeChartEngine.OUTPUT_PNG;
    if (getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP) != null) {
        if (ChartComponent.SVG_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_SVG;
        } else if (ChartComponent.CHART_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_CHART;
        } else if (ChartComponent.PNG_BYTES_TYPE.equalsIgnoreCase(getInputStringValue(ChartComponent.OUTPUT_TYPE_PROP))) {
            outputType = JFreeChartEngine.OUTPUT_PNG_BYTES;
        }
    }
    boolean keepTempFile = false;
    if (isDefinedInput(KEEP_TEMP_FILE_PROP)) {
        keepTempFile = getInputBooleanValue(KEEP_TEMP_FILE_PROP, false);
    }
    JFreeChart chart = null;
    switch(outputType) {
        /**
         ************************** OUTPUT_PNG_BYTES ********************************************
         */
        case JFreeChartEngine.OUTPUT_PNG_BYTES:
            // $NON-NLS-1$
            chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this);
            // TODO Shouldn't the mime types and other strings here be constant somewhere? Where do we
            // put this type of general info ?
            // $NON-NLS-1$
            String mimeType = "image/png";
            // $NON-NLS-1$ //$NON-NLS-2$
            IContentItem contentItem = getOutputItem("chartdata", mimeType, ".png");
            contentItem.setMimeType(mimeType);
            try {
                OutputStream output = contentItem.getOutputStream(getActionName());
                ChartUtilities.writeChartAsPNG(output, chart, width, height);
            } catch (Exception e) {
                // $NON-NLS-1$
                error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0004_CANT_CREATE_IMAGE"), e);
                return false;
            }
            break;
        /**
         ************************** OUTPUT_SVG && OUTPUT_PNG ************************************
         */
        case JFreeChartEngine.OUTPUT_SVG:
        case JFreeChartEngine.OUTPUT_PNG:
            // Don't include the map in a file if HTML_MAPPING_HTML is specified, as that
            // param sends the map back on the outputstream as a string
            boolean createMapFile = !isDefinedOutput(ChartComponent.HTML_MAPPING_HTML);
            boolean hasTemplate = urlTemplate != null && urlTemplate.length() > 0;
            File[] fileResults = createTempFile(outputType, hasTemplate, !keepTempFile);
            if (fileResults == null) {
                // $NON-NLS-1$
                error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0003_CANT_CREATE_TEMP_FILES"));
                return false;
            }
            String chartId = fileResults[ChartComponent.FILE_NAME].getName().substring(0, fileResults[ChartComponent.FILE_NAME].getName().indexOf('.'));
            String filePathWithoutExtension = ChartComponent.TEMP_DIRECTORY + chartId;
            PrintWriter printWriter = new PrintWriter(new StringWriter());
            ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
            JFreeChartEngine.saveChart(dataDefinition, title, "", filePathWithoutExtension, width, height, outputType, printWriter, info, // $NON-NLS-1$
            this);
            // Creating the image map
            boolean useBaseUrl = true;
            // $NON-NLS-1$
            String urlTarget = "pentaho_popup";
            // Prepend the base url to the front of every drill through link
            if (chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG) != null) {
                Boolean booleanValue = new Boolean(chartAttributes.selectSingleNode(ChartComponent.USE_BASE_URL_TAG).getText());
                useBaseUrl = booleanValue.booleanValue();
            }
            // What target for link? _parent, _blank, etc.
            if (chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG) != null) {
                urlTarget = chartAttributes.selectSingleNode(ChartComponent.URL_TARGET_TAG).getText();
            }
            String mapString = null;
            if (hasTemplate) {
                try {
                    String mapId = fileResults[ChartComponent.MAP_NAME].getName().substring(0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.'));
                    mapString = ImageMapUtilities.getImageMap(mapId, info, new StandardToolTipTagFragmentGenerator(), new PentahoChartURLTagFragmentGenerator(urlTemplate, urlTarget, useBaseUrl, dataDefinition, parameterName, outerParameterName));
                    if (createMapFile) {
                        BufferedWriter out = new BufferedWriter(new FileWriter(fileResults[ChartComponent.MAP_NAME]));
                        out.write(mapString);
                        out.flush();
                        out.close();
                    }
                } catch (IOException e) {
                    error(Messages.getInstance().getErrorString("ChartComponent.ERROR_0001_CANT_WRITE_MAP", // $NON-NLS-1$
                    fileResults[ChartComponent.MAP_NAME].getPath()));
                    return false;
                } catch (Exception e) {
                    error(e.getLocalizedMessage(), e);
                    return false;
                }
            }
            /**
             *****************************************************************************************************
             * Legitimate outputs for the ChartComponent in an action sequence:
             *
             * CHART_OUTPUT (chart-output) Stores the chart in the content repository as an IContentItem.
             *
             * CHART_FILE_NAME_OUTPUT (chart-filename) Returns the name of the chart file, including the file extension
             * (with no path information) as a String.
             *
             * HTML_MAPPING_OUTPUT (chart-mapping) Returns the name of the file that the map has been saved to, including
             * the file extension (with no path information) as a String. Will be empty if url-template is undefined
             *
             * HTML_MAPPING_HTML (chart-map-html) Returns the chart image map HTML as a String. Will be empty if
             * url-template is undefined
             *
             * BASE_URL_OUTPUT (base-url) Returns the web app's base URL (ie., http://localhost:8080/pentaho) as a String.
             *
             * HTML_IMG_TAG (image-tag) Returns the HTML snippet including the image map, image (<IMG />) tag for the chart
             * image with src, width, height and usemap attributes defined. Usemap will not be included if url-template is
             * undefined.
             *
             ******************************************************************************************************
             */
            // Now set the outputs
            Set outputs = getOutputNames();
            if ((outputs != null) && (outputs.size() > 0)) {
                Iterator iter = outputs.iterator();
                while (iter.hasNext()) {
                    String outputName = (String) iter.next();
                    String outputValue = null;
                    if (outputName.equals(ChartComponent.CHART_FILE_NAME_OUTPUT)) {
                        outputValue = fileResults[ChartComponent.FILE_NAME].getName();
                    } else if (outputName.equals(ChartComponent.HTML_MAPPING_OUTPUT)) {
                        if (hasTemplate) {
                            outputValue = fileResults[ChartComponent.MAP_NAME].getName();
                        }
                    } else if (outputName.equals(ChartComponent.HTML_MAPPING_HTML)) {
                        outputValue = mapString;
                    } else if (outputName.equals(ChartComponent.BASE_URL_OUTPUT)) {
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        outputValue = requestContext.getContextPath();
                    } else if (outputName.equals(ChartComponent.CONTEXT_PATH_OUTPUT)) {
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        outputValue = requestContext.getContextPath();
                    } else if (outputName.equals(ChartComponent.FULLY_QUALIFIED_SERVER_URL_OUTPUT)) {
                        IApplicationContext applicationContext = PentahoSystem.getApplicationContext();
                        if (applicationContext != null) {
                            outputValue = applicationContext.getFullyQualifiedServerURL();
                        } else {
                            IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                            outputValue = requestContext.getContextPath();
                        }
                    } else if (outputName.equals(ChartComponent.HTML_IMG_TAG)) {
                        // $NON-NLS-1$
                        outputValue = hasTemplate ? mapString : "";
                        // $NON-NLS-1$
                        outputValue += "<img border=\"0\" ";
                        // $NON-NLS-1$//$NON-NLS-2$
                        outputValue += "width=\"" + width + "\" ";
                        // $NON-NLS-1$//$NON-NLS-2$
                        outputValue += "height=\"" + height + "\" ";
                        if (hasTemplate) {
                            outputValue += "usemap=\"#" + fileResults[ChartComponent.MAP_NAME].getName().substring(0, fileResults[ChartComponent.MAP_NAME].getName().indexOf('.')) + // $NON-NLS-1$//$NON-NLS-2$
                            "\" ";
                        }
                        IPentahoRequestContext requestContext = PentahoRequestContextHolder.getRequestContext();
                        String contextPath = requestContext.getContextPath();
                        outputValue += // $NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
                        "src=\"" + contextPath + "getImage?image=" + fileResults[ChartComponent.FILE_NAME].getName() + "\"/>";
                    }
                    if (outputValue != null) {
                        setOutputValue(outputName, outputValue);
                    }
                }
            }
            break;
        /**
         ************************ OUTPUT_CHART && DEFAULT ************************************
         */
        case JFreeChartEngine.OUTPUT_CHART:
        default:
            String chartName = ChartComponent.CHART_OUTPUT;
            if (isDefinedInput(ChartComponent.CHART_NAME_PROP)) {
                chartName = getInputStringValue(ChartComponent.CHART_NAME_PROP);
            }
            // $NON-NLS-1$
            chart = JFreeChartEngine.getChart(dataDefinition, title, "", width, height, this);
            setOutputValue(chartName, chart);
            break;
    }
    return true;
}
Also used : StandardToolTipTagFragmentGenerator(org.jfree.chart.imagemap.StandardToolTipTagFragmentGenerator) CategoryDatasetChartDefinition(org.pentaho.platform.uifoundation.chart.CategoryDatasetChartDefinition) XYZSeriesCollectionChartDefinition(org.pentaho.platform.uifoundation.chart.XYZSeriesCollectionChartDefinition) Set(java.util.Set) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) Node(org.dom4j.Node) Element(org.dom4j.Element) OutputStream(java.io.OutputStream) FileWriter(java.io.FileWriter) IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) IActionSequenceResource(org.pentaho.platform.api.engine.IActionSequenceResource) BufferedWriter(java.io.BufferedWriter) PieDatasetChartDefinition(org.pentaho.platform.uifoundation.chart.PieDatasetChartDefinition) PentahoChartURLTagFragmentGenerator(org.pentaho.platform.uifoundation.chart.PentahoChartURLTagFragmentGenerator) StringWriter(java.io.StringWriter) Iterator(java.util.Iterator) ChartRenderingInfo(org.jfree.chart.ChartRenderingInfo) List(java.util.List) PrintWriter(java.io.PrintWriter) Dataset(org.jfree.data.general.Dataset) TimeSeriesCollectionChartDefinition(org.pentaho.platform.uifoundation.chart.TimeSeriesCollectionChartDefinition) TimeTableXYDatasetChartDefinition(org.pentaho.platform.uifoundation.chart.TimeTableXYDatasetChartDefinition) DialWidgetDefinition(org.pentaho.platform.uifoundation.chart.DialWidgetDefinition) XmlParseException(org.pentaho.platform.api.util.XmlParseException) IOException(java.io.IOException) PentahoEntityResolver(org.pentaho.platform.engine.services.solution.PentahoEntityResolver) JFreeChart(org.jfree.chart.JFreeChart) IOException(java.io.IOException) XmlParseException(org.pentaho.platform.api.util.XmlParseException) IPentahoResultSet(org.pentaho.commons.connection.IPentahoResultSet) StandardEntityCollection(org.jfree.chart.entity.StandardEntityCollection) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) BarLineChartDefinition(org.pentaho.platform.uifoundation.chart.BarLineChartDefinition) XYSeriesCollectionChartDefinition(org.pentaho.platform.uifoundation.chart.XYSeriesCollectionChartDefinition) IContentItem(org.pentaho.platform.api.repository.IContentItem) File(java.io.File)

Example 2 with IApplicationContext

use of org.pentaho.platform.api.engine.IApplicationContext in project pentaho-platform by pentaho.

the class JFreeReportComponent method writeHtml.

public boolean writeHtml(final MasterReport report, final OutputStream outputStream, final int yieldRate, String htmlContentHandlerUrlPattern) {
    try {
        if (htmlContentHandlerUrlPattern == null) {
            final Configuration globalConfig = ClassicEngineBoot.getInstance().getGlobalConfig();
            htmlContentHandlerUrlPattern = PentahoRequestContextHolder.getRequestContext().getContextPath();
            // $NON-NLS-1$
            htmlContentHandlerUrlPattern += globalConfig.getConfigProperty("org.pentaho.web.ContentHandler");
        }
        final IApplicationContext ctx = PentahoSystem.getApplicationContext();
        final URLRewriter rewriter;
        final ContentLocation dataLocation;
        final NameGenerator dataNameGenerator;
        if (ctx != null) {
            // $NON-NLS-1$
            File dataDirectory = new File(ctx.getFileOutputPath("system/tmp/"));
            if (dataDirectory.exists() && (dataDirectory.isDirectory() == false)) {
                dataDirectory = dataDirectory.getParentFile();
                if (dataDirectory.isDirectory() == false) {
                    throw new ReportProcessingException(Messages.getInstance().getErrorString("JFreeReportDirectoryComponent.ERROR_0001_INVALID_DIR", // $NON-NLS-1$
                    dataDirectory.getPath()));
                }
            } else if (dataDirectory.exists() == false) {
                dataDirectory.mkdirs();
            }
            final FileRepository dataRepository = new FileRepository(dataDirectory);
            dataLocation = dataRepository.getRoot();
            dataNameGenerator = new DefaultNameGenerator(dataLocation);
            rewriter = new PentahoURLRewriter(htmlContentHandlerUrlPattern);
        } else {
            dataLocation = null;
            dataNameGenerator = null;
            rewriter = new PentahoURLRewriter(htmlContentHandlerUrlPattern);
        }
        final StreamRepository targetRepository = new StreamRepository(null, outputStream);
        final ContentLocation targetRoot = targetRepository.getRoot();
        final HtmlOutputProcessor outputProcessor = new StreamHtmlOutputProcessor(report.getConfiguration());
        final HtmlPrinter printer = new AllItemsHtmlPrinter(report.getResourceManager());
        // $NON-NLS-1$//$NON-NLS-2$
        printer.setContentWriter(targetRoot, new DefaultNameGenerator(targetRoot, "index", "html"));
        printer.setDataWriter(dataLocation, dataNameGenerator);
        printer.setUrlRewriter(rewriter);
        outputProcessor.setPrinter(printer);
        final StreamReportProcessor sp = new StreamReportProcessor(report, outputProcessor);
        if (yieldRate > 0) {
            sp.addReportProgressListener(new YieldReportListener(yieldRate));
        }
        sp.processReport();
        sp.close();
        outputStream.flush();
        return true;
    } catch (ReportProcessingException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e);
        return false;
    } catch (IOException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e);
        return false;
    } catch (ContentIOException e) {
        // $NON-NLS-1$
        error(Messages.getInstance().getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e);
        return false;
    }
}
Also used : FileRepository(org.pentaho.reporting.libraries.repository.file.FileRepository) Configuration(org.pentaho.reporting.libraries.base.config.Configuration) ModifiableConfiguration(org.pentaho.reporting.libraries.base.config.ModifiableConfiguration) DefaultNameGenerator(org.pentaho.reporting.libraries.repository.DefaultNameGenerator) DefaultNameGenerator(org.pentaho.reporting.libraries.repository.DefaultNameGenerator) NameGenerator(org.pentaho.reporting.libraries.repository.NameGenerator) IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) ContentIOException(org.pentaho.reporting.libraries.repository.ContentIOException) IOException(java.io.IOException) PentahoURLRewriter(org.pentaho.platform.plugin.action.jfreereport.helper.PentahoURLRewriter) StreamHtmlOutputProcessor(org.pentaho.reporting.engine.classic.core.modules.output.table.html.StreamHtmlOutputProcessor) HtmlOutputProcessor(org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlOutputProcessor) ContentIOException(org.pentaho.reporting.libraries.repository.ContentIOException) URLRewriter(org.pentaho.reporting.engine.classic.core.modules.output.table.html.URLRewriter) PentahoURLRewriter(org.pentaho.platform.plugin.action.jfreereport.helper.PentahoURLRewriter) ReportProcessingException(org.pentaho.reporting.engine.classic.core.ReportProcessingException) YieldReportListener(org.pentaho.reporting.engine.classic.core.layout.output.YieldReportListener) AllItemsHtmlPrinter(org.pentaho.reporting.engine.classic.core.modules.output.table.html.AllItemsHtmlPrinter) ContentLocation(org.pentaho.reporting.libraries.repository.ContentLocation) StreamHtmlOutputProcessor(org.pentaho.reporting.engine.classic.core.modules.output.table.html.StreamHtmlOutputProcessor) StreamReportProcessor(org.pentaho.reporting.engine.classic.core.modules.output.table.base.StreamReportProcessor) File(java.io.File) AllItemsHtmlPrinter(org.pentaho.reporting.engine.classic.core.modules.output.table.html.AllItemsHtmlPrinter) HtmlPrinter(org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlPrinter) StreamRepository(org.pentaho.reporting.libraries.repository.stream.StreamRepository)

Example 3 with IApplicationContext

use of org.pentaho.platform.api.engine.IApplicationContext in project pentaho-platform by pentaho.

the class SystemSettingsConfigurationTest method testGetProperties.

@Test
public void testGetProperties() throws Exception {
    SystemSettings settings = new SystemSettings();
    IApplicationContext appContext = mock(IApplicationContext.class);
    PentahoSystem.setApplicationContext(appContext);
    when(appContext.getSolutionPath(anyString())).thenReturn(TestResourceLocation.TEST_RESOURCES + "/solution/system/pentaho.xml");
    config = new SystemSettingsConfiguration("system", settings);
    Properties properties = config.getProperties();
    assertNotNull(properties);
    assertEquals("DEBUG", properties.getProperty("log-level"));
}
Also used : IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) ISystemSettings(org.pentaho.platform.api.engine.ISystemSettings) SystemSettings(org.pentaho.platform.engine.core.system.SystemSettings) Properties(java.util.Properties) Test(org.junit.Test)

Example 4 with IApplicationContext

use of org.pentaho.platform.api.engine.IApplicationContext in project pentaho-platform by pentaho.

the class PentahoWebContextFilterTest method setup.

@Before
public void setup() throws IOException, ServletException {
    this.serverScheme = "https";
    String serverName = "di.pentaho.local";
    int port = 9055;
    this.serverAddress = this.serverScheme + "://" + serverName + ":" + port;
    this.contextRoot = "/the/context/root/";
    this.fullyQualifiedServerURL = this.serverAddress + this.contextRoot;
    this.mockRequest = mock(HttpServletRequest.class);
    ServletContext mockServletContext = mock(ServletContext.class);
    ServletRegistration mockServletRegistration = mock(ServletRegistration.class);
    Collection<String> mappings = new ArrayList<>(1);
    mappings.add(PentahoWebContextFilter.DEFAULT_OSGI_BRIDGE);
    when(mockServletRegistration.getMappings()).thenReturn(mappings);
    when(mockServletContext.getServletRegistration(PentahoWebContextFilter.PLATFORM_OSGI_BRIDGE_ID)).thenReturn(mockServletRegistration);
    when(this.mockRequest.getServletContext()).thenReturn(mockServletContext);
    when(this.mockRequest.getRequestURI()).thenReturn("/somewhere/" + PentahoWebContextFilter.WEB_CONTEXT_JS);
    when(this.mockRequest.getScheme()).thenReturn(this.serverScheme);
    when(this.mockRequest.getServerName()).thenReturn(serverName);
    when(this.mockRequest.getServerPort()).thenReturn(port);
    when(this.mockRequest.getHeader("referer")).thenReturn(this.serverAddress + "/some/app");
    this.mockResponse = mock(HttpServletResponse.class);
    this.mockResponseOutputStream = new java.io.ByteArrayOutputStream();
    when(this.mockResponse.getOutputStream()).thenReturn(new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            PentahoWebContextFilterTest.this.mockResponseOutputStream.write(b);
        }
    });
    FilterConfig mockFilterConfig = mock(FilterConfig.class);
    this.pentahoWebContextFilter = spy(new PentahoWebContextFilter());
    IApplicationContext mockApplicationContext = mock(IApplicationContext.class);
    when(mockApplicationContext.getFullyQualifiedServerURL()).thenReturn(this.fullyQualifiedServerURL);
    doReturn(mockApplicationContext).when(this.pentahoWebContextFilter).getApplicationContext();
    IPentahoRequestContext mockRequestContext = mock(IPentahoRequestContext.class);
    when(mockRequestContext.getContextPath()).thenReturn(this.contextRoot);
    doReturn(mockRequestContext).when(this.pentahoWebContextFilter).getRequestContext();
    this.activeTheme = "xptoTheme";
    IUserSetting mockUserSetting = mock(IUserSetting.class);
    when(mockUserSetting.getSettingValue()).thenReturn(this.activeTheme);
    IUserSettingService mockUserSettingsService = mock(IUserSettingService.class);
    when(mockUserSettingsService.getUserSetting("pentaho-user-theme", null)).thenReturn(mockUserSetting);
    doReturn(mockUserSettingsService).when(this.pentahoWebContextFilter).getUserSettingsService();
    this.sessionName = "testSession";
    IPentahoSession mockSession = mock(IPentahoSession.class);
    when(mockSession.getName()).thenReturn(this.sessionName);
    doReturn(mockSession).when(this.pentahoWebContextFilter).getSession();
    this.reservedChars = new ArrayList<>(2);
    this.reservedChars.add('r');
    this.reservedChars.add('c');
    doReturn(this.reservedChars).when(this.pentahoWebContextFilter).getRepositoryReservedChars();
    IPluginManager mockPluginManager = mock(IPluginManager.class);
    doReturn(mockPluginManager).when(this.pentahoWebContextFilter).getPluginManager();
    doReturn(PentahoWebContextFilter.DEFAULT_SERVICES_ROOT).when(this.pentahoWebContextFilter).initializeServicesPath();
    this.pentahoWebContextFilter.init(mockFilterConfig);
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) IUserSetting(org.pentaho.platform.api.usersettings.pojo.IUserSetting) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRegistration(javax.servlet.ServletRegistration) IPentahoRequestContext(org.pentaho.platform.api.engine.IPentahoRequestContext) IUserSettingService(org.pentaho.platform.api.usersettings.IUserSettingService) ServletContext(javax.servlet.ServletContext) IPluginManager(org.pentaho.platform.api.engine.IPluginManager) FilterConfig(javax.servlet.FilterConfig) Before(org.junit.Before)

Example 5 with IApplicationContext

use of org.pentaho.platform.api.engine.IApplicationContext in project pentaho-platform by pentaho.

the class ReportUtils method getTempDirectory.

public static synchronized File getTempDirectory(final IPentahoSession session) {
    IApplicationContext ctx = PentahoSystem.getApplicationContext();
    if (ctx != null) {
        // $NON-NLS-1$
        final String fileOutputPath = ctx.getFileOutputPath("system/tmp/");
        final File tempDir = new File(fileOutputPath);
        final String id = session.getId();
        final File userTempDir;
        if (id == null) {
            // typical sloopy programming! Someone forgot to check null values.
            userTempDir = tempDir;
        } else {
            userTempDir = new File(tempDir, id);
        }
        // this operation silently fails if the dir already exists.
        userTempDir.mkdir();
        return userTempDir;
    }
    // $NON-NLS-1$
    throw new IllegalStateException(Messages.getInstance().getString("ReportUtils.ERROR_0036_PENTAHO_SYSTEM_NOT_OK"));
}
Also used : IApplicationContext(org.pentaho.platform.api.engine.IApplicationContext) File(java.io.File)

Aggregations

IApplicationContext (org.pentaho.platform.api.engine.IApplicationContext)20 File (java.io.File)9 IOException (java.io.IOException)5 Before (org.junit.Before)5 IPentahoSession (org.pentaho.platform.api.engine.IPentahoSession)5 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 Properties (java.util.Properties)3 Matchers.anyString (org.mockito.Matchers.anyString)3 RepositoryFile (org.pentaho.platform.api.repository2.unified.RepositoryFile)3 OutputStream (java.io.OutputStream)2 IPentahoRequestContext (org.pentaho.platform.api.engine.IPentahoRequestContext)2 StandaloneApplicationContext (org.pentaho.platform.engine.core.system.StandaloneApplicationContext)2 PentahoEntityResolver (org.pentaho.platform.engine.services.solution.PentahoEntityResolver)2 PentahoURLRewriter (org.pentaho.platform.plugin.action.jfreereport.helper.PentahoURLRewriter)2 ReportProcessingException (org.pentaho.reporting.engine.classic.core.ReportProcessingException)2 YieldReportListener (org.pentaho.reporting.engine.classic.core.layout.output.YieldReportListener)2 StreamReportProcessor (org.pentaho.reporting.engine.classic.core.modules.output.table.base.StreamReportProcessor)2 AllItemsHtmlPrinter (org.pentaho.reporting.engine.classic.core.modules.output.table.html.AllItemsHtmlPrinter)2 HtmlOutputProcessor (org.pentaho.reporting.engine.classic.core.modules.output.table.html.HtmlOutputProcessor)2