0001: /*
0002: * Copyright 2006 Pentaho Corporation. All rights reserved.
0003: * This software was developed by Pentaho Corporation and is provided under the terms
0004: * of the Mozilla Public License, Version 1.1, or any later version. You may not use
0005: * this file except in compliance with the license. If you need a copy of the license,
0006: * please go to http://www.mozilla.org/MPL/MPL-1.1.txt. The Original Code is the Pentaho
0007: * BI Platform. The Initial Developer is Pentaho Corporation.
0008: *
0009: * Software distributed under the Mozilla Public License is distributed on an "AS IS"
0010: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
0011: * the license for the specific language governing your rights and limitations.
0012: */
0013: package org.pentaho.plugin.jfreereport;
0014:
0015: import java.awt.Dialog;
0016: import java.awt.Frame;
0017: import java.awt.GraphicsEnvironment;
0018: import java.io.ByteArrayInputStream;
0019: import java.io.File;
0020: import java.io.FileNotFoundException;
0021: import java.io.IOException;
0022: import java.io.InputStream;
0023: import java.io.OutputStream;
0024: import java.io.OutputStreamWriter;
0025: import java.io.UnsupportedEncodingException;
0026: import java.net.URL;
0027: import java.util.HashMap;
0028: import java.util.Iterator;
0029: import java.util.Map;
0030:
0031: import javax.activation.DataSource;
0032: import javax.print.DocFlavor;
0033: import javax.print.PrintException;
0034: import javax.print.PrintService;
0035: import javax.print.PrintServiceLookup;
0036: import javax.swing.table.TableModel;
0037:
0038: import org.apache.commons.logging.Log;
0039: import org.apache.commons.logging.LogFactory;
0040: import org.jfree.base.config.ModifiableConfiguration;
0041: import org.jfree.io.IOUtils;
0042: import org.jfree.report.DataFactory;
0043: import org.jfree.report.JFreeReport;
0044: import org.jfree.report.JFreeReportBoot;
0045: import org.jfree.report.ParameterDataRow;
0046: import org.jfree.report.ReportProcessingException;
0047: import org.jfree.report.ResourceBundleFactory;
0048: import org.jfree.report.ext.modules.java14print.Java14PrintUtil;
0049: import org.jfree.report.layout.output.YieldReportListener;
0050: import org.jfree.report.modules.gui.base.PreviewDialog;
0051: import org.jfree.report.modules.gui.base.ReportController;
0052: import org.jfree.report.modules.gui.print.PrintUtil;
0053: import org.jfree.report.modules.output.pageable.base.PageableReportProcessor;
0054: import org.jfree.report.modules.output.pageable.pdf.PdfOutputProcessor;
0055: import org.jfree.report.modules.output.table.base.FlowReportProcessor;
0056: import org.jfree.report.modules.output.table.base.StreamReportProcessor;
0057: import org.jfree.report.modules.output.table.csv.StreamCSVOutputProcessor;
0058: import org.jfree.report.modules.output.table.html.AllItemsHtmlPrinter;
0059: import org.jfree.report.modules.output.table.html.HtmlOutputProcessor;
0060: import org.jfree.report.modules.output.table.html.HtmlPrinter;
0061: import org.jfree.report.modules.output.table.html.StreamHtmlOutputProcessor;
0062: import org.jfree.report.modules.output.table.html.URLRewriter;
0063: import org.jfree.report.modules.output.table.rtf.StreamRTFOutputProcessor;
0064: import org.jfree.report.modules.output.table.xls.FlowExcelOutputProcessor;
0065: import org.jfree.report.modules.output.xml.XMLProcessor;
0066: import org.jfree.report.modules.parser.base.ReportGenerator;
0067: import org.jfree.report.util.ReportProperties;
0068: import org.jfree.repository.ContentIOException;
0069: import org.jfree.repository.ContentLocation;
0070: import org.jfree.repository.DefaultNameGenerator;
0071: import org.jfree.repository.NameGenerator;
0072: import org.jfree.repository.file.FileRepository;
0073: import org.jfree.repository.stream.StreamRepository;
0074: import org.jfree.resourceloader.FactoryParameterKey;
0075: import org.jfree.resourceloader.ResourceException;
0076: import org.jfree.resourceloader.ResourceKey;
0077: import org.jfree.resourceloader.ResourceManager;
0078: import org.jfree.ui.RefineryUtilities;
0079: import org.jfree.util.Configuration;
0080: import org.pentaho.actionsequence.dom.ActionInput;
0081: import org.pentaho.actionsequence.dom.ActionOutput;
0082: import org.pentaho.actionsequence.dom.ActionResource;
0083: import org.pentaho.actionsequence.dom.actions.ActionDefinition;
0084: import org.pentaho.actionsequence.dom.actions.ActionFactory;
0085: import org.pentaho.actionsequence.dom.actions.JFreeReportAction;
0086: import org.pentaho.core.component.IComponent;
0087: import org.pentaho.core.component.IDataComponent;
0088: import org.pentaho.core.component.IPreparedComponent;
0089: import org.pentaho.commons.connection.IPentahoMetaData;
0090: import org.pentaho.commons.connection.IPentahoResultSet;
0091: import org.pentaho.core.repository.IContentItem;
0092: import org.pentaho.core.repository.IContentLocation;
0093: import org.pentaho.core.repository.IContentRepository;
0094: import org.pentaho.core.runtime.IActionParameter;
0095: import org.pentaho.core.runtime.IRuntimeContext;
0096: import org.pentaho.core.solution.IActionResource;
0097: import org.pentaho.core.system.IApplicationContext;
0098: import org.pentaho.core.system.PentahoSystem;
0099: import org.pentaho.messages.Messages;
0100: import org.pentaho.messages.util.LocaleHelper;
0101: import org.pentaho.plugin.jfreereport.components.JFreeReportValidateParametersComponent;
0102: import org.pentaho.plugin.jfreereport.helper.PentahoDataFactory;
0103: import org.pentaho.plugin.jfreereport.helper.PentahoResourceBundleFactory;
0104: import org.pentaho.plugin.jfreereport.helper.PentahoResourceData;
0105: import org.pentaho.plugin.jfreereport.helper.PentahoResourceLoader;
0106: import org.pentaho.plugin.jfreereport.helper.PentahoTableDataFactory;
0107: import org.pentaho.plugin.jfreereport.helper.PentahoTableModel;
0108: import org.pentaho.plugin.jfreereport.helper.PentahoURLRewriter;
0109: import org.pentaho.plugin.jfreereport.helper.ReportUtils;
0110: import org.pentaho.plugin.jfreereport.repository.ReportContentRepository;
0111: import org.xml.sax.InputSource;
0112:
0113: /**
0114: * The JFreeReportComponent provides a simple-to-use frontend for the reporting
0115: * process. <p/> This component will execute JFreeReport reports in one of two
0116: * different modes: <p/>
0117: * <h3>sqlMode = true</h3>
0118: * <p/> This means that the JFreeReport component is expected to execute an SQL query,
0119: * wrap the resulting SQL Resultset in a TableModel, and use that to execute a report
0120: * whose definition is in the file system. In this mode, the action-sequence
0121: * definition must contain the following elements: In the resource-definition section,
0122: * there must be a resource called "report-definition" which defines the location of
0123: * the jfreereport xml document. <p/> In the component-definition sction, there must
0124: * be the following entries:
0125: * <ul>
0126: * <li>A "query" parameter which contains an SQL query.</li>
0127: * <li>Either for connecting to the SQL datasource:
0128: * <ul>
0129: * <li>A "jndi" parameter (with the jndi name of the datasource)</li>
0130: * <li>or The database parameters "driver", "user-id", "password" and "connection" so
0131: * that a database connection can be established for running the afore-mentioned
0132: * "query".</li>
0133: * </ul>
0134: * </li>
0135: * </ul>
0136: * <h3>sqlMode = false</h3>
0137: * <p/> This means that the JFreeReport component is expected to execute a report that
0138: * exists in a .jar file (like the reporting demo reports) along with the TableModel
0139: * class that provides the data for the report. In this mode, the action-sequence
0140: * definition must contain the following elements: In the resource-definition section,
0141: * there must be a resource called "report-jar" that points to the .jar file that
0142: * contains the report .xml file, and the TableModel implementation. <p/> In the
0143: * component-definition section, there must be two entries:
0144: * <ul>
0145: * <li> "report-location" - This is the location of the report .xml document (e.g.
0146: * org/jfree/report/demo/report1.xml)</li>
0147: * <li> "class-location" - This is the package-qualified class that implements
0148: * TableModel (e.g. org.jfree.report.demo.SampleData1).</li>
0149: * </ul>
0150: *
0151: * @author mbatchel
0152: * @created Sep 8, 2005
0153: */
0154: public class JFreeReportComponent extends AbstractJFreeReportComponent {
0155: private static final long serialVersionUID = -4185151399689983507L;
0156: private static int INIT_REPORT_PARAMS_STATUS_PASSED = 1;
0157: private static int INIT_REPORT_PARAMS_STATUS_FAILED = 2;
0158: private static int INIT_REPORT_PARAMS_STATUS_PROMPT_PENDING = 3;
0159: private static final String PROGRESS_DIALOG_ENABLED_KEY = "org.jfree.report.modules.gui.base.ProgressDialogEnabled";//$NON-NLS-1$
0160: private static final String PROGRESS_BAR_ENABLED_KEY = "org.jfree.report.modules.gui.base.ProgressBarEnabled";//$NON-NLS-1$
0161: private static final boolean DO_NOT_USE_THE_CONTENT_REPOSITORY = true;
0162:
0163: private JFreeReportValidateParametersComponent validateParametersComponent;
0164:
0165: public JFreeReportComponent() {
0166: }
0167:
0168: public boolean init() {
0169: return true;
0170: }
0171:
0172: public void done() {
0173: }
0174:
0175: public boolean validateSystemSettings() {
0176: return true;
0177: }
0178:
0179: public Log getLogger() {
0180: return LogFactory.getLog(JFreeReportComponent.class);
0181: }
0182:
0183: protected boolean initAndValidate(IComponent component) {
0184: component.setInstanceId(getInstanceId());
0185: component.setActionName(getActionName());
0186: component.setProcessId(getProcessId());
0187: component.setComponentDefinition(getComponentDefinition());
0188: component.setRuntimeContext(getRuntimeContext());
0189: component.setSession(getSession());
0190: component.setLoggingLevel(getLoggingLevel());
0191: component.setMessages(getMessages());
0192: return (component.validate() == IRuntimeContext.RUNTIME_CONTEXT_VALIDATE_OK);
0193: }
0194:
0195: /**
0196: * We cannot validate the parameters of all components, as the required parameters
0197: * might not have been created.
0198: *
0199: * @return
0200: */
0201: public boolean validateAction() {
0202:
0203: boolean result = true;
0204: if (!(getActionDefinition() instanceof JFreeReportAction)) {
0205: error(Messages
0206: .getErrorString(
0207: "ComponentBase.ERROR_0001_UNKNOWN_ACTION_TYPE", getActionDefinition().getElement().asXML())); //$NON-NLS-1$
0208: result = false;
0209: } else {
0210: validateParametersComponent = new JFreeReportValidateParametersComponent();
0211: if (initAndValidate(validateParametersComponent) == false) {
0212: error(Messages
0213: .getString("JFreeReportComponent.ERROR_0025_COULD_NOT_VALIDATE")); //$NON-NLS-1$
0214: result = false;
0215: }
0216: }
0217: return result;
0218: }
0219:
0220: private boolean isParameterUIAvailable() {
0221: /*
0222: * See if we are allowed to generate a parameter selection user interface. If
0223: * we are being called as part of a process, this will not be allowed.
0224: */
0225: if (!feedbackAllowed()) {
0226: // We could not get an output stream for the feedback, but we are
0227: // allowed
0228: // to generate UI, so return an error
0229: error(Messages
0230: .getErrorString("JFreeReport.ERROR_0020_INVALID_FEEDBACK_STREAM")); //$NON-NLS-1$
0231: return false;
0232: }
0233: // We need input from the user, we have delivered an input form into the
0234: // feeback stream
0235: setFeedbackMimeType("text/html"); //$NON-NLS-1$
0236: return true;
0237: }
0238:
0239: private int initReportParams() {
0240: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0241: int result = INIT_REPORT_PARAMS_STATUS_PASSED;
0242: final String defaultValue = ""; //$NON-NLS-1$
0243:
0244: ActionInput[] actionInputs = jFreeReportAction
0245: .getAllInputParams();
0246: for (int i = 0; i < actionInputs.length; i++) {
0247: Object paramValue = actionInputs[i].getValue();
0248: String inputName = actionInputs[i].getName();
0249: if (paramValue == null || ("".equals(paramValue))) //$NON-NLS-1$
0250: {
0251: IActionParameter paramParameter = getInputParameter(inputName);
0252: if (paramParameter.getPromptStatus() == IActionParameter.PROMPT_PENDING) {
0253: result = INIT_REPORT_PARAMS_STATUS_PROMPT_PENDING;
0254: continue;
0255: }
0256: if (isParameterUIAvailable()) {
0257: // The parameter value was not provided, and we are allowed
0258: // to
0259: // create user interface forms
0260: createFeedbackParameter(inputName, inputName,
0261: "", defaultValue, true); //$NON-NLS-1$
0262: result = INIT_REPORT_PARAMS_STATUS_PROMPT_PENDING;
0263: } else {
0264: result = INIT_REPORT_PARAMS_STATUS_FAILED;
0265: }
0266: }
0267: }
0268: if (result == INIT_REPORT_PARAMS_STATUS_PROMPT_PENDING) {
0269: addTempParameterObject(
0270: REPORTVALIDATECOMPONENT_REPORTTEMP_UI_NEEDED,
0271: Boolean.TRUE);
0272: } else {
0273: addTempParameterObject(
0274: REPORTVALIDATECOMPONENT_REPORTTEMP_UI_NEEDED,
0275: Boolean.FALSE);
0276: }
0277: return result;
0278: }
0279:
0280: /**
0281: * This method gets called from the outside. Based upon our mode call the correct
0282: * function.
0283: */
0284: public boolean executeAction() {
0285: int initParamsResult = initReportParams();
0286: boolean result = false;
0287: if (initParamsResult == INIT_REPORT_PARAMS_STATUS_FAILED) {
0288: result = false;
0289: } else if (initParamsResult == INIT_REPORT_PARAMS_STATUS_PROMPT_PENDING
0290: || isPromptPending()) {
0291: result = true;
0292: } else if (initParamsResult == INIT_REPORT_PARAMS_STATUS_PASSED) {
0293: result = executeReportAction();
0294: }
0295: return result;
0296: }
0297:
0298: protected boolean executeReportAction() {
0299: boolean result = false;
0300: try {
0301: PentahoTableDataFactory factory = getDataFactory();
0302: if (factory != null) {
0303: addTempParameterObject(
0304: DATACOMPONENT_REPORTTEMP_DATAFACTORY, factory);
0305: }
0306: JFreeReport report = getReport();
0307: if (report != null) {
0308: addTempParameterObject(
0309: DATACOMPONENT_REPORTTEMP_OBJINPUT, report);
0310: if (initReportConfigParameters(report)
0311: && (initReportInputs(report))) {
0312: result = generateReport(report, factory);
0313: }
0314: }
0315: } catch (ClassNotFoundException ex) {
0316: error(
0317: Messages
0318: .getErrorString("JFreeReport.ERROR_0021_DATA_COMPONENT_FAILED"), ex); //$NON-NLS-1$
0319: } catch (InstantiationException ex) {
0320: error(
0321: Messages
0322: .getErrorString("JFreeReport.ERROR_0021_DATA_COMPONENT_FAILED"), ex); //$NON-NLS-1$
0323: } catch (IllegalAccessException ex) {
0324: error(
0325: Messages
0326: .getErrorString("JFreeReport.ERROR_0021_DATA_COMPONENT_FAILED"), ex); //$NON-NLS-1$
0327: } catch (IOException ex) {
0328: error(
0329: Messages
0330: .getErrorString("JFreeReport.ERROR_0008_INVALID_OUTPUT_STREAM"), ex); //$NON-NLS-1$
0331: } catch (Exception ex) {
0332: error(ex.getMessage());
0333: }
0334: return result;
0335: }
0336:
0337: protected PentahoTableDataFactory getDataFactory()
0338: throws ClassNotFoundException, InstantiationException,
0339: IllegalAccessException, Exception {
0340: PentahoTableDataFactory factory = null;
0341: factory = getQueryComponentDataFactory();
0342: if (factory == null) {
0343: factory = getInputParamDataFactory();
0344: }
0345: if (factory == null) {
0346: factory = getJarDataFactory();
0347: }
0348: if (factory == null) {
0349: throw new Exception(
0350: Messages
0351: .getString("JFreeReport.ERROR_0022_DATA_INPUT_INVALID_OBJECT"));
0352: }
0353: return factory;
0354: }
0355:
0356: private PentahoTableDataFactory getQueryComponentDataFactory()
0357: throws ClassNotFoundException, InstantiationException,
0358: IllegalAccessException, Exception {
0359: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0360: PentahoTableDataFactory factory = null;
0361: String dataComponentName = jFreeReportAction.getDataComponent()
0362: .getStringValue();
0363: String origComponentName = jFreeReportAction.getComponentName();
0364: if (dataComponentName != null) {
0365: if (JFreeReportAction.SQL_DATA_SOURCE
0366: .equalsIgnoreCase(dataComponentName)) {
0367: dataComponentName = DATACOMPONENT_SQLCLASS;
0368: } else if (JFreeReportAction.MDX_DATA_SOURCE
0369: .equalsIgnoreCase(dataComponentName)) {
0370: dataComponentName = DATACOMPONENT_MDXCLASS;
0371: }
0372: try {
0373: // This is a giant hack and a big no, no. Basically we're going to transform the JFreeReportAction into a
0374: // SQL or MDX lookup action, by changing its component name. Then we create the appropriate component to run the transformed action.
0375: // All this to support the DB and Query info being embedded in the JFreeReport action. This is definitely deprecated functionality
0376: // that should not be relied upon. The correct way to do this is to create an SQL or MDX action prior to the JFreeReport
0377: // action in the action sequence. That action performs the desired query, then pass the results of that query to the JFreeReport
0378: // action.
0379: jFreeReportAction.setComponentName(dataComponentName);
0380: ActionDefinition tmpActionDefinition = ActionFactory
0381: .getActionDefinition(jFreeReportAction
0382: .getElement(), jFreeReportAction
0383: .getActionParameterMgr());
0384: final Class componentClass = Class
0385: .forName(dataComponentName);
0386: IDataComponent dataComponent = (IDataComponent) componentClass
0387: .newInstance();
0388: dataComponent.setInstanceId(getInstanceId());
0389: dataComponent.setActionName(getActionName());
0390: dataComponent.setProcessId(getProcessId());
0391: dataComponent.setActionDefinition(tmpActionDefinition);
0392: dataComponent
0393: .setComponentDefinition(getComponentDefinition());
0394: dataComponent.setRuntimeContext(getRuntimeContext());
0395: dataComponent.setSession(getSession());
0396: dataComponent.setLoggingLevel(getLoggingLevel());
0397: dataComponent.setMessages(getMessages());
0398: // if that fails, then we know we messed up again.
0399: // Abort, we cant continue anyway.
0400: if ((dataComponent.validate() == IRuntimeContext.RUNTIME_CONTEXT_VALIDATE_OK)
0401: && dataComponent.init()
0402: && (dataComponent.execute() == IRuntimeContext.RUNTIME_STATUS_SUCCESS)) {
0403: final IPentahoResultSet resultset = dataComponent
0404: .getResultSet();
0405: factory = new PentahoTableDataFactory(
0406: DATACOMPONENT_DEFAULTINPUT,
0407: new PentahoTableModel(resultset));
0408: } else {
0409: throw new IllegalArgumentException(
0410: Messages
0411: .getErrorString("JFreeReport.ERROR_0021_DATA_COMPONENT_FAILED"));
0412: }
0413: } catch (ClassNotFoundException e) {
0414: } catch (InstantiationException e) {
0415: // TODO Auto-generated catch block
0416: e.printStackTrace();
0417: } catch (IllegalAccessException e) {
0418: // TODO Auto-generated catch block
0419: e.printStackTrace();
0420: } finally {
0421: jFreeReportAction.setComponentName(origComponentName);
0422: }
0423: }
0424: return factory;
0425: }
0426:
0427: private PentahoTableDataFactory getJarDataFactory()
0428: throws Exception {
0429: PentahoTableDataFactory factory = null;
0430: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0431: try {
0432: ActionResource actionResource = jFreeReportAction
0433: .getDataJar().getJar();
0434: if (actionResource != null) {
0435: DataSource dataSource = actionResource.getDataSource();
0436: InputStream in = dataSource.getInputStream();
0437: try {
0438: // not being able to read a single char is definitly a big boo ..
0439: if (in.read() == -1) {
0440: throw new Exception(
0441: Messages
0442: .getErrorString("JFreeReport.ERROR_0009_REPORT_JAR_UNREADABLE")); //$NON-NLS-1$
0443: } else {
0444: final ClassLoader loader = ReportUtils
0445: .createJarLoader(getSession(),
0446: getResource(actionResource
0447: .getName()));
0448: if (loader == null) {
0449: throw new Exception(
0450: Messages
0451: .getString("JFreeReportDataComponent.ERROR_0035_COULD_NOT_CREATE_CLASSLOADER")); //$NON-NLS-1$
0452: } else if (!isDefinedInput(DATACOMPONENT_CLASSLOCINPUT)) {
0453: throw new Exception(
0454: Messages
0455: .getErrorString("JFreeReport.ERROR_0012_CLASS_LOCATION_MISSING")); //$NON-NLS-1$
0456: } else {
0457: // Get input parameters, and set them as properties in the report
0458: // object.
0459: final ReportProperties reportProperties = new ReportProperties();
0460: ActionInput[] actionInputs = jFreeReportAction
0461: .getAllInputParams();
0462: for (int i = 0; i < actionInputs.length; i++) {
0463: final Object paramValue = actionInputs[i]
0464: .getValue();
0465: if (paramValue instanceof Object[]) {
0466: final Object[] values = (Object[]) paramValue;
0467: final StringBuffer valuesBuffer = new StringBuffer();
0468: // TODO support non-string items
0469: for (int z = 0; z < values.length; z++) {
0470: if (z == 0) {
0471: valuesBuffer
0472: .append(values[z]
0473: .toString());
0474: } else {
0475: valuesBuffer
0476: .append(',')
0477: .append(
0478: values[z]
0479: .toString());
0480: }
0481: }
0482: reportProperties.put(
0483: actionInputs[i].getName(),
0484: valuesBuffer.toString());
0485: } else {
0486: reportProperties.put(
0487: actionInputs[i].getName(),
0488: paramValue);
0489: }
0490: }
0491:
0492: final DataFactory dataFactory = new PentahoDataFactory(
0493: loader);
0494: final TableModel model = dataFactory
0495: .queryData(jFreeReportAction
0496: .getDataJar()
0497: .getDataClass(),
0498: new ParameterDataRow(
0499: reportProperties));
0500:
0501: factory = new PentahoTableDataFactory(
0502: DATACOMPONENT_DEFAULTINPUT, model);
0503: }
0504: }
0505: } catch (Exception e) {
0506: throw new Exception(
0507: Messages
0508: .getErrorString("JFreeReport.ERROR_0009_REPORT_JAR_UNREADABLE"));
0509: }
0510: }
0511: } catch (FileNotFoundException e1) {
0512: throw new Exception(Messages.getErrorString(
0513: "JFreeReport.ERROR_0010_REPORT_JAR_MISSING",
0514: jFreeReportAction.getDataJar().toString()));
0515: }
0516: return factory;
0517: }
0518:
0519: private PentahoTableDataFactory getInputParamDataFactory() {
0520: PentahoTableDataFactory factory = null;
0521: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0522:
0523: ActionInput reportDataParam = (ActionInput) jFreeReportAction
0524: .getData();
0525: Object dataObject = reportDataParam != null ? reportDataParam
0526: .getValue() : null;
0527: if ((dataObject instanceof IPentahoResultSet)
0528: || (dataObject instanceof TableModel)) {
0529: factory = new PentahoTableDataFactory();
0530: if (dataObject instanceof IPentahoResultSet) {
0531: final IPentahoResultSet resultset = (IPentahoResultSet) dataObject;
0532: resultset.beforeFirst();
0533: factory.addTable(DATACOMPONENT_DEFAULTINPUT,
0534: new PentahoTableModel(resultset));
0535: } else if (dataObject instanceof TableModel) {
0536: factory.addTable(DATACOMPONENT_DEFAULTINPUT,
0537: (TableModel) dataObject);
0538: }
0539:
0540: ActionInput[] subreportQueries = jFreeReportAction
0541: .getSubreportQueryParams();
0542: for (int i = 0; i < subreportQueries.length; i++) {
0543: dataObject = subreportQueries[i].getValue();
0544: if (dataObject instanceof IPreparedComponent) {
0545: factory
0546: .addPreparedComponent(subreportQueries[i]
0547: .getName(),
0548: (IPreparedComponent) dataObject);
0549: } else if (dataObject instanceof IPentahoResultSet) {
0550: final IPentahoResultSet resultset = (IPentahoResultSet) dataObject;
0551: resultset.beforeFirst();
0552: factory.addTable(subreportQueries[i].getName(),
0553: new PentahoTableModel(resultset));
0554: } else if (dataObject instanceof TableModel) {
0555: factory.addTable(subreportQueries[i].getName(),
0556: (TableModel) dataObject);
0557: }
0558: }
0559: }
0560: return factory;
0561: }
0562:
0563: private String getHostColonPort(String pentahoBaseURL) {
0564: try {
0565: URL url = new URL(pentahoBaseURL);
0566: return url.getHost() + ":" + url.getPort();//$NON-NLS-1$
0567: } catch (Exception e) {
0568: }
0569: return pentahoBaseURL;
0570: }
0571:
0572: private String getBaseServerURL(String pentahoBaseURL) {
0573: try {
0574: URL url = new URL(pentahoBaseURL);
0575: return url.getProtocol()
0576: + "://" + url.getHost() + ":" + url.getPort(); //$NON-NLS-1$ //$NON-NLS-2$
0577: } catch (Exception e) {
0578: }
0579: return pentahoBaseURL;
0580: }
0581:
0582: private JFreeReport parseReport(IActionResource resource) {
0583: try {
0584: // define the resource url so that PentahoResourceLoader recognizes the path.
0585: String resourceUrl = PentahoResourceLoader.SOLUTION_SCHEMA_NAME
0586: + PentahoResourceLoader.SCHEMA_SEPARATOR
0587: + resource.getAddress();
0588:
0589: String pentahoBaseURL = PentahoSystem
0590: .getApplicationContext().getBaseUrl();
0591:
0592: HashMap helperObjects = new HashMap();
0593:
0594: helperObjects
0595: .put(
0596: new FactoryParameterKey("pentahoBaseURL"), PentahoSystem.getApplicationContext().getBaseUrl()); //$NON-NLS-1$
0597:
0598: // trim out the server and port
0599: helperObjects
0600: .put(
0601: new FactoryParameterKey("serverBaseURL"), getBaseServerURL(pentahoBaseURL)); //$NON-NLS-1$
0602:
0603: helperObjects
0604: .put(
0605: new FactoryParameterKey("solutionRoot"), PentahoSystem.getApplicationContext().getSolutionPath("")); //$NON-NLS-1$ //$NON-NLS-2$
0606:
0607: // get the host:port portion only
0608: helperObjects
0609: .put(
0610: new FactoryParameterKey("hostColonPort"), getHostColonPort(pentahoBaseURL)); //$NON-NLS-1$
0611:
0612: // add the runtime context so that PentahoResourceData class can get access to the solution repo
0613: helperObjects.put(new FactoryParameterKey(
0614: PentahoResourceData.PENTAHO_RUNTIME_CONTEXT_KEY),
0615: getRuntimeContext());
0616:
0617: Iterator it = getInputNames().iterator();
0618: while (it.hasNext()) {
0619: try {
0620: String inputName = (String) it.next();
0621: String inputValue = getInputStringValue(inputName);
0622: helperObjects.put(
0623: new FactoryParameterKey(inputName),
0624: inputValue);
0625: } catch (Exception e) {
0626: }
0627: }
0628:
0629: ResourceManager resourceManager = new ResourceManager();
0630: resourceManager.registerDefaults();
0631:
0632: ResourceKey contextKey = resourceManager.createKey(
0633: resourceUrl, helperObjects);
0634: ResourceKey key = resourceManager.createKey(resourceUrl,
0635: helperObjects);
0636:
0637: return ReportGenerator.getInstance().parseReport(
0638: resourceManager, key, contextKey);
0639:
0640: } catch (Exception ex) {
0641: error(
0642: Messages
0643: .getErrorString(
0644: "JFreeReport.ERROR_0007_COULD_NOT_PARSE", resource.getAddress()), ex); //$NON-NLS-1$
0645: return null;
0646: }
0647: }
0648:
0649: public JFreeReport getReport() throws Exception {
0650: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0651: JFreeReport report = getReportFromResource();
0652: if (report == null) {
0653: report = getReportFromInputParam();
0654: if (report == null) {
0655: report = getReportFromJar();
0656: }
0657: }
0658: if ((report != null)
0659: && jFreeReportAction.getCreatePrivateCopy()
0660: .getBooleanValue(false)) {
0661: report = (JFreeReport) report.clone();
0662: }
0663: return report;
0664: }
0665:
0666: private JFreeReport getReportFromResource()
0667: throws ResourceException, IOException {
0668: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0669: JFreeReport report = null;
0670: Object reportDefinition = jFreeReportAction
0671: .getReportDefinition();
0672: IActionResource resource = null;
0673: if (reportDefinition instanceof ActionResource) {
0674: resource = getResource(((ActionResource) reportDefinition)
0675: .getName());
0676: }
0677: if (resource != null) {
0678: if (resource.getSourceType() == IActionResource.XML) {
0679: String repDef = resource.getAddress();
0680: ReportGenerator generator = ReportGenerator
0681: .getInstance();
0682:
0683: // add the runtime context so that PentahoResourceData class can get access to the solution repo
0684: generator
0685: .setObject(
0686: PentahoResourceData.PENTAHO_RUNTIME_CONTEXT_KEY,
0687: getRuntimeContext());
0688:
0689: // TODO sbarkdull, this is not the correct way to get the encoding. the encoding was
0690: // defined in the XML document, we are guessing that the xml document was encoded
0691: // with the encoding specified by system-encoding, which is a pure guess.
0692: // see BISERVER-895
0693: String encoding = LocaleHelper.getSystemEncoding();
0694: ByteArrayInputStream inStream = new ByteArrayInputStream(
0695: repDef.getBytes(encoding));
0696: InputSource repDefInputSource = new InputSource(
0697: inStream);
0698: repDefInputSource.setEncoding(encoding);
0699: report = generator.parseReport(repDefInputSource,
0700: getDefinedResourceURL(null));
0701: } else {
0702: report = parseReport(resource);
0703: }
0704: }
0705: return report;
0706: }
0707:
0708: private JFreeReport getReportFromInputParam()
0709: throws ResourceException, UnsupportedEncodingException,
0710: IOException {
0711: JFreeReport report = null;
0712: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0713:
0714: Object reportDefinition = jFreeReportAction
0715: .getReportDefinition();
0716: if (reportDefinition instanceof ActionInput) {
0717: String repDef = ((ActionInput) reportDefinition)
0718: .getStringValue();
0719: report = createReport(repDef);
0720: }
0721:
0722: return report;
0723: }
0724:
0725: protected JFreeReport createReport(String reportDefinition)
0726: throws ResourceException, IOException {
0727: ReportGenerator generator = ReportGenerator.getInstance();
0728:
0729: // add the runtime context so that PentahoResourceData class can get access to the solution repo
0730: generator.setObject(
0731: PentahoResourceData.PENTAHO_RUNTIME_CONTEXT_KEY,
0732: getRuntimeContext());
0733:
0734: // get base URL
0735: String baseURL = PentahoSystem.getApplicationContext()
0736: .getBaseUrl();
0737: URL url = null;
0738: try {
0739: url = new URL(baseURL);
0740: } catch (Exception e) {
0741: // a null URL is ok
0742: warn(Messages
0743: .getString("JFreeReportLoadComponent.WARN_COULD_NOT_CREATE_URL")); //$NON-NLS-1$
0744: }
0745: ByteArrayInputStream inStream = new ByteArrayInputStream(
0746: reportDefinition.getBytes(LocaleHelper
0747: .getSystemEncoding()));
0748: InputSource reportDefinitionInputSource = new InputSource(
0749: inStream);
0750: reportDefinitionInputSource.setEncoding(LocaleHelper
0751: .getSystemEncoding());
0752: return generator.parseReport(reportDefinitionInputSource,
0753: getDefinedResourceURL(url)); //$NON-NLS-1$
0754: }
0755:
0756: private JFreeReport getReportFromJar() throws Exception {
0757: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0758: JFreeReport report;
0759: ActionResource reportJar = jFreeReportAction
0760: .getReportDefinitionJar().getJar();
0761: final IActionResource resource = getResource(reportJar
0762: .getName());
0763: final ClassLoader loader = ReportUtils.createJarLoader(
0764: getSession(), resource);
0765: if (loader == null) {
0766: throw new Exception(
0767: Messages
0768: .getString("JFreeReportLoadComponent.ERROR_0035_COULD_NOT_CREATE_CLASSLOADER")); //$NON-NLS-1$
0769: }
0770:
0771: String reportLocation = jFreeReportAction
0772: .getReportDefinitionJar().getReportLocation();
0773: URL resourceUrl = loader.getResource(reportLocation);
0774: if (resourceUrl == null) {
0775: throw new Exception(Messages.getErrorString(
0776: "JFreeReport.ERROR_0016_REPORT_RESOURCE_INVALID", //$NON-NLS-1$
0777: reportLocation, resource.getAddress()));
0778: }
0779:
0780: try {
0781: ReportGenerator generator = ReportGenerator.getInstance();
0782:
0783: // add the runtime context so that PentahoResourceData class can get access to the solution repo
0784: generator.setObject(
0785: PentahoResourceData.PENTAHO_RUNTIME_CONTEXT_KEY,
0786: getRuntimeContext());
0787:
0788: report = generator.parseReport(resourceUrl,
0789: getDefinedResourceURL(resourceUrl));
0790: } catch (Exception ex) {
0791: throw new Exception(
0792: Messages
0793: .getErrorString(
0794: "JFreeReport.ERROR_0007_COULD_NOT_PARSE", reportLocation), ex); //$NON-NLS-1$
0795: }
0796: return report;
0797: }
0798:
0799: private URL getDefinedResourceURL(URL defaultValue) {
0800: if (isDefinedInput(REPORTLOAD_RESURL) == false) {
0801: return defaultValue;
0802: }
0803:
0804: try {
0805: final String inputStringValue = getInputStringValue(Messages
0806: .getString(REPORTLOAD_RESURL));
0807: return new URL(inputStringValue);
0808: } catch (Exception e) {
0809: return defaultValue;
0810: }
0811: }
0812:
0813: private boolean initReportConfigParameters(JFreeReport report) {
0814: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0815: boolean result = true;
0816: if (isDefinedInput(DATACOMPONENT_REPORTTEMP_OBJINPUT)) {
0817: Object reportConfigParams = jFreeReportAction
0818: .getReportConfig().getValue();
0819: if (reportConfigParams != null) {
0820: if (reportConfigParams instanceof IPentahoResultSet) {
0821: setReportConfigParameters(report,
0822: (IPentahoResultSet) reportConfigParams);
0823: } else if (reportConfigParams instanceof Map) {
0824: setReportConfigParameters(report,
0825: (Map) reportConfigParams);
0826: } else if (reportConfigParams instanceof JFreeReportAction.StaticReportConfig) {
0827: setReportConfigParameters(
0828: report,
0829: (JFreeReportAction.StaticReportConfig) reportConfigParams);
0830: } else {
0831: error(Messages
0832: .getErrorString("JFreeReport.ERROR_0026_UNKNOWN_REPORT_CONFIGURATION_PARAMETERS")); //$NON-NLS-1$
0833: result = false;
0834: ;
0835: }
0836: }
0837: }
0838: return result;
0839: }
0840:
0841: private void setReportConfigParameters(JFreeReport report,
0842: JFreeReportAction.StaticReportConfig reportConfig) {
0843: // We have some configuration parameters in the component definition
0844: for (int i = 0; i < reportConfig.size(); i++) {
0845: JFreeReportAction.StaticReportConfigItem staticReportConfigItem = (JFreeReportAction.StaticReportConfigItem) reportConfig
0846: .get(i);
0847: String parmName = staticReportConfigItem.getName();
0848: String parmValue = staticReportConfigItem.getValue();
0849: if ((parmName == null) || (parmName.length() == 0)) {
0850: // Ignore configuration settings without name=
0851: error(Messages
0852: .getErrorString("JFreeReport.ERROR_0027_REPORT_CONFIGURATION_PARAMETER_IGNORED")); //$NON-NLS-1$
0853: continue;
0854: }
0855: if (parmValue != null) {
0856: parmValue = parmValue.trim();
0857: if (parmValue.length() > 0) {
0858: report.getReportConfiguration().setConfigProperty(
0859: parmName, applyInputsToFormat(parmValue));
0860: } else {
0861: error(Messages
0862: .getErrorString("JFreeReport.ERROR_0027_REPORT_CONFIGURATION_PARAMETER_IGNORED")); //$NON-NLS-1$
0863: }
0864: } else {
0865: error(Messages
0866: .getErrorString("JFreeReport.ERROR_0027_REPORT_CONFIGURATION_PARAMETER_IGNORED")); //$NON-NLS-1$
0867: }
0868: }
0869:
0870: }
0871:
0872: private void setReportConfigParameters(JFreeReport report,
0873: Map values) {
0874: Map.Entry ent;
0875: ModifiableConfiguration config = report
0876: .getReportConfiguration();
0877: Iterator it = values.entrySet().iterator();
0878: while (it.hasNext()) {
0879: ent = (Map.Entry) it.next();
0880: if ((ent.getKey() != null) && (ent.getValue() != null)) {
0881: config.setConfigProperty(ent.getKey().toString(),
0882: applyInputsToFormat(ent.getValue().toString()));
0883: }
0884: }
0885: }
0886:
0887: private void setReportConfigParameters(JFreeReport report,
0888: IPentahoResultSet values) {
0889: int rowCount = values.getRowCount();
0890: int colCount = values.getColumnCount();
0891: ModifiableConfiguration config = report
0892: .getReportConfiguration();
0893: if (colCount >= 2) {
0894: IPentahoMetaData md = values.getMetaData();
0895: int nameIdx = md.getColumnIndex("name");//$NON-NLS-1$
0896: int valIdx = md.getColumnIndex("value");//$NON-NLS-1$
0897: if (nameIdx < 0) {
0898: nameIdx = 0;
0899: }
0900: if (valIdx < 0) {
0901: valIdx = 1;
0902: }
0903: for (int i = 0; i < rowCount; i++) {
0904: Object[] aRow = values.getDataRow(i);
0905: if ((aRow[nameIdx] != null) && (aRow[valIdx] != null)) {
0906: config
0907: .setConfigProperty(
0908: aRow[nameIdx].toString(),
0909: applyInputsToFormat(aRow[valIdx]
0910: .toString()));
0911: }
0912: }
0913: } else {
0914: error(Messages
0915: .getErrorString("JFreeReport.ERROR_0025_INVALID_REPORT_CONFIGURATION_PARAMETERS")); //$NON-NLS-1$
0916: }
0917: }
0918:
0919: private boolean initReportInputs(JFreeReport report)
0920: throws CloneNotSupportedException {
0921:
0922: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
0923: // Get input parameters, and set them as properties in the report
0924: // object.
0925: ActionInput[] actionInputs = jFreeReportAction
0926: .getAllInputParams();
0927: for (int i = 0; i < actionInputs.length; i++) {
0928: String paramName = actionInputs[i].getName();
0929: Object paramValue = actionInputs[i].getValue();
0930: if (paramValue == null || "".equals(paramValue)) { //$NON-NLS-1$
0931: continue;
0932: }
0933:
0934: // we filter some well-known bad-guys. It is dangerous to have the
0935: // report-object (the parsed JFreeReport object), the "report-data"
0936: // (the tablemodel) or the "data" reference copied to the report.
0937: // also dangerous are result sets and table models.
0938:
0939: if (paramValue instanceof IPentahoResultSet) {
0940: continue;
0941: }
0942: if (paramValue instanceof TableModel) {
0943: continue;
0944: }
0945: if (DATACOMPONENT_REPORTTEMP_OBJINPUT.equals(paramName)) {
0946: continue;
0947: }
0948: if (DATACOMPONENT_REPORTTEMP_DATAFACTORY.equals(paramName)) {
0949: continue;
0950: }
0951: if (DATACOMPONENT_REPORTTEMP_DATAINPUT.equals(paramName)) {
0952: continue;
0953: }
0954: if (DATACOMPONENT_DATAINPUT.equals(paramName)) {
0955: continue;
0956: }
0957:
0958: if (paramValue instanceof Object[]) {
0959: Object values[] = (Object[]) paramValue;
0960: StringBuffer valuesBuffer = new StringBuffer();
0961: // TODO support non-string items
0962: for (int j = 0; j < values.length; j++) {
0963: if (j == 0) {
0964: valuesBuffer.append(values[j].toString());
0965: } else {
0966: valuesBuffer.append(',').append(
0967: values[j].toString());
0968: }
0969: }
0970: report.setProperty(paramName, valuesBuffer.toString());
0971: } else {
0972: report.setProperty(paramName, paramValue);
0973: }
0974: }
0975: return true;
0976: }
0977:
0978: private String getMimeType(String outputFormat) {
0979: String mimeType = null;
0980: if (REPORTALLCONTENT_OUTPUTTYPE_HTML.equals(outputFormat)) {
0981: mimeType = "text/html";
0982: } else if (REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(outputFormat)) {
0983: mimeType = "application/pdf";
0984: } else if (REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(outputFormat)) {
0985: mimeType = "application/vnd.ms-excel";
0986: } else if (REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(outputFormat)) {
0987: mimeType = "text/csv";
0988: } else if (REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(outputFormat)) {
0989: mimeType = "application/rtf";
0990: } else if (REPORTALLCONTENT_OUTPUTTYPE_XML.equals(outputFormat)) {
0991: mimeType = "text/xml";
0992: }
0993: return mimeType;
0994: }
0995:
0996: private String getFileExtension(String outputFormat) {
0997: String fileExtension = null;
0998: if (REPORTALLCONTENT_OUTPUTTYPE_HTML.equals(outputFormat)) {
0999: fileExtension = ".html";
1000: } else if (REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(outputFormat)) {
1001: fileExtension = ".pdf";
1002: } else if (REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(outputFormat)) {
1003: fileExtension = ".xls";
1004: } else if (REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(outputFormat)) {
1005: fileExtension = ".csv";
1006: } else if (REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(outputFormat)) {
1007: fileExtension = ".rtf";
1008: } else if (REPORTALLCONTENT_OUTPUTTYPE_XML.equals(outputFormat)) {
1009: fileExtension = ".xml";
1010: }
1011: return fileExtension;
1012: }
1013:
1014: private boolean generateReport(JFreeReport report,
1015: PentahoTableDataFactory factory) throws IOException {
1016: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
1017:
1018: boolean result = false;
1019:
1020: applyThreadPriority();
1021:
1022: // this might be invalid in case the action is contained in a sub-directory.
1023: final String baseName = IOUtils.getInstance()
1024: .stripFileExtension(getActionName());
1025: final String path = getSolutionName() + File.separator
1026: + getSolutionPath();
1027: final PentahoResourceBundleFactory bundleFactory = new PentahoResourceBundleFactory(
1028: path, baseName, getSession());
1029: report.setResourceBundleFactory(bundleFactory);
1030: // set the default resourcebundle. This allows users to override the
1031: // resource-bundle in case they want to keep common strings in a common
1032: // collection.
1033: report
1034: .getReportConfiguration()
1035: .setConfigProperty(
1036: ResourceBundleFactory.DEFAULT_RESOURCE_BUNDLE_CONFIG_KEY,
1037: baseName);
1038:
1039: if (factory != null) {
1040: report.setDataFactory(factory);
1041: }
1042:
1043: Object reportWriter = null;
1044: String printerName = jFreeReportAction.getPrinterName()
1045: .getStringValue();
1046: String outputFormat = jFreeReportAction.getOutputType()
1047: .getStringValue();
1048:
1049: if (printerName != null) {
1050: result = print(report, getActionTitle(), printerName);
1051: } else if (REPORTALLCONTENT_OUTPUTTYPE_SWING
1052: .equals(outputFormat)) {
1053: if (GraphicsEnvironment.isHeadless()) {
1054: result = writeSwingPreview(report);
1055: }
1056: warn(Messages
1057: .getString("JFreeReportAllContentComponent.WARN_HEADLESSMODE_ACTIVE")); //$NON-NLS-1$
1058: } else if (REPORTALLCONTENT_OUTPUTTYPE_HTML
1059: .equals(outputFormat)
1060: || REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(outputFormat)
1061: || REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(outputFormat)
1062: || REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(outputFormat)
1063: || REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(outputFormat)
1064: || REPORTALLCONTENT_OUTPUTTYPE_XML.equals(outputFormat)) {
1065: String mimeType = getMimeType(outputFormat);
1066: String fileExtention = getFileExtension(outputFormat);
1067: IContentItem contentItem = getContentItem(mimeType,
1068: fileExtention);
1069: OutputStream outputStream = null;
1070: if (contentItem != null) {
1071: outputStream = contentItem
1072: .getOutputStream(getActionName());
1073: } else {
1074: outputStream = getDefaultOutputStream(mimeType);
1075: }
1076: result = writeReport(outputFormat, report, outputStream,
1077: jFreeReportAction.getReportGenerationYieldRate()
1078: .getIntValue(0), jFreeReportAction
1079: .getHtmlContentHandlerUrlPattern()
1080: .getStringValue());
1081: if (contentItem != null) {
1082: contentItem.closeOutputStream();
1083: }
1084: } else {
1085: warn(Messages
1086: .getString("JFreeReportAllContentComponent.WARN_NO_PRINTER_GIVEN")); //$NON-NLS-1$
1087: }
1088: return result;
1089: }
1090:
1091: private void applyThreadPriority() {
1092: String priority = ((JFreeReportAction) getActionDefinition())
1093: .getReportGenerationPriority().getStringValue();
1094: try {
1095: if (REPORTGENERATE_PRIORITYLOWER.equals(priority)) {
1096: Thread.currentThread().setPriority(
1097: Math
1098: .max(Thread.currentThread()
1099: .getPriority() - 1, 1));
1100: } else if (REPORTGENERATE_PRIORITYLOWEST.equals(priority)) {
1101: Thread.currentThread().setPriority(1);
1102: }
1103: } catch (Exception e) {
1104: // Non fatal exception.
1105: warn(Messages
1106: .getString("AbstractGenerateContentComponent.ERROR_0044_UNABLE_T0_SET_THREAD_PRIORITY")); //$NON-NLS-1$
1107: }
1108: }
1109:
1110: protected IContentItem getContentItem(String mimeType,
1111: String extension) {
1112: JFreeReportAction jFreeReportAction = (JFreeReportAction) getActionDefinition();
1113: // Try to get the output from the action-sequence document.
1114: IContentItem contentItem = null;
1115: ActionOutput actionOutput = jFreeReportAction.getOutputReport();
1116: if (actionOutput != null) {
1117: contentItem = getOutputItem(actionOutput.getName(),
1118: mimeType, extension);
1119: contentItem.setMimeType(mimeType);
1120: } else if (getOutputNames().size() == 1) {
1121: String outputName = (String) getOutputNames().iterator()
1122: .next();
1123: contentItem = getOutputContentItem(outputName, mimeType);
1124: contentItem.setMimeType(mimeType);
1125: }
1126: return contentItem;
1127: }
1128:
1129: private boolean writeReport(String outputFormat,
1130: JFreeReport report, OutputStream outputStream,
1131: int yieldRate, String htmlContentHandlerUrlPattern) {
1132: boolean result = false;
1133: if (REPORTALLCONTENT_OUTPUTTYPE_HTML.equals(outputFormat)) {
1134: result = writeHtml(report, outputStream, yieldRate,
1135: htmlContentHandlerUrlPattern);
1136: } else if (REPORTALLCONTENT_OUTPUTTYPE_PDF.equals(outputFormat)) {
1137: result = writePdf(report, outputStream, yieldRate);
1138: } else if (REPORTALLCONTENT_OUTPUTTYPE_XLS.equals(outputFormat)) {
1139: result = writeXls(report, outputStream, yieldRate);
1140: } else if (REPORTALLCONTENT_OUTPUTTYPE_CSV.equals(outputFormat)) {
1141: result = writeCsv(report, outputStream, yieldRate);
1142: } else if (REPORTALLCONTENT_OUTPUTTYPE_RTF.equals(outputFormat)) {
1143: result = writeRtf(report, outputStream, yieldRate);
1144: } else if (REPORTALLCONTENT_OUTPUTTYPE_XML.equals(outputFormat)) {
1145: result = writeXml(report, outputStream);
1146: }
1147: return result;
1148: }
1149:
1150: public boolean writeHtml(JFreeReport report,
1151: OutputStream outputStream, int yieldRate,
1152: String htmlContentHandlerUrlPattern) {
1153: try {
1154: IContentRepository contentRepository = null;
1155: try {
1156: contentRepository = PentahoSystem
1157: .getContentRepository(getSession());
1158: } catch (Throwable t) {
1159: debug(
1160: Messages
1161: .getString("JFreeReportHtmlComponent.DEBUG_0044_PROCESSING_WITHOUT_CONTENT_REPOS"), t); //$NON-NLS-1$
1162: }
1163:
1164: if (htmlContentHandlerUrlPattern == null) {
1165: final Configuration globalConfig = JFreeReportBoot
1166: .getInstance().getGlobalConfig();
1167: htmlContentHandlerUrlPattern = globalConfig
1168: .getConfigProperty("org.pentaho.web.ContentHandler"); //$NON-NLS-1$
1169: }
1170:
1171: final IApplicationContext ctx = PentahoSystem
1172: .getApplicationContext();
1173:
1174: final URLRewriter rewriter;
1175: final ContentLocation dataLocation;
1176: final NameGenerator dataNameGenerator;
1177: if (contentRepository == null
1178: || DO_NOT_USE_THE_CONTENT_REPOSITORY) {
1179: debug(Messages
1180: .getString("JFreeReportHtmlComponent.DEBUG_0044_PROCESSING_WITHOUT_CONTENT_REPOS")); //$NON-NLS-1$
1181: if (ctx != null) {
1182: File dataDirectory = new File(ctx
1183: .getFileOutputPath("system/tmp/"));//$NON-NLS-1$
1184: if (dataDirectory.exists()
1185: && dataDirectory.isDirectory() == false) {
1186: dataDirectory = dataDirectory.getParentFile();
1187: if (dataDirectory.isDirectory() == false) {
1188: throw new ReportProcessingException(
1189: Messages
1190: .getErrorString(
1191: "JFreeReportDirectoryComponent.ERROR_0001_INVALID_DIR", dataDirectory.getPath())); //$NON-NLS-1$
1192: }
1193: } else if (dataDirectory.exists() == false) {
1194: dataDirectory.mkdirs();
1195: }
1196:
1197: final FileRepository dataRepository = new FileRepository(
1198: dataDirectory);
1199: dataLocation = dataRepository.getRoot();
1200: dataNameGenerator = new DefaultNameGenerator(
1201: dataLocation);
1202: rewriter = new PentahoURLRewriter(
1203: htmlContentHandlerUrlPattern);
1204: } else {
1205: dataLocation = null;
1206: dataNameGenerator = null;
1207: rewriter = new PentahoURLRewriter(
1208: htmlContentHandlerUrlPattern);
1209: }
1210: } else {
1211: debug(Messages
1212: .getString("JFreeReportHtmlComponent.DEBUG_045_PROCESSING_WITH_CONTENT_REPOS")); //$NON-NLS-1$
1213: final String thePath = getSolutionName()
1214: + "/" + getSolutionPath() + "/" + getSession().getId();//$NON-NLS-1$//$NON-NLS-2$
1215: final IContentLocation pentahoContentLocation = contentRepository
1216: .newContentLocation(thePath, getActionName(),
1217: getActionTitle(), getSolutionPath(),
1218: true);
1219: // todo
1220: final ReportContentRepository repository = new ReportContentRepository(
1221: pentahoContentLocation, getActionName());
1222: dataLocation = repository.getRoot();
1223: dataNameGenerator = new DefaultNameGenerator(
1224: dataLocation);
1225: rewriter = new PentahoURLRewriter(
1226: htmlContentHandlerUrlPattern);
1227: }
1228:
1229: final StreamRepository targetRepository = new StreamRepository(
1230: null, outputStream);
1231: final ContentLocation targetRoot = targetRepository
1232: .getRoot();
1233:
1234: final HtmlOutputProcessor outputProcessor = new StreamHtmlOutputProcessor(
1235: report.getConfiguration());
1236: final HtmlPrinter printer = new AllItemsHtmlPrinter(report
1237: .getResourceManager());
1238: printer.setContentWriter(targetRoot,
1239: new DefaultNameGenerator(targetRoot,
1240: "index", "html"));//$NON-NLS-1$//$NON-NLS-2$
1241: printer.setDataWriter(dataLocation, dataNameGenerator);
1242: printer.setUrlRewriter(rewriter);
1243: outputProcessor.setPrinter(printer);
1244:
1245: final StreamReportProcessor sp = new StreamReportProcessor(
1246: report, outputProcessor);
1247: if (yieldRate > 0) {
1248: sp.addReportProgressListener(new YieldReportListener(
1249: yieldRate));
1250: }
1251: sp.processReport();
1252: sp.close();
1253:
1254: outputStream.flush();
1255: return true;
1256: } catch (ReportProcessingException e) {
1257: error(
1258: Messages
1259: .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e); //$NON-NLS-1$
1260: return false;
1261: } catch (IOException e) {
1262: error(
1263: Messages
1264: .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e); //$NON-NLS-1$
1265: return false;
1266: } catch (ContentIOException e) {
1267: error(
1268: Messages
1269: .getString("JFreeReportHtmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e); //$NON-NLS-1$
1270: return false;
1271: }
1272: }
1273:
1274: protected boolean writeXls(final JFreeReport report,
1275: final OutputStream outputStream, int yieldRate) {
1276: boolean result = false;
1277: try {
1278: final FlowExcelOutputProcessor target = new FlowExcelOutputProcessor(
1279: report.getConfiguration(), outputStream);
1280: final FlowReportProcessor reportProcessor = new FlowReportProcessor(
1281: report, target);
1282:
1283: if (isDefinedInput(WORKBOOK_PARAM)) {
1284: target
1285: .setTemplateInputStream(getInputStream(WORKBOOK_PARAM));
1286: }
1287: if (yieldRate > 0) {
1288: reportProcessor
1289: .addReportProgressListener(new YieldReportListener(
1290: yieldRate));
1291: }
1292: reportProcessor.processReport();
1293: reportProcessor.close();
1294: outputStream.flush();
1295: result = true;
1296: } catch (Exception e) {
1297: error(
1298: Messages
1299: .getString("JFreeReportExcelComponent.ERROR_0037_ERROR_READING_REPORT_INPUT"), e); //$NON-NLS-1$
1300: }
1301: return result;
1302: }
1303:
1304: protected boolean writePdf(final JFreeReport report,
1305: final OutputStream outputStream, int yieldRate) {
1306: PageableReportProcessor proc = null;
1307: boolean result = false;
1308: try {
1309:
1310: final PdfOutputProcessor outputProcessor = new PdfOutputProcessor(
1311: report.getConfiguration(), outputStream);
1312: proc = new PageableReportProcessor(report, outputProcessor);
1313: if (yieldRate > 0) {
1314: proc.addReportProgressListener(new YieldReportListener(
1315: yieldRate));
1316: }
1317: proc.processReport();
1318: proc.close();
1319: proc = null;
1320: result = true;
1321: } catch (Exception e) {
1322: org.jfree.util.Log
1323: .error(
1324: Messages
1325: .getErrorString(
1326: "JFreeReportPdfComponent.ERROR_0001_WRITING_PDF_FAILED", //$NON-NLS-1$
1327: e.getLocalizedMessage()), e);
1328: } finally {
1329: if (proc != null) {
1330: proc.close();
1331: }
1332: }
1333: return result;
1334: }
1335:
1336: public boolean print(JFreeReport report, String jobName,
1337: String printerName) {
1338: boolean result = false;
1339: if (jobName != null) {
1340: report.getReportConfiguration().setConfigProperty(
1341: PrintUtil.PRINTER_JOB_NAME_KEY,
1342: String.valueOf(jobName));
1343: }
1344:
1345: PrintService printer = null;
1346: PrintService[] services = PrintServiceLookup
1347: .lookupPrintServices(
1348: DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
1349: for (int i = 0; i < services.length; i++) {
1350: final PrintService service = services[i];
1351: if (service.getName().equals(printerName)) {
1352: printer = service;
1353: }
1354: }
1355: if ((printer == null) && (services.length > 0)) {
1356: printer = services[0];
1357: }
1358:
1359: try {
1360: Java14PrintUtil.printDirectly(report, printer);
1361: result = true;
1362: } catch (PrintException e) {
1363: } catch (ReportProcessingException e) {
1364: }
1365: return result;
1366: }
1367:
1368: protected boolean writeCsv(final JFreeReport report,
1369: final OutputStream outputStream, int yieldRate) {
1370: boolean result = false;
1371: try {
1372: final StreamCSVOutputProcessor target = new StreamCSVOutputProcessor(
1373: report.getConfiguration(), outputStream);
1374: final StreamReportProcessor reportProcessor = new StreamReportProcessor(
1375: report, target);
1376: if (yieldRate > 0) {
1377: reportProcessor
1378: .addReportProgressListener(new YieldReportListener(
1379: yieldRate));
1380: }
1381: reportProcessor.processReport();
1382: reportProcessor.close();
1383: outputStream.flush();
1384: result = true;
1385: } catch (ReportProcessingException e) {
1386: } catch (IOException e) {
1387: }
1388: return result;
1389: }
1390:
1391: protected boolean writeRtf(final JFreeReport report,
1392: final OutputStream outputStream, int yieldRate) {
1393: boolean result = false;
1394: try {
1395: final StreamRTFOutputProcessor target = new StreamRTFOutputProcessor(
1396: report.getConfiguration(), outputStream);
1397: final StreamReportProcessor proc = new StreamReportProcessor(
1398: report, target);
1399: if (yieldRate > 0) {
1400: proc.addReportProgressListener(new YieldReportListener(
1401: yieldRate));
1402: }
1403: proc.processReport();
1404: proc.close();
1405: outputStream.close();
1406: result = true;
1407: } catch (ReportProcessingException e) {
1408: } catch (IOException e) {
1409: }
1410: return result;
1411: }
1412:
1413: protected boolean writeXml(final JFreeReport report,
1414: final OutputStream outputStream) {
1415: boolean result = false;
1416: try {
1417: final XMLProcessor processor = new XMLProcessor(report);
1418: final OutputStreamWriter writer = new OutputStreamWriter(
1419: outputStream);
1420: processor.setWriter(writer);
1421: processor.processReport();
1422:
1423: writer.close();
1424: result = true;
1425: } catch (ReportProcessingException e) {
1426: error(
1427: Messages
1428: .getString("JFreeReportXmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e); //$NON-NLS-1$
1429: } catch (IOException e) {
1430: error(
1431: Messages
1432: .getString("JFreeReportXmlComponent.ERROR_0046_FAILED_TO_PROCESS_REPORT"), e); //$NON-NLS-1$
1433: }
1434: return result;
1435: }
1436:
1437: protected boolean writeSwingPreview(final JFreeReport report) {
1438: final ModifiableConfiguration reportConfiguration = report
1439: .getReportConfiguration();
1440:
1441: final boolean progressBar = getInputBooleanValue(
1442: REPORTSWING_PROGRESSBAR,
1443: "true" .equals(reportConfiguration.getConfigProperty(PROGRESS_BAR_ENABLED_KEY)));//$NON-NLS-1$
1444: final boolean progressDialog = getInputBooleanValue(
1445: REPORTSWING_PROGRESSDIALOG,
1446: "true" .equals(reportConfiguration.getConfigProperty(PROGRESS_DIALOG_ENABLED_KEY)));//$NON-NLS-1$
1447: reportConfiguration.setConfigProperty(
1448: PROGRESS_DIALOG_ENABLED_KEY, String
1449: .valueOf(progressDialog));
1450: reportConfiguration.setConfigProperty(PROGRESS_BAR_ENABLED_KEY,
1451: String.valueOf(progressBar));
1452:
1453: final PreviewDialog dialog = createDialog(report);
1454: final ReportController reportController = getReportController();
1455: if (reportController != null) {
1456: dialog.setReportController(reportController);
1457: }
1458: dialog.pack();
1459: if (dialog.getParent() != null) {
1460: RefineryUtilities.centerDialogInParent(dialog);
1461: } else {
1462: RefineryUtilities.centerFrameOnScreen(dialog);
1463: }
1464:
1465: dialog.setVisible(true);
1466: return true;
1467: }
1468:
1469: private ReportController getReportController() {
1470: if (isDefinedInput(REPORTSWING_REPORTCONTROLLER)) {
1471: final Object controller = getInputValue(REPORTSWING_REPORTCONTROLLER);
1472: if (controller instanceof ReportController) {
1473: return (ReportController) controller;
1474: }
1475: }
1476: return null;
1477: }
1478:
1479: private PreviewDialog createDialog(final JFreeReport report) {
1480: final boolean modal = getInputBooleanValue(REPORTSWING_MODAL,
1481: true);
1482:
1483: if (isDefinedInput(REPORTSWING_PARENTDIALOG)) {
1484: final Object parent = getInputValue(REPORTSWING_PARENTDIALOG);
1485: if (parent instanceof Dialog) {
1486: return new PreviewDialog(report, (Dialog) parent, modal);
1487: } else if (parent instanceof Frame) {
1488: return new PreviewDialog(report, (Frame) parent, modal);
1489: }
1490: }
1491:
1492: final PreviewDialog previewDialog = new PreviewDialog(report);
1493: previewDialog.setModal(modal);
1494: return previewDialog;
1495: }
1496: }
|