Example usage for org.dom4j Element attributes

List of usage examples for org.dom4j Element attributes

Introduction

In this page you can find the example usage for org.dom4j Element attributes.

Prototype

List<Attribute> attributes();

Source Link

Document

Returns the Attribute instances this element contains as a backed List so that the attributes may be modified directly using the List interface.

Usage

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

License:Open Source License

/**
 * Create the JFreeReport file.//from w ww  .  ja  v  a  2s  .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 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.web.servlet.AdhocWebService.java

License:Open Source License

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

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

    if (bUseTemplate) {
        templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath;
        templateDoc = repository.getResourceAsDocument(templatePath, ISolutionRepository.ACTION_EXECUTE);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }

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

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

        applyMetadata(field, column, columnWidthUnitsConsistent, locale);

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

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

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

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

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

From source file:org.pentaho.ui.xul.impl.AbstractXulLoader.java

License:Open Source License

protected void processOverlay(Element overlayEle, Element srcEle) {
    for (Object child : overlayEle.elements()) {
        Element overlay = (Element) child;
        String overlayId = overlay.attributeValue("ID");
        logger.debug("Processing overlay\nID: " + overlayId);
        Element sourceElement = srcEle.getDocument().elementByID(overlayId);
        if (sourceElement == null) {
            logger.error("Could not find corresponding element in src doc with id: " + overlayId);
            continue;
        }//from   w  w w.  ja v a  2  s . c om
        logger.debug("Found match in source doc:");

        String removeElement = overlay.attributeValue("removeelement");
        if (removeElement != null && removeElement.equalsIgnoreCase("true")) {
            sourceElement.getParent().remove(sourceElement);
        } else {

            List attribs = overlay.attributes();

            // merge in attributes
            for (Object o : attribs) {
                Attribute atr = (Attribute) o;
                sourceElement.addAttribute(atr.getName(), atr.getValue());
            }

            Document targetDocument = srcEle.getDocument();

            // lets start out by just including everything
            for (Object overlayChild : overlay.elements()) {
                Element pluckedElement = (Element) overlay.content()
                        .remove(overlay.content().indexOf(overlayChild));

                if (pluckedElement.getName().equals("dialog")) {
                    String newOnload = pluckedElement.attributeValue("onload");
                    if (newOnload != null) {
                        String existingOnload = targetDocument.getRootElement().attributeValue("onload");
                        String finalOnload = "";
                        if (existingOnload != null) {
                            finalOnload = existingOnload + ", ";
                        }
                        finalOnload += newOnload;
                        targetDocument.getRootElement().setAttributeValue("onload", finalOnload);
                    }
                }

                String insertBefore = pluckedElement.attributeValue("insertbefore");
                String insertAfter = pluckedElement.attributeValue("insertafter");
                String position = pluckedElement.attributeValue("position");

                // determine position to place it
                int positionToInsert = -1;
                if (insertBefore != null) {
                    Element insertBeforeTarget = sourceElement.elementByID(insertBefore);
                    positionToInsert = sourceElement.elements().indexOf(insertBeforeTarget);

                } else if (insertAfter != null) {
                    Element insertAfterTarget = sourceElement.elementByID(insertAfter);
                    positionToInsert = sourceElement.elements().indexOf(insertAfterTarget);
                    if (positionToInsert != -1) {
                        positionToInsert++; // we want to be after that point;
                    }
                } else if (position != null) {
                    int pos = Integer.parseInt(position);
                    positionToInsert = (pos <= sourceElement.elements().size()) ? pos : -1;
                }
                if (positionToInsert == -1) {
                    // default to last
                    positionToInsert = sourceElement.elements().size();
                }
                if (positionToInsert > sourceElement.elements().size()) {
                    sourceElement.elements().add(pluckedElement);
                } else {
                    sourceElement.elements().add(positionToInsert, pluckedElement);
                }
                logger.debug("processed overlay child: " + ((Element) overlayChild).getName() + " : "
                        + pluckedElement.getName());
            }
        }
    }
}

From source file:org.pentaho.ui.xul.impl.AbstractXulLoader.java

License:Open Source License

public void processOverlay(String overlaySrc, org.pentaho.ui.xul.dom.Document targetDocument,
        XulDomContainer container, Object resourceBundle) throws XulException {

    InputStream in = getInputStreamForSrc(overlaySrc);
    Document doc = null;// w  w  w  .jav a  2s  .co m

    ResourceBundle res = (ResourceBundle) resourceBundle;

    String runningTranslatedOutput = getDocFromInputStream(in).asXML(); // TODO IOUtils this
    if (resourceBundle != null) {
        try {
            runningTranslatedOutput = ResourceBundleTranslator.translate(runningTranslatedOutput, res);

        } catch (IOException e) {
            logger.error("Error loading resource bundle for overlay: " + overlaySrc, e);
        }
    }

    // check for top-level message bundle and apply it
    if (this.mainBundle != null) {
        try {

            runningTranslatedOutput = ResourceBundleTranslator.translate(runningTranslatedOutput,
                    this.mainBundle);
            try {
                SAXReader rdr = new SAXReader();
                String upperedIdDoc = this.upperCaseIDAttrs(runningTranslatedOutput.toString());
                doc = rdr.read(new StringReader(upperedIdDoc));
            } catch (DocumentException e) {
                logger.error("Error loading XML while applying top level message bundle to overlay file:", e);
            }
        } catch (IOException e) {
            logger.error("Error loading Resource Bundle File to apply to overlay: ", e);
        }
    } else {
        try {
            SAXReader rdr = new SAXReader();
            String upperedIdDoc = this.upperCaseIDAttrs(runningTranslatedOutput.toString());
            doc = rdr.read(new StringReader(upperedIdDoc));
        } catch (DocumentException e) {
            logger.error("Error loading XML while applying top level message bundle to overlay file:", e);
        }
    }

    Element overlayRoot = doc.getRootElement();

    for (Object child : overlayRoot.elements()) {
        Element overlay = (Element) child;
        String overlayId = overlay.attributeValue("ID");
        String removeElement = overlay.attributeValue("removeelement");

        org.pentaho.ui.xul.dom.Element sourceElement = targetDocument.getElementById(overlayId);
        if (sourceElement == null) {
            logger.warn("Cannot overlay element with id [" + overlayId + "] "
                    + "as it does not exist in the target document.");
            continue;
        }

        if (removeElement != null && removeElement.equals("true")) {
            sourceElement.getParent().removeChild(sourceElement);
        }

        parser.setClassLoaders(classloaders);
        for (Object childToParse : overlay.elements()) {
            Element childElement = (Element) childToParse;

            logger.debug("Processing overlay on element with id: " + overlayId);
            parser.reset();
            parser.setContainer(container);
            XulComponent c = parser.parse(childElement, (XulContainer) sourceElement);

            String insertBefore = childElement.attributeValue("insertbefore");
            String insertAfter = childElement.attributeValue("insertafter");
            String position = childElement.attributeValue("position");

            XulContainer sourceContainer = ((XulContainer) sourceElement);

            // determine position to place it
            int positionToInsert = -1;
            if (insertBefore != null) {
                org.pentaho.ui.xul.dom.Element insertBeforeTarget = targetDocument.getElementById(insertBefore);
                positionToInsert = sourceContainer.getChildNodes().indexOf(insertBeforeTarget);
            } else if (insertAfter != null) {
                org.pentaho.ui.xul.dom.Element insertAfterTarget = targetDocument.getElementById(insertAfter);
                positionToInsert = sourceContainer.getChildNodes().indexOf(insertAfterTarget);
                if (positionToInsert != -1) {
                    positionToInsert += 1;
                }
            } else if (position != null) {
                int pos = Integer.parseInt(position);
                positionToInsert = (pos <= sourceContainer.getChildNodes().size()) ? pos : -1;
            }
            if (positionToInsert == -1 || positionToInsert == sourceContainer.getChildNodes().size()) {
                // default to previous behavior
                sourceContainer.addChild(c);
            } else {
                sourceContainer.addChildAt(c, positionToInsert);
            }
            notifyOverlayDomReady(c);

            logger.debug("added child: " + c);
        }

        List attribs = overlay.attributes();

        // merge in attributes
        for (Object o : attribs) {
            Attribute atr = (Attribute) o;
            try {
                BeanUtils.setProperty(sourceElement, atr.getName(), atr.getValue());
                sourceElement.setAttribute(atr.getName(), atr.getValue());
            } catch (InvocationTargetException e) {
                logger.error(e);
            } catch (IllegalAccessException e) {
                logger.error(e);
            }
        }

    }

}

From source file:org.projectforge.business.gantt.GanttChartDao.java

License:Open Source License

/**
 * Removes all unnecessary GanttObject elements from the DOM (those without any information rather than the id).
 */// www. ja v  a2s  .  c  om
