Example usage for org.dom4j.io SAXReader setEntityResolver

List of usage examples for org.dom4j.io SAXReader setEntityResolver

Introduction

In this page you can find the example usage for org.dom4j.io SAXReader setEntityResolver.

Prototype

public void setEntityResolver(EntityResolver entityResolver) 

Source Link

Document

Sets the entity resolver used to resolve entities.

Usage

From source file:org.pentaho.di.ui.trans.steps.getxmldata.XMLInputFieldsImportProgressDialog.java

License:Apache License

@SuppressWarnings("unchecked")
private RowMetaAndData[] doScan(IProgressMonitor monitor) throws Exception {
    monitor.beginTask(//from  w w w.j av  a 2 s  . c  om
            BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ScanningFile", filename),
            1);

    SAXReader reader = XMLParserFactoryProducer.getSAXReader(null);
    monitor.worked(1);
    if (monitor.isCanceled()) {
        return null;
    }
    // Validate XML against specified schema?
    if (meta.isValidating()) {
        reader.setValidation(true);
        reader.setFeature("http://apache.org/xml/features/validation/schema", true);
    } else {
        // Ignore DTD
        reader.setEntityResolver(new IgnoreDTDEntityResolver());
    }
    monitor.worked(1);
    monitor.beginTask(
            BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingDocument"), 1);
    if (monitor.isCanceled()) {
        return null;
    }
    InputStream is = null;
    try {

        Document document = null;
        if (!Utils.isEmpty(filename)) {
            is = KettleVFS.getInputStream(filename);
            document = reader.read(is, encoding);
        } else {
            if (!Utils.isEmpty(xml)) {
                document = reader.read(new StringReader(xml));
            } else {
                document = reader.read(new URL(url));
            }
        }

        monitor.worked(1);
        monitor.beginTask(
                BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.DocumentOpened"), 1);
        monitor.worked(1);
        monitor.beginTask(
                BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.ReadingNode"), 1);

        if (monitor.isCanceled()) {
            return null;
        }
        List<Node> nodes = document.selectNodes(this.loopXPath);
        monitor.worked(1);
        monitor.subTask(BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes"));

        if (monitor.isCanceled()) {
            return null;
        }
        for (Node node : nodes) {
            if (monitor.isCanceled()) {
                return null;
            }

            nr++;
            monitor.subTask(BaseMessages.getString(PKG,
                    "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", String.valueOf(nr)));
            monitor.subTask(BaseMessages.getString(PKG,
                    "GetXMLDateLoopNodesImportProgressDialog.Task.FetchNodes", node.getPath()));
            setNodeField(node, monitor);
            childNode(node, monitor);

        }
        monitor.worked(1);
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (Exception e) { /* Ignore */
        }
    }

    RowMetaAndData[] listFields = fieldsList.toArray(new RowMetaAndData[fieldsList.size()]);

    monitor.setTaskName(
            BaseMessages.getString(PKG, "GetXMLDateLoopNodesImportProgressDialog.Task.NodesReturned"));

    monitor.done();

    return listFields;

}

From source file:org.pentaho.jpivot.AnalysisSaver.java

License:Open Source License

public static boolean saveAnalysis(final IPentahoSession session, final HashMap props, String path,
        String fileName, final boolean overwrite) {

    if ("true".equals(PentahoSystem.getSystemSetting("kiosk-mode", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        throw new RuntimeException(
                Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0006_SAVE_IS_DISABLED")); //$NON-NLS-1$
    }//from   w  ww  . ja  va2  s.  c  o  m

    try {
        AnalysisSaver.logger = LogFactory.getLog(AnalysisSaver.class);

        // TODO: if this is a new JPivot report, get doc from generateXAction

        // We will (at this point in time) always have an original action sequence to start from...
        String originalActionReference = (String) props.get("actionreference"); //$NON-NLS-1$

        if (originalActionReference == null) {
            throw new MissingParameterException(
                    Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0001_MISSING_ACTION_REFERENCE")); //$NON-NLS-1$
        }
        Document document = null;
        if (NEW_ACTION.equals(originalActionReference)) {
            String model = (String) props.get(PivotViewComponent.MODEL);
            String jndi = (String) props.get(PivotViewComponent.CONNECTION);
            String jdbc = null; // NOT SUPPORTED AT THIS TIME
            String cube = null; // No need, MDX statement already exists 

            String xaction = new AnalysisViewService().generateXAction(PentahoSessionHolder.getSession(),
                    Messages.getInstance().getString("BaseTest.DEFAULT_TITLE"),
                    Messages.getInstance().getString("BaseTest.DEFAULT_DESCRIPTION"), model, jndi, jdbc, cube);
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            final String encoding = XmlHelper.getEncoding(xaction, null);
            document = reader.read(new ByteArrayInputStream(xaction.getBytes(encoding)));
        } else {
            try {
                org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
                reader.setEntityResolver(new SolutionURIResolver());
                document = reader.read(ActionSequenceResource.getInputStream(originalActionReference,
                        LocaleHelper.getLocale()));
            } catch (Throwable t) {
                // XML document can't be read. We'll just return a null document.
            }
        }
        // Update the document with the stuff we passed in on the props
        document = AnalysisSaver.updateDocument(document, props);
        fileName = fileName.endsWith(AnalysisSaver.SUFFIX) ? fileName : fileName + AnalysisSaver.SUFFIX;

        path = cleansePath(path, fileName);

        // Write contents to Unified Repository

        RepositoryFile jpivotRepoFile = null;
        IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class);
        try {
            jpivotRepoFile = repository.getFile(path + '/' + fileName);
        } catch (UnifiedRepositoryException e) {
            // file does not exist, ignore exception
        }
        if (jpivotRepoFile != null) {
            jpivotRepoFile = repository.updateFile(jpivotRepoFile,
                    new SimpleRepositoryFileData(
                            new ByteArrayInputStream(document.asXML().getBytes(document.getXMLEncoding())),
                            LocaleHelper.getSystemEncoding(), "application/xml"),
                    "Update to existing file");
        } else {
            RepositoryFile parentFile = repository.getFile(path);
            jpivotRepoFile = new RepositoryFile.Builder(fileName).title(RepositoryFile.ROOT_LOCALE, fileName)
                    .description(RepositoryFile.ROOT_LOCALE, fileName).build();
            jpivotRepoFile = repository.createFile(parentFile.getId(), jpivotRepoFile,
                    new SimpleRepositoryFileData(
                            new ByteArrayInputStream(document.asXML().getBytes(document.getXMLEncoding())),
                            LocaleHelper.getSystemEncoding(), "application/xml"),
                    "Initial JPivot View Check-in");
        }
    } catch (Exception e) {
        AnalysisSaver.logger.error(Messages.getInstance().getErrorString("ANALYSISSAVER.ERROR_0000_UNKNOWN"), //$NON-NLS-1$
                e);
        return false;
    }

    return true;
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

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

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

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

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

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

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

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

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

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

License:Open Source License

public void getTemplateReportSpec(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap)
        throws AdhocWebServiceException, IOException {
    String responseEncoding = PentahoSystem.getSystemSetting("web-service-encoding", "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$
    String reportSpecName = parameterProvider.getStringParameter("reportSpecPath", null); //$NON-NLS-1$
    Document reportSpecDoc = null;
    if (!StringUtils.isEmpty(reportSpecName)) {
        reportSpecName = AdhocContentGenerator.WAQR_REPOSITORY_PATH + reportSpecName;
        try {// ww w. j a  v a 2s . co m
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            reportSpecDoc = reader
                    .read(ActionSequenceResource.getInputStream(reportSpecName, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }
    } else {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0005_MISSING_REPORTSPEC_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    XmlDom4JHelper.saveDom(reportSpecDoc, outputStream, responseEncoding, wrapWithSoap);
}

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

License:Open Source License

public void getWaqrReportSpecDoc(final IParameterProvider parameterProvider, final OutputStream outputStream,
        final IPentahoSession userSession, final boolean wrapWithSoap)
        throws AdhocWebServiceException, IOException {
    String responseEncoding = PentahoSystem.getSystemSetting("web-service-encoding", "utf-8"); //$NON-NLS-1$ //$NON-NLS-2$
    String solution = parameterProvider.getStringParameter("solution", null); //$NON-NLS-1$
    String path = parameterProvider.getStringParameter("path", null); //$NON-NLS-1$
    String filename = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$

    path = URLDecoder.decode(path);
    // replace the extension to get to the report spec
    int pos = filename.lastIndexOf("."); //$NON-NLS-1$
    filename = filename.substring(0, pos + 1) + "xreportspec"; //$NON-NLS-1$

    Document reportSpecDoc = null;
    if (!StringUtils.isEmpty(solution) && (null != path) && !StringUtils.isEmpty(filename)) {
        String filePath = ActionInfo.buildSolutionPath(solution, path, filename);
        try {//  www  .j  a v  a 2  s. co m
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            reportSpecDoc = reader
                    .read(ActionSequenceResource.getInputStream(filePath, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }
    } else {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0005_MISSING_REPORTSPEC_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    /*
     * -------------------------------- BISERVER-5263
     * --------------------------------------- Pre-3.6 ReportSpecs generated by
     * waqr didn't have an xmi file specified in the domain_id node. Below we
     * detect this condition (ie. we're trying to edit a pre-3.6 report using a
     * 3.7 dist) and we specify the default metadata.xmi file for the solution
     * specified.
     */
    Node domainIdNode = reportSpecDoc.selectSingleNode("//report-spec/query/mql/domain_id"); //$NON-NLS-1$
    String domainId = domainIdNode.getText();
    if (!domainId.endsWith(".xmi")) { //$NON-NLS-1$
        domainId += "/metadata.xmi"; //$NON-NLS-1$
        domainIdNode.setText(domainId);
    }
    // ---------------------------------------------------------------------------------------
    XmlDom4JHelper.saveDom(reportSpecDoc, outputStream, responseEncoding, wrapWithSoap);
}

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

License:Open Source License

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

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

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

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

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

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

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

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

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

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

License:Open Source License

public Document getTemplateReportSpec(final IParameterProvider parameterProvider,
        final IPentahoSession userSession) throws AdhocWebServiceException, IOException {

    String reportSpecName = parameterProvider.getStringParameter("reportSpecPath", null); //$NON-NLS-1$
    Document reportSpecDoc = null;
    if (!StringUtils.isEmpty(reportSpecName)) {
        reportSpecName = AdhocWebService.WAQR_REPOSITORY_PATH + reportSpecName;
        try {/*from ww w  .  j av  a  2s  .  c o m*/
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            reportSpecDoc = reader
                    .read(ActionSequenceResource.getInputStream(reportSpecName, LocaleHelper.getLocale()));
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }
    } else {
        String msg = Messages.getInstance().getString("AdhocWebService.ERROR_0005_MISSING_REPORTSPEC_NAME"); //$NON-NLS-1$
        throw new AdhocWebServiceException(msg);
    }
    return reportSpecDoc;
}

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

License:Open Source License

public Document getWaqrReportSpecDoc(final IParameterProvider parameterProvider,
        final IPentahoSession userSession) throws AdhocWebServiceException, IOException {

    IUnifiedRepository repository = PentahoSystem.get(IUnifiedRepository.class, userSession);
    String fileName = parameterProvider.getStringParameter("filename", null); //$NON-NLS-1$
    if (fileName != null) {
        String cleansedFileName = idToPath(fileName);
        String reportSpecFile = cleansedFileName.substring(0, fileName.lastIndexOf('.') + 1)
                + WAQR_XREPORTSPEC_FILE_EXTENSION;
        Document reportSpecDoc = null;
        try {/* w  ww  .  j a  v  a 2 s . c  o  m*/
            RepositoryFile file = repository
                    .getFile(URLDecoder.decode(reportSpecFile, LocaleHelper.getSystemEncoding()));
            RepositoryFileInputStream is = new RepositoryFileInputStream(file);
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            reader.setEntityResolver(new SolutionURIResolver());
            reportSpecDoc = reader.read(is);
        } catch (Throwable t) {
            // XML document can't be read. We'll just return a null document.
        }
        return reportSpecDoc;
    } else {
        return null;
    }
}

From source file:org.pentaho.platform.uifoundation.component.xml.WidgetGridComponent.java

License:Open Source License

@Override
public Document getXmlContent() {

    // get the data to populate the widgets
    IPentahoResultSet resultSet = null;/*www .j  av a  2 s  .c  o m*/
    if (solution != null) {
        resultSet = getActionData();
    }

    // create the widget to use
    // load the XML document that defines the dial
    Document dialDefinition = null;
    try {
        org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
        reader.setEntityResolver(new SolutionURIResolver());
        dialDefinition = reader
                .read(ActionSequenceResource.getInputStream(definitionPath, LocaleHelper.getLocale()));
    } catch (Throwable t) {
        // XML document can't be read. We'll just return a null document.
    }

    // create a dial definition from the XML definition
    WidgetDefinition widgetDefinition = new DialWidgetDefinition(dialDefinition, 0, widgetWidth, widgetHeight,
            getSession());

    return createDials(resultSet, widgetDefinition);
}

From source file:org.sapia.soto.hibernate.HibernateServiceImpl.java

License:Open Source License

/**
 * @see org.sapia.soto.Service#init()/*w ww .java  2s.co m*/
 */
public void init() throws Exception {
    if (_configResource != null) {
        InputStream confStream = _env.resolveStream(_configResource);
        try {
            SAXReader reader = new SAXReader();
            // Use hibernates entity resolver to prevent access to the net on each load
            reader.setEntityResolver(new DTDEntityResolver());
            Document doc = reader.read(confStream);
            DOMWriter writer = new DOMWriter();
            _config.configure(writer.write(doc));
        } finally {
            confStream.close();
        }
    }
    _sessions = _config.buildSessionFactory();
}