private boolean removeUnnecessaryElements(final Element element) {
    if (CollectionUtils.isNotEmpty(element.elements()) == true) {
        for (final Object childObj : element.elements()) {
            final Element child = (Element) childObj;
            if (removeUnnecessaryElements(child) == true) {
                element.remove(child);
            }
        }
    }
    if (CollectionUtils.isNotEmpty(element.elements()) == true) {
        // Element has descendants.
        return false;
    }
    if (StringUtils.isBlank(element.getText()) == false) {
        // Element has non blank content.
        return false;
    }
    // Element has no descendants:
    if (CollectionUtils.isEmpty(element.attributes()) == true) {
        // Element has no attributes.
        return true;
    }
    if ("predecessor".equals(element.getName()) == true) {
        if (element.attribute(XmlObjectWriter.ATTR_ID) != null) {
            // Describes a complete Gantt task which is referenced, so full output is needed.
            return false;
        } else {
            final Attribute idAttr = element.attribute("id");
            final Attribute refIdAttr = element.attribute(XmlObjectWriter.ATTR_REF_ID);
            element.setAttributes(null);
            if (refIdAttr != null) {
                element.addAttribute(XmlObjectWriter.ATTR_REF_ID, refIdAttr.getValue());
            } else if (idAttr != null) {
                // External reference (no ref-id, but task id):
                element.addAttribute("id", idAttr.getValue());
            } else {
                // Should not occur.
                return true;
            }
            return false;
        }
    } else if (element.attributes().size() == 1 && element.attribute("id") != null) {
        // Element has only id attribute and is not a predecessor definition for tasks outside the current Gantt object tree.
        return true;
    }
    return false;
}

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

License:Open Source License

private void checkForIgnoredElements(final StringBuffer buf, final Element el) {
    if (processedElements.contains(el) == false) {
        buf.append("Ignored xml element: ").append(el.getPath()).append("\n");
    }//from w w  w .  j a  v a  2  s. co m
    @SuppressWarnings("rawtypes")
    final List attributes = el.attributes();
    if (attributes != null) {
        final Set<String> attributeSet = processedAttributes.get(el);
        for (final Object attr : attributes) {
            if (attributeSet == null || attributeSet.contains(((Attribute) attr).getName()) == false) {
                buf.append("Ignored xml attribute: ").append(((Attribute) attr).getPath()).append("\n");
            }
        }
    }
    @SuppressWarnings("rawtypes")
    final List children = el.elements();
    if (children != null) {
        for (final Object child : children) {
            checkForIgnoredElements(buf, (Element) child);
        }
    }
}

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

License:Open Source License

/**
 * Please note: Does not set the default values, this should be done by the class itself (when declaring the fields or in the
 * constructors)./*from   www .  j  ava  2s . c  o m*/
 * @param obj The object to assign the parameters parsed from the given xml element.
 * @param str
 */
public void read(final Object obj, final Element el) {
    if (el == null) {
        return;
    }
    final Field[] fields = BeanHelper.getAllDeclaredFields(obj.getClass());
    AccessibleObject.setAccessible(fields, true);
    for (final Object listObject : el.attributes()) {
        final Attribute attr = (Attribute) listObject;
        final String key = attr.getName();
        if (StringHelper.isIn(key, XmlObjectWriter.ATTR_ID, XmlObjectWriter.ATTR_REF_ID) == true) {
            // Do not try to find fields for o-id and ref-id.
            continue;
        }
        final String value = attr.getText();
        proceedElement(obj, fields, el, key, value, true);
    }
    for (final Object listObject : el.elements()) {
        final Element childElement = (Element) listObject;
        final String key = childElement.getName();
        proceedElement(obj, fields, childElement, key, null, false);
    }
    putProcessedElement(el);
}

From source file:org.saiku.plugin.PentahoDatasourceManager.java

License:Apache License

private void loadDatasourcesFromXml(String dataSources) {
    EntityResolver loader = new PentahoEntityResolver();
    Document doc = null;//w w  w.  j av a 2 s .  c o  m
    try {
        doc = XmlDom4JHelper.getDocFromFile(dataSources, loader);
        String modified = doc.asXML();
        doc = XmlDom4JHelper.getDocFromString(modified, loader);

        List<Node> nodes = doc.selectNodes("/DataSources/DataSource/Catalogs/Catalog"); //$NON-NLS-1$
        int nr = 0;
        for (Node node : nodes) {
            nr++;
            String name = "PentahoDs" + nr;
            Element e = (Element) node;
            List<Attribute> list = e.attributes();
            for (Attribute attribute : list) {
                String aname = attribute.getName();
                if ("name".equals(aname)) {
                    name = attribute.getStringValue();
                }
            }

            Node ds = node.selectSingleNode("DataSourceInfo");
            Node cat = node.selectSingleNode("Definition");
            String connectStr = ds.getStringValue();
            PropertyList pl = Util.parseConnectString(connectStr);
            String dynProcName = pl.get(RolapConnectionProperties.DynamicSchemaProcessor.name());
            if (StringUtils.isNotBlank(dynamicSchemaProcessor) && StringUtils.isBlank(dynProcName)) {
                pl.put(RolapConnectionProperties.DynamicSchemaProcessor.name(), dynamicSchemaProcessor);

            }
            LOG.debug("NAME: " + name + " DSINFO: " + pl.toString() + "  ###CATALOG: "
                    + (cat != null ? cat.getStringValue() : "NULL"));
            Properties props = new Properties();
            props.put("driver", "mondrian.olap4j.MondrianOlap4jDriver");
            props.put("location", "jdbc:mondrian:" + pl.toString() + ";Catalog=" + cat.getStringValue());
            if (saikuDatasourceProcessor != null) {
                props.put(ISaikuConnection.DATASOURCE_PROCESSORS, saikuDatasourceProcessor);
            }
            if (saikuConnectionProcessor != null) {
                props.put(ISaikuConnection.CONNECTION_PROCESSORS, saikuConnectionProcessor);
            }
            props.list(System.out);

            SaikuDatasource sd = new SaikuDatasource(name, SaikuDatasource.Type.OLAP, props);
            datasources.put(name, sd);

        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.error(e);
    }
    if (LOG.isDebugEnabled()) {
        if (doc == null) {
            LOG.debug("Original Document is null");
        } else {
            LOG.debug("Original Document:" + doc.asXML()); //$NON-NLS-1$
        }
    }

}

From source file:org.sipfoundry.sipxconfig.phone.polycom.PolycomXmlTestCase.java

License:Contributor Agreement License

protected void dumpXml(Element element, PrintStream out, String indent) {
    out.print(indent + "<" + element.getName());
    List<Attribute> attributes = element.attributes();
    for (Attribute attribute : attributes) {
        out.println(indent);/*ww w.j ava 2 s.  c o m*/
        out.print(XML_INDENT + indent + attribute.getName() + "=\"" + attribute.getText() + "\"");
    }

    // Note: Polycom XML elements have no text, only attributes and child elements.

    List<Element> children = element.elements();
    if (children.isEmpty()) {
        out.println("");
        out.println(indent + "/>");
    } else {
        out.println(">");
        for (Element child : children) {
            out.println(indent);
            dumpXml(child, out, indent + XML_INDENT + XML_INDENT);
        }
        out.println(indent + "</" + element.getName() + ">");
    }
}

From source file:org.sysmodb.ControlCharStrippingXMLWriter.java

License:BSD License

@Override
protected void writeAttributes(Element element) throws IOException {
    for (Object at : element.attributes()) {
        ((Attribute) at).setText(stripControlCharacters(((Attribute) at).getText()));
    }/*from w  w  w  .  j  ava 2s.  c  o m*/
    Attribute attribute = element.attribute("formula");
    if (attribute != null) {
        attribute.setText(stripControlCharacters(attribute.getText()));
    }
    if (element.getText() != null && element.getText().length() > 0) {
        element.setText(stripControlCharacters(element.getText()));
    }
    super.writeAttributes(element);
}