List of usage examples for org.dom4j.io XMLWriter close
public void close() throws IOException
From source file:org.pentaho.actionsequence.dom.ActionSequenceDocument.java
License:Open Source License
public String toString() { String string = null;//from w ww . j av a2s . com try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(document.getXMLEncoding()); StringWriter stringWriter = new StringWriter(); XMLWriter writer = new XMLWriter(stringWriter, format); // XMLWriter has a bug that is avoided if we reparse the document // prior to calling XMLWriter.write() writer.write(DocumentHelper.parseText(document.asXML())); writer.close(); Document tempDocument = DocumentHelper.parseText(stringWriter.toString()); string = tempDocument.getRootElement().asXML(); } catch (Exception e) { string = super.toString(); } return string; }
From source file:org.pentaho.agilebi.spoon.publish.PublisherHelper.java
License:Open Source License
private static String replaceAttributeValue(String aElement, String anAttribute, String aValue, String aFile) throws Exception { String originalValue = null;/* www . j ava2 s . c o m*/ if (aFile != null) { SAXReader reader = new SAXReader(); Document doc = reader.read(new File(aFile)); Element root = doc.getRootElement(); for (Iterator<Element> i = root.elementIterator(); i.hasNext();) { Element element = i.next(); if (element.getName().equals(aElement)) { Attribute attr = element.attribute(anAttribute); originalValue = attr.getValue(); attr.setValue(aValue); } } XMLWriter writer = new XMLWriter(new FileWriter(aFile)); writer.write(doc); writer.close(); } return originalValue; }
From source file:org.pentaho.di.trans.steps.rssoutput.RssOutput.java
License:Apache License
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (RssOutputMeta) smi;//ww w. j a v a2s . c om data = (RssOutputData) sdi; Object[] r = getRow(); // this also waits for a previous step to be finished. if (r == null) { // no more input to be expected... if (!first) { if (!meta.isCustomRss()) { // No more input..so write and close the file. WriteToFile(data.channeltitlevalue, data.channellinkvalue, data.channeldescriptionvalue, data.channelpubdatevalue, data.channelcopyrightvalue, data.channelimagelinkvalue, data.channelimagedescriptionvalue, data.channelimagelinkvalue, data.channelimageurlvalue, data.channellanguagevalue, data.channelauthorvalue); } else { // Write to document OutputFormat format = org.dom4j.io.OutputFormat.createPrettyPrint(); // Set encoding ... if (Utils.isEmpty(meta.getEncoding())) { format.setEncoding("iso-8859-1"); } else { format.setEncoding(meta.getEncoding()); } try { XMLWriter writer = new XMLWriter(new FileWriter(new File(data.filename)), format); writer.write(data.document); writer.close(); } catch (Exception e) { // Ignore errors } finally { data.document = null; } } } setOutputDone(); return false; } if (first) { first = false; data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = data.inputRowMeta.clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore); // Let's check for filename... if (meta.isFilenameInField()) { if (Utils.isEmpty(meta.getFileNameField())) { logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameFieldMissing")); setErrors(1); stopAll(); return false; } // get filename field index data.indexOfFieldfilename = data.inputRowMeta.indexOfValue(meta.getFileNameField()); if (data.indexOfFieldfilename < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getFileNameField())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getFileNameField())); } } else { data.filename = buildFilename(); } // Check if filename is empty.. if (Utils.isEmpty(data.filename)) { logError(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty")); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.FilenameEmpty")); } // Do we need to create parent folder ? if (meta.isCreateParentFolder()) { // Check for parent folder FileObject parentfolder = null; try { // Get parent folder parentfolder = KettleVFS.getFileObject(data.filename, getTransMeta()).getParent(); if (!parentfolder.exists()) { if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.ParentFolderExists", parentfolder.getName().toString())); } parentfolder.createFolder(); if (log.isDetailed()) { logDetailed(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder", parentfolder.getName().toString())); } } } catch (Exception e) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder", parentfolder.getName().toString())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.CanNotCreateParentFolder", parentfolder.getName().toString())); } finally { if (parentfolder != null) { try { parentfolder.close(); } catch (Exception ex) { /* Ignore */ } } } } if (!meta.isCustomRss()) { // Let's check for mandatory fields ... if (Utils.isEmpty(meta.getChannelTitle())) { logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelTitleMissing")); setErrors(1); stopAll(); return false; } if (Utils.isEmpty(meta.getChannelDescription())) { logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelDescription")); setErrors(1); stopAll(); return false; } if (Utils.isEmpty(meta.getChannelLink())) { logError(BaseMessages.getString(PKG, "RssOutput.Log.ChannelLink")); setErrors(1); stopAll(); return false; } // Let's take the index of channel title field ... data.indexOfFieldchanneltitle = data.inputRowMeta.indexOfValue(meta.getChannelTitle()); if (data.indexOfFieldchanneltitle < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle())); throw new KettleException( BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelTitle())); } data.channeltitlevalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneltitle); // Let's take the index of channel description field ... data.indexOfFieldchanneldescription = data.inputRowMeta.indexOfValue(meta.getChannelDescription()); if (data.indexOfFieldchanneldescription < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelDescription())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelDescription())); } data.channeldescriptionvalue = data.inputRowMeta.getString(r, data.indexOfFieldchanneldescription); // Let's take the index of channel link field ... data.indexOfFieldchannellink = data.inputRowMeta.indexOfValue(meta.getChannelLink()); if (data.indexOfFieldchannellink < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink())); throw new KettleException( BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLink())); } data.channellinkvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellink); if (!Utils.isEmpty(meta.getItemTitle())) { // Let's take the index of item title field ... data.indexOfFielditemtitle = data.inputRowMeta.indexOfValue(meta.getItemTitle()); if (data.indexOfFielditemtitle < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemTitle())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemTitle())); } } if (!Utils.isEmpty(meta.getItemDescription())) { // Let's take the index of item description field ... data.indexOfFielditemdescription = data.inputRowMeta.indexOfValue(meta.getItemDescription()); if (data.indexOfFielditemdescription < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemDescription())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemDescription())); } } if (meta.AddGeoRSS()) { if (Utils.isEmpty(meta.getGeoPointLong())) { throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLatEmpty")); } if (Utils.isEmpty(meta.getGeoPointLong())) { throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.GeoPointLongEmpty")); } // Let's take the index of item geopointX field ... data.indexOfFielditempointx = data.inputRowMeta.indexOfValue(meta.getGeoPointLat()); if (data.indexOfFielditempointx < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getGeoPointLat())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getGeoPointLat())); } // Let's take the index of item geopointY field ... data.indexOfFielditempointy = data.inputRowMeta.indexOfValue(meta.getGeoPointLong()); if (data.indexOfFielditempointy < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getGeoPointLong())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getGeoPointLong())); } } // It's time to check non empty fields ! // Channel PubDate field ... if (!Utils.isEmpty(meta.getChannelPubDate())) { data.indexOfFieldchannelpubdate = data.inputRowMeta.indexOfValue(meta.getChannelPubDate()); if (data.indexOfFieldchannelpubdate < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelPubDate())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelPubDate())); } data.channelpubdatevalue = data.inputRowMeta.getDate(r, data.indexOfFieldchannelpubdate); } // Channel Language field ... if (!Utils.isEmpty(meta.getChannelLanguage())) { data.indexOfFieldchannellanguage = data.inputRowMeta.indexOfValue(meta.getChannelLanguage()); if (data.indexOfFieldchannellanguage < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLanguage())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelLanguage())); } data.channellanguagevalue = data.inputRowMeta.getString(r, data.indexOfFieldchannellanguage); } // Channel Copyright field ... if (!Utils.isEmpty(meta.getChannelCopyright())) { data.indexOfFieldchannelcopyright = data.inputRowMeta.indexOfValue(meta.getChannelCopyright()); if (data.indexOfFieldchannelcopyright < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelCopyright())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelCopyright())); } data.channelcopyrightvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelcopyright); } // Channel Author field ... if (!Utils.isEmpty(meta.getChannelAuthor())) { data.indexOfFieldchannelauthor = data.inputRowMeta.indexOfValue(meta.getChannelAuthor()); if (data.indexOfFieldchannelauthor < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelAuthor())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelAuthor())); } data.channelauthorvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelauthor); } // Channel Image field ... if (meta.AddImage()) { // Channel image title if (!Utils.isEmpty(meta.getChannelImageTitle())) { data.indexOfFieldchannelimagetitle = data.inputRowMeta .indexOfValue(meta.getChannelImageTitle()); if (data.indexOfFieldchannelimagetitle < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageTitle())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageTitle())); } data.channelimagetitlevalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelimagetitle); } // Channel link title if (!Utils.isEmpty(meta.getChannelImageLink())) { data.indexOfFieldchannelimagelink = data.inputRowMeta .indexOfValue(meta.getChannelImageLink()); if (data.indexOfFieldchannelimagelink < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageLink())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageLink())); } data.channelimagelinkvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelimagelink); } // Channel url title if (!Utils.isEmpty(meta.getChannelImageUrl())) { data.indexOfFieldchannelimageurl = data.inputRowMeta .indexOfValue(meta.getChannelImageUrl()); if (data.indexOfFieldchannelimageurl < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageUrl())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageUrl())); } data.channelimageurlvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelimageurl); } // Channel description title if (!Utils.isEmpty(meta.getChannelImageDescription())) { data.indexOfFieldchannelimagedescription = data.inputRowMeta .indexOfValue(meta.getChannelImageDescription()); if (data.indexOfFieldchannelimagedescription < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageDescription())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getChannelImageDescription())); } data.channelimagedescriptionvalue = data.inputRowMeta.getString(r, data.indexOfFieldchannelimagedescription); } } // Item link field ... if (!Utils.isEmpty(meta.getItemLink())) { data.indexOfFielditemlink = data.inputRowMeta.indexOfValue(meta.getItemLink()); if (data.indexOfFielditemlink < 0) { // The field is unreachable ! logError( BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink())); throw new KettleException( BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemLink())); } } // Item pubdate field ... if (!Utils.isEmpty(meta.getItemPubDate())) { data.indexOfFielditempubdate = data.inputRowMeta.indexOfValue(meta.getItemPubDate()); if (data.indexOfFielditempubdate < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemPubDate())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemPubDate())); } } // Item author field ... if (!Utils.isEmpty(meta.getItemAuthor())) { data.indexOfFielditemauthor = data.inputRowMeta.indexOfValue(meta.getItemAuthor()); if (data.indexOfFielditemauthor < 0) { // The field is unreachable ! logError(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemAuthor())); throw new KettleException(BaseMessages.getString(PKG, "RssOutput.Log.ErrorFindingField", meta.getItemAuthor())); } } } else { // Custom RSS // Check Custom channel fields data.customchannels = new int[meta.getChannelCustomFields().length]; for (int i = 0; i < meta.getChannelCustomFields().length; i++) { data.customchannels[i] = data.inputRowMeta.indexOfValue(meta.getChannelCustomFields()[i]); if (data.customchannels[i] < 0) { // couldn't find field! throw new KettleStepException(BaseMessages.getString(PKG, "RssOutput.Exception.FieldRequired", meta.getChannelCustomFields()[i])); } } // Check Custom channel fields data.customitems = new int[meta.getItemCustomFields().length]; for (int i = 0; i < meta.getItemCustomFields().length; i++) { data.customitems[i] = data.inputRowMeta.indexOfValue(meta.getItemCustomFields()[i]); if (data.customitems[i] < 0) { // couldn't find field! throw new KettleStepException(BaseMessages.getString(PKG, "RssOutput.Exception.FieldRequired", meta.getItemCustomFields()[i])); } } // Prepare Output RSS Custom document data.document = DocumentHelper.createDocument(); data.rssElement = data.document.addElement("rss"); data.rssElement.addAttribute("version", "2.0"); // add namespaces here ... for (int i = 0; i < meta.getNameSpaces().length; i++) { data.rssElement.addNamespace(environmentSubstitute(meta.getNameSpacesTitle()[i]), environmentSubstitute(meta.getNameSpaces()[i])); } // Add channel data.channel = data.rssElement.addElement("channel"); // Set channel Only the first time ... for (int i = 0; i < data.customchannels.length; i++) { String channelname = environmentSubstitute(meta.getChannelCustomTags()[i]); String channelvalue = data.inputRowMeta.getString(r, data.customchannels[i]); if (log.isDetailed()) { logDetailed("outputting channel value <" + channelname + ">" + channelvalue + "<" + channelname + "/>"); } // add Channel Element channeltag = data.channel.addElement(channelname); channeltag.setText(channelvalue); } } } // end test first time // Let's get value for each item... if (!meta.isCustomRss()) { String itemtitlevalue = null; String itemauthorvalue = null; String itemlinkvalue = null; Date itemdatevalue = null; String itemdescvalue = null; String itemgeopointx = null; String itemgeopointy = null; if (data.indexOfFielditemtitle > -1) { itemtitlevalue = data.inputRowMeta.getString(r, data.indexOfFielditemtitle); } if (data.indexOfFielditemauthor > -1) { itemauthorvalue = data.inputRowMeta.getString(r, data.indexOfFielditemauthor); } if (data.indexOfFielditemlink > -1) { itemlinkvalue = data.inputRowMeta.getString(r, data.indexOfFielditemlink); } if (data.indexOfFielditempubdate > -1) { itemdatevalue = data.inputRowMeta.getDate(r, data.indexOfFielditempubdate); } if (data.indexOfFielditemdescription > -1) { itemdescvalue = data.inputRowMeta.getString(r, data.indexOfFielditemdescription); } if (data.indexOfFielditempointx > -1) { itemgeopointx = data.inputRowMeta.getString(r, data.indexOfFielditempointx); } if (data.indexOfFielditempointy > -1) { itemgeopointy = data.inputRowMeta.getString(r, data.indexOfFielditempointy); } // Now add entry .. if (!createEntry(itemauthorvalue, itemtitlevalue, itemlinkvalue, itemdatevalue, itemdescvalue, itemgeopointx, itemgeopointy)) { throw new KettleException("Error adding item to feed"); } } else { // Set item tag at each row received if (meta.isDisplayItem()) { data.itemtag = data.channel.addElement("item"); } for (int i = 0; i < data.customitems.length; i++) { // get item value and name String itemname = environmentSubstitute(meta.getItemCustomTags()[i]); String itemvalue = data.inputRowMeta.getString(r, data.customitems[i]); if (log.isDetailed()) { logDetailed("outputting item value <" + itemname + ">" + itemvalue + "<" + itemname + "/>"); } // add Item if (meta.isDisplayItem()) { Element itemtagsub = data.itemtag.addElement(itemname); itemtagsub.setText(itemvalue); } else { // display item at channel level Element temp = data.channel.addElement(itemname); temp.setText(itemvalue); } } } try { putRow(data.outputRowMeta, r); // in case we want it to go further... incrementLinesOutput(); if (checkFeedback(getLinesOutput())) { if (log.isDebug()) { logDebug(BaseMessages.getString(PKG, "RssOutput.Log.Linenr", "" + getLinesOutput())); } } } catch (KettleStepException e) { logError(BaseMessages.getString(PKG, "RssOutputMeta.Log.ErrorInStep") + e.getMessage()); setErrors(1); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } return true; }
From source file:org.pentaho.jfreereport.wizard.utility.report.ReportGenerationUtility.java
License:Open Source License
/** * NOTE: the templateDoc is the target of the merge. * /* w w w . java 2s.c o m*/ * @param templateDoc * @param generatedDoc * @param mergeStream */ public static void mergeTemplate(Document templateDoc, Document generatedDoc, OutputStream mergeStream) { try { // replace parser-config settings in templateDoc from generatedDoc Element templateReportNode = ((Element) templateDoc.selectSingleNode("/report")); //$NON-NLS-1$ Element generatedReportNode = ((Element) generatedDoc.selectSingleNode("/report")); //$NON-NLS-1$ // move attributes from generated to template // blow away existing attributes first List templateAttributes = templateReportNode.attributes(); for (int i = templateAttributes.size() - 1; i >= 0; i--) { Attribute attribute = (Attribute) templateAttributes.get(i); templateReportNode.remove(attribute); } // now move generated into template List generatedAttributes = generatedReportNode.attributes(); for (int i = generatedAttributes.size() - 1; i >= 0; i--) { Attribute attribute = (Attribute) generatedAttributes.get(i); generatedReportNode.remove(attribute); templateReportNode.add(attribute); } List templateParserConfigProps = templateReportNode.selectNodes("parser-config/*"); //$NON-NLS-1$ List generatedParserConfigProps = generatedReportNode.selectNodes("parser-config/*"); //$NON-NLS-1$ Element templateParserConfigElement = (Element) templateReportNode.selectSingleNode("parser-config"); //$NON-NLS-1$ Element generatedParserConfigElement = (Element) generatedReportNode.selectSingleNode("parser-config"); //$NON-NLS-1$ // replace any empty elements in the generated doc with the corresponding contents of the template doc for (int i = 0; i < generatedParserConfigProps.size(); i++) { Element generatedParserConfigProp = (Element) generatedParserConfigProps.get(i); Element templateParserConfigProp = (Element) templateParserConfigProps.get(i); String generatedText = generatedParserConfigProp.getText(); if (!StringUtils.isEmpty(generatedText)) { generatedParserConfigElement.remove(generatedParserConfigProp); templateParserConfigElement.remove(templateParserConfigProp); templateParserConfigElement.add(generatedParserConfigProp); } } // replace items section in templateDoc from generatedDoc if (templateReportNode.selectSingleNode("items") != null) { //$NON-NLS-1$ templateReportNode.remove(templateReportNode.selectSingleNode("items")); //$NON-NLS-1$ } Element itemsElement = (Element) generatedReportNode.selectSingleNode("items"); //$NON-NLS-1$ if (itemsElement != null) { generatedReportNode.remove(itemsElement); templateReportNode.add(itemsElement); } // GROUP MERGING List groups = templateReportNode.selectNodes("groups/*"); //$NON-NLS-1$ // if groups has no elements, then we're just going to straight copy // the groups from the generated version // this is a new requirement per Kurtis Cruzada if (ReportSpecUtility.getNumberOfGroupsInTemplate(templateDoc) == 0) { // replace groups section in templateDoc from generatedDoc if (templateReportNode.selectSingleNode("groups") != null) { //$NON-NLS-1$ templateReportNode.remove(templateReportNode.selectSingleNode("groups")); //$NON-NLS-1$ } // might not have a top level groups node, add it if (generatedReportNode.selectSingleNode("groups") == null) { //$NON-NLS-1$ generatedReportNode.addElement("groups"); //$NON-NLS-1$ } Element groupElement = (Element) generatedReportNode.selectSingleNode("groups"); //$NON-NLS-1$ if (groupElement != null) { generatedReportNode.remove(groupElement); templateReportNode.add(groupElement); } } else { // both sets of groups should be identical in number // each group based on index should correspond // for all group headers, append new content // for all group footers insert new content, push down old // both lists must have the same # of groups (this is a // requirement) List generatedGroups = generatedReportNode.selectNodes("groups/*"); //$NON-NLS-1$ for (int i = 0; i < groups.size(); i++) { Element templateGroup = (Element) groups.get(i); for (int j = i + 1; j < generatedGroups.size(); j++) { Element generatedGroup = (Element) generatedGroups.get(j); Element templateGroupHeader = (Element) templateGroup.selectSingleNode("groupheader"); //$NON-NLS-1$ Element generatedGroupHeader = (Element) generatedGroup.selectSingleNode("groupheader"); //$NON-NLS-1$ Element templateGroupFooter = (Element) templateGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$ Element generatedGroupFooter = (Element) generatedGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$ try { if (templateGroupHeader.attribute("pagebreak-before-print") != null) { //$NON-NLS-1$ templateGroupHeader.attribute("pagebreak-before-print").detach(); //$NON-NLS-1$ } templateGroupHeader.addAttribute("pagebreak-before-print", //$NON-NLS-1$ (generatedGroupHeader.attributeValue("pagebreak-before-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // e.printStackTrace(); } try { if (templateGroupHeader.attribute("pagebreak-after-print") != null) { //$NON-NLS-1$ templateGroupHeader.attribute("pagebreak-after-print").detach(); //$NON-NLS-1$ } templateGroupHeader.addAttribute("pagebreak-after-print", //$NON-NLS-1$ (generatedGroupHeader.attributeValue("pagebreak-after-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // e.printStackTrace(); } try { if (templateGroupFooter.attribute("pagebreak-before-print") != null) { //$NON-NLS-1$ templateGroupFooter.attribute("pagebreak-before-print").detach(); //$NON-NLS-1$ } templateGroupFooter.addAttribute("pagebreak-before-print", //$NON-NLS-1$ (generatedGroupFooter.attributeValue("pagebreak-before-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // e.printStackTrace(); } try { if (templateGroupFooter.attribute("pagebreak-after-print") != null) { //$NON-NLS-1$ templateGroupFooter.attribute("pagebreak-after-print").detach(); //$NON-NLS-1$ } templateGroupFooter.addAttribute("pagebreak-after-print", //$NON-NLS-1$ (generatedGroupFooter.attributeValue("pagebreak-after-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // e.printStackTrace(); } try { if (templateGroupHeader.attribute("repeat") != null) { //$NON-NLS-1$ templateGroupHeader.attribute("repeat").detach(); //$NON-NLS-1$ } templateGroupHeader.addAttribute("repeat", //$NON-NLS-1$ (generatedGroupHeader.attributeValue("repeat")) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } catch (Exception e) { // e.printStackTrace(); } } } if (groups != null) { Element innermostGroup = null; int innermostFieldsInGroup = 0; for (int i = 0; i < groups.size(); i++) { Element groupElement = (Element) groups.get(i); List fields = groupElement.selectNodes("fields/*"); //$NON-NLS-1$ if (fields != null && fields.size() > 0 && fields.size() > innermostFieldsInGroup) { innermostFieldsInGroup = fields.size(); innermostGroup = groupElement; } } Element generatedInnermostGroup = null; if (generatedGroups != null) { int generatedInnermostFieldsInGroup = 0; for (int i = 0; i < generatedGroups.size(); i++) { Element groupElement = (Element) generatedGroups.get(i); List fields = groupElement.selectNodes("fields/*"); //$NON-NLS-1$ if (fields != null && fields.size() > 0 && fields.size() > generatedInnermostFieldsInGroup) { generatedInnermostFieldsInGroup = fields.size(); generatedInnermostGroup = groupElement; } } } // at this point we have found the innermost group // this will be used for updating the group header/footer if (innermostGroup != null) { // handle headers: append header if header exists, else // create Element groupHeader = (Element) innermostGroup.selectSingleNode("groupheader"); //$NON-NLS-1$ if (groupHeader == null) { // direct header replacement with // generatedInnermostGroup header Element headerElement = (Element) generatedInnermostGroup .selectSingleNode("groupheader"); //$NON-NLS-1$ if (headerElement != null) { generatedInnermostGroup.remove(headerElement); innermostGroup.add(headerElement); } } else { // insertion: loop through elements of generated, // append to header List groupHeaderNodes = innermostGroup.selectNodes("groupheader/*"); //$NON-NLS-1$ List generatedGroupHeaderNodes = generatedInnermostGroup.selectNodes("groupheader/*"); //$NON-NLS-1$ Element generatedGroupHeader = (Element) generatedInnermostGroup .selectSingleNode("groupheader"); //$NON-NLS-1$ // fix up header/footer breaking for innermost group int y = 0; for (int i = 0; i < groupHeaderNodes.size(); i++) { Element element = (Element) groupHeaderNodes.get(i); try { y = Math.max(y, Integer.parseInt(element.attributeValue("y")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } try { y = Math.max(y, Integer.parseInt(element.attributeValue("y1")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } try { y = Math.max(y, Integer.parseInt(element.attributeValue("y2")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } } for (int i = 0; i < generatedGroupHeaderNodes.size(); i++) { Element element = (Element) generatedGroupHeaderNodes.get(i); generatedGroupHeader.remove(element); if (element.attribute("y") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y")); //$NON-NLS-1$ element.attribute("y").detach(); //$NON-NLS-1$ element.addAttribute("y", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } else if (element.attribute("y1") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y1")); //$NON-NLS-1$ element.attribute("y1").detach(); //$NON-NLS-1$ element.addAttribute("y1", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } else if (element.attribute("y2") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y2")); //$NON-NLS-1$ element.attribute("y2").detach(); //$NON-NLS-1$ element.addAttribute("y2", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } groupHeader.add(element); } } // handle footers: Element groupFooter = (Element) innermostGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$ if (groupFooter == null) { // direct footer replacement with // generatedInnermostGroup footer Element footerElement = (Element) generatedInnermostGroup .selectSingleNode("groupfooter"); //$NON-NLS-1$ if (footerElement != null) { generatedInnermostGroup.remove(footerElement); innermostGroup.add(footerElement); } } else { // insertion: loop through elements of generated, // inserting to // template footer top (remove existing, add new, // add existing back) List groupFooterNodes = groupFooter.selectNodes("*"); //$NON-NLS-1$ // remove existing for (int i = 0; i < groupFooterNodes.size(); i++) { groupFooter.remove((Element) groupFooterNodes.get(i)); } // add new List generatedGroupFooterNodes = generatedInnermostGroup.selectNodes("groupfooter/*"); //$NON-NLS-1$ Element generatedGroupFooter = (Element) generatedInnermostGroup .selectSingleNode("groupfooter"); //$NON-NLS-1$ int y = 0; for (int i = 0; i < generatedGroupFooterNodes.size(); i++) { Element element = (Element) generatedGroupFooterNodes.get(i); generatedGroupFooter.remove(element); groupFooter.add(element); try { y = Math.max(y, Integer.parseInt(element.attributeValue("y")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } try { y = Math.max(y, Integer.parseInt(element.attributeValue("y1")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } try { y = Math.max(y, Integer.parseInt(element.attributeValue("y2")) //$NON-NLS-1$ + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$ } catch (Exception e) { // NumberFormat exceptions, ignore } } // add existing back, pushed down for (int i = 0; i < groupFooterNodes.size(); i++) { Element element = (Element) groupFooterNodes.get(i); if (element.attribute("y") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y")); //$NON-NLS-1$ element.attribute("y").detach(); //$NON-NLS-1$ element.addAttribute("y", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } else if (element.attribute("y1") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y1")); //$NON-NLS-1$ element.attribute("y1").detach(); //$NON-NLS-1$ element.addAttribute("y1", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } else if (element.attribute("y2") != null) { //$NON-NLS-1$ int yValue = Integer.parseInt(element.attributeValue("y2")); //$NON-NLS-1$ element.attribute("y2").detach(); //$NON-NLS-1$ element.addAttribute("y2", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$ } groupFooter.add((Element) groupFooterNodes.get(i)); } } } } // need to merge 'dummy' group if we're doing grand totals for (int i = 0; i < generatedGroups.size(); i++) { Element generatedGroup = (Element) generatedGroups.get(i); if (generatedGroup.attributeValue(NAME_ATTRIBUTE_NAME).equals("dummy")) { //$NON-NLS-1$ for (int j = 0; j < groups.size(); j++) { Element group = (Element) groups.get(j); if (group.attributeValue(NAME_ATTRIBUTE_NAME).equals("dummy")) { //$NON-NLS-1$ Element groupsElement = (Element) templateReportNode.selectSingleNode("groups"); //$NON-NLS-1$ generatedGroup.detach(); group.detach(); groupsElement.add(generatedGroup); } } } } } // 'merge' functions section in templateDoc from generatedDoc Element functionsElement = (Element) templateReportNode.selectSingleNode("functions"); //$NON-NLS-1$ Element generatedFunctionsElement = (Element) generatedReportNode.selectSingleNode("functions"); //$NON-NLS-1$ if (generatedFunctionsElement != null) { List functionList = generatedFunctionsElement.selectNodes("function"); //$NON-NLS-1$ for (int i = 0; i < functionList.size(); i++) { Element functionElement = (Element) functionList.get(i); generatedFunctionsElement.remove(functionElement); functionsElement.add(functionElement); } } // 'merge' expression section in templateDoc from generatedDoc Element expressionsElement = (Element) templateReportNode.selectSingleNode("functions"); //$NON-NLS-1$ Element generatedExpressionsElement = (Element) generatedReportNode.selectSingleNode("functions"); //$NON-NLS-1$ if (generatedExpressionsElement != null) { List expressionsList = generatedExpressionsElement.selectNodes("expression"); //$NON-NLS-1$ for (int i = 0; i < expressionsList.size(); i++) { Element expressionElement = (Element) expressionsList.get(i); generatedExpressionsElement.remove(expressionElement); expressionsElement.add(expressionElement); } } // pump watermark if exists if (generatedReportNode.selectSingleNode("watermark") != null) { //$NON-NLS-1$ Element watermarkNode = (Element) generatedReportNode.selectSingleNode("watermark"); //$NON-NLS-1$ Element templateWatermarkNode = (Element) templateReportNode.selectSingleNode("watermark"); //$NON-NLS-1$ if (templateWatermarkNode != null) { templateWatermarkNode.detach(); } if (watermarkNode != null) { watermarkNode.detach(); } templateReportNode.add(watermarkNode); } // push generatedDoc changes into templateDoc and write result to // mergeStream OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(mergeStream, format); writer.write(templateDoc); writer.close(); } catch (Exception e) { getLogger().error(e.getMessage(), e); } }
From source file:org.pentaho.jfreereport.wizard.utility.report.ReportGenerationUtility.java
License:Open Source License
/** * From the report description in the <param>reportSpec</param> parameter, create * a JFree Report report definition in XML format, and return the XML via * the <param>outputStream</param> parameter. * /*w ww. j a v a 2s. c o m*/ * @param reportSpec * @param outputStream * @param encoding * @param pageWidth * @param pageHeight * @param createTotalColumn * @param totalColumnName * @param totalColumnWidth * @param spacerWidth */ public static void createJFreeReportXML(ReportSpec reportSpec, OutputStream outputStream, String encoding, int pageWidth, int pageHeight, boolean createTotalColumn, String totalColumnName, int totalColumnWidth, int spacerWidth) { Field fields[] = reportSpec.getField(); Field details[] = ReportSpecUtility.getDetails(fields); Field groups[] = ReportSpecUtility.getGroups(fields); List spaceFields = setupSpaceFields(fields); try { boolean expressionExists = ReportSpecUtility.doesExpressionExist(fields); setupDetailFieldWidths(reportSpec, details); int itemRowHeight = ReportSpecUtility.getRowHeight(reportSpec, details); // dom4j Document document = DOMDocumentFactory.getInstance().createDocument(); document.addDocType("report", "-//JFreeReport//DTD report definition//EN//simple/version 0.8.5", //$NON-NLS-1$//$NON-NLS-2$ "http://jfreereport.sourceforge.net/report-085.dtd"); //$NON-NLS-1$ org.dom4j.Element reportNode = document.addElement("report"); //$NON-NLS-1$ Element configuration = reportNode.addElement(CONFIGURATION_ELEMENT_NAME); if (null != encoding) { document.setXMLEncoding(encoding); addEncoding(configuration, encoding); } // reportNode.addAttribute("xmlns", "http://jfreereport.sourceforge.net/namespaces/reports/legacy/simple"); // add parser-config to generated report addParserConfig(reportSpec, reportNode); // set report name reportNode.addAttribute(NAME_ATTRIBUTE_NAME, StringEscapeUtils.escapeXml(reportSpec.getReportName())); // set orientation reportNode.addAttribute("orientation", reportSpec.getOrientation()); //$NON-NLS-1$ // set page-format or page width/height setPageFormat(reportSpec, reportNode, pageWidth, pageHeight); // set margins setMargins(reportSpec, reportNode); if (reportSpec.getIncludeSrc() != null && !"".equalsIgnoreCase(reportSpec.getIncludeSrc())) { //$NON-NLS-1$ org.dom4j.Element includeElement = reportNode.addElement("include"); //$NON-NLS-1$ includeElement.addAttribute("src", "file://" + reportSpec.getIncludeSrc().replace('\\', '/')); //$NON-NLS-1$ //$NON-NLS-2$ } // set watermark setWatermark(reportSpec, reportNode); Element groupsNode = reportNode.addElement("groups"); //$NON-NLS-1$ Element itemsNode = reportNode.addElement("items"); //$NON-NLS-1$ Element functionNode = reportNode.addElement("functions"); //$NON-NLS-1$ if (reportSpec.getChart() != null && reportSpec.getUseChart()) { Element reportHeaderElement = reportNode.addElement("reportheader"); //$NON-NLS-1$ addChartElement(reportSpec, null, functionNode, reportHeaderElement, 0); } setItemsFont(reportSpec, itemsNode); // create banding rectangle if banding is turned on createRowBanding(reportSpec, details, itemsNode, functionNode, itemRowHeight); // programatically create details section processDetailsSection(reportSpec, details, groups, itemsNode, functionNode, itemRowHeight); // programatically create groups section processGroupsSection(reportSpec, details, groups, groupsNode, functionNode, itemRowHeight, expressionExists, spacerWidth); // spit out report xml definition OutputFormat format = OutputFormat.createPrettyPrint(); if (null != encoding) { format.setEncoding(encoding); // TODO sbarkull, not sure this is necessary } XMLWriter writer = new XMLWriter(outputStream, format); writer.write(document); writer.close(); // put _SPACE_ fields back in place as they were for (int i = 0; i < spaceFields.size(); i++) { Field f = (Field) spaceFields.get(i); f.setName("_SPACE_" + (i + 1)); //$NON-NLS-1$ f.setDisplayName("_SPACE_" + (i + 1)); //$NON-NLS-1$ } } catch (Exception e) { getLogger().error(e.getMessage(), e); } }
From source file:org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper.java
License:Open Source License
@Deprecated protected synchronized void writeDataSources(DataSources dataSources) { File dataSourcesFile;//from w w w. ja v a2s . c o m try { dataSourcesFile = new File(new URL(dataSourcesConfig).getFile()); // dataSourcesConfigResource.getFile(); } catch (IOException e) { throw new MondrianCatalogServiceException(Messages.getInstance() .getErrorString("MondrianCatalogHelper.ERROR_0005_RESOURCE_NOT_AVAILABLE"), e, Reason.GENERAL); //$NON-NLS-1$ } Writer sxml; try { sxml = new FileWriter(dataSourcesFile); } catch (IOException e) { throw new MondrianCatalogServiceException(e); } StringWriter sw = new StringWriter(); XMLOutput pxml = new XMLOutput(sw); pxml.print("<?xml version=\"1.0\"?>\n"); //$NON-NLS-1$ dataSources.displayXML(pxml, 0); Document doc = null; try { doc = XmlDom4JHelper.getDocFromString(sw.toString(), new PentahoEntityResolver()); } catch (XmlParseException e) { throw new MondrianCatalogServiceException(e); } // pretty print try { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(doc.getXMLEncoding()); XMLWriter writer = new XMLWriter(sxml, format); writer.write(doc); writer.close(); // CleanXmlHelper.saveDomToWriter(doc, sxml); } catch (IOException e) { throw new MondrianCatalogServiceException(e); } IOUtils.closeQuietly(sxml); }
From source file:org.pentaho.platform.plugin.adhoc.AdhocContentGenerator.java
License:Open Source License
/** * Create the JFreeReport file./*from w w w .j a va2s.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 repository * @param userSession * @return * @throws IOException * @throws AdhocWebServiceException * @throws PentahoMetadataException */ public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode, IPentahoSession userSession, OutputStream jfreeMergedOutputStream) throws IOException, AdhocWebServiceException, PentahoMetadataException { Map reportSpecTypeToElement = null; Document templateDoc = null; Element templateItems = null; boolean bUseTemplate = !StringUtils.isEmpty(templatePath); if (bUseTemplate) { templatePath = AdhocContentGenerator.WAQR_REPOSITORY_PATH + templatePath; try { org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); reader.setEntityResolver(new SolutionURIResolver()); templateDoc = reader .read(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale())); } catch (Throwable t) { // XML document can't be read. We'll just return a null document. } templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$ List nodes = templateItems.elements(); Iterator it = nodes.iterator(); reportSpecTypeToElement = new HashMap(); while (it.hasNext()) { Element element = (Element) it.next(); reportSpecTypeToElement.put(element.getName(), element); } } // get the business model from the mql statement String xml = mqlNode.asXML(); // first see if it's a thin model... QueryXmlHelper helper = new QueryXmlHelper(); IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null); Query queryObject = null; try { queryObject = helper.fromXML(repo, xml); } catch (Exception e) { String msg = Messages.getInstance() .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$ error(msg, e); throw new AdhocWebServiceException(msg, e); } LogicalModel model = null; if (queryObject != null) { model = queryObject.getLogicalModel(); } if (model == null) { throw new AdhocWebServiceException( Messages.getInstance().getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$ } String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(), queryObject.getDomain().getLocaleCodes()); String reportXMLEncoding = XmlHelper.getEncoding(reportXML); ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream( reportXML.getBytes(reportXMLEncoding)); ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream, ReportSpec.class, reportXMLEncoding); if (reportSpec == null) { throw new AdhocWebServiceException( Messages.getInstance().getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$ } // ========== begin column width stuff // make copies of the business columns; in the next step we're going to fill out any missing column widths LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length]; for (int i = 0; i < reportSpec.getField().length; i++) { Field field = reportSpec.getField()[i]; String name = field.getName(); LogicalColumn column = model.findLogicalColumn(name); columns[i] = (LogicalColumn) column.clone(); } boolean columnWidthUnitsConsistent = AdhocContentGenerator.areMetadataColumnUnitsConsistent(reportSpec, model); if (!columnWidthUnitsConsistent) { logger.error(Messages.getInstance() .getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$ } else { double columnWidthScaleFactor = 1.0; int missingColumnWidthCount = 0; int columnWidthSumOfPercents; double defaultWidth; columnWidthSumOfPercents = AdhocContentGenerator.getSumOfMetadataColumnWidths(reportSpec, model); missingColumnWidthCount = AdhocContentGenerator.getMissingColumnWidthCount(reportSpec, model); // if there are columns with no column width specified, figure out what percent we should use for them if (missingColumnWidthCount > 0) { if (columnWidthSumOfPercents < 100) { int remainingPercent = 100 - columnWidthSumOfPercents; defaultWidth = remainingPercent / missingColumnWidthCount; columnWidthSumOfPercents = 100; } else { defaultWidth = 10; columnWidthSumOfPercents += (missingColumnWidthCount * 10); } // fill in columns without column widths for (int i = 0; i < columns.length; i++) { ColumnWidth property = (ColumnWidth) columns[i] .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId()); if (property == null) { property = new ColumnWidth(WidthType.PERCENT, defaultWidth); columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property); } } } if (columnWidthSumOfPercents > 100) { columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents; } // now scale down if necessary if (columnWidthScaleFactor < 1.0) { for (int i = 0; i < columns.length; i++) { ColumnWidth property = (ColumnWidth) columns[i] .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId()); ColumnWidth newProperty = new ColumnWidth(property.getType(), columnWidthScaleFactor * property.getWidth()); columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty); } } } // ========== end column width stuff for (int i = 0; i < reportSpec.getField().length; i++) { Field field = reportSpec.getField()[i]; LogicalColumn column = columns[i]; applyMetadata(field, column, columnWidthUnitsConsistent, locale); // Template properties have the lowest priority, merge them last if (bUseTemplate) { Element templateDefaults = null; if (column.getDataType() != null) { templateDefaults = (Element) reportSpecTypeToElement .get(AdhocContentGenerator.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell } /* * NOTE: this merge of the template with the node's properties only sets the following properties: * format, fontname, fontsize, color, alignment, vertical-alignment, */ AdhocContentGenerator.applyTemplate(field, templateDefaults); } AdhocContentGenerator.applyDefaults(field); } // end for /* * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it, * and some of the template. */ ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream(); ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding, (OutputStream) jfreeOutputStream); String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding); Document generatedJFreeDoc = null; try { generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, new PentahoEntityResolver()); } catch (XmlParseException e) { String msg = Messages.getInstance() .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$ error(msg, e); throw new AdhocWebServiceException(msg, e); } /* * Merge template's /report/items element's attributes into the * generated document's /report/items element's attributes. There should not be any * conflict with the metadata, or the xreportspec in the reportXML param */ if (bUseTemplate) { Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$ List templateAttrs = templateItems.attributes(); // from the template's /report/items element Iterator templateAttrsIt = templateAttrs.iterator(); while (templateAttrsIt.hasNext()) { Attribute attr = (Attribute) templateAttrsIt.next(); String name = attr.getName(); String value = attr.getText(); Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$ if (node != null) { node.setText(value); } else { reportItems.addAttribute(name, value); } } List templateElements = templateItems.elements(); Iterator templateElementsIt = templateElements.iterator(); while (templateElementsIt.hasNext()) { Element element = (Element) templateElementsIt.next(); element.detach(); reportItems.add(element); } /* * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate()) * with the generated document can wait until last because none of the * properties involved in this merge are settable by the metadata or the WAQR UI */ ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream); } else { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(reportXMLEncoding); XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format); writer.write(generatedJFreeDoc); writer.close(); } }
From source file:org.pentaho.platform.plugin.adhoc.AdhocContentGenerator.java
License:Open Source License
public void createMQLQueryActionSequence(final String domainId, final String modelId, final String tableId, final String columnId, final String searchStr, final OutputStream outputStream, final String userSessionName) throws IOException { Document document = DOMDocumentFactory.getInstance().createDocument(); document.setXMLEncoding(LocaleHelper.getSystemEncoding()); Element actionSeqElement = document.addElement("action-sequence"); //$NON-NLS-1$ actionSeqElement.addElement("version").setText("1"); //$NON-NLS-1$ //$NON-NLS-2$ actionSeqElement.addElement("title").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$ actionSeqElement.addElement("logging-level").setText("ERROR"); //$NON-NLS-1$ //$NON-NLS-2$ Element documentationElement = actionSeqElement.addElement("documentation"); //$NON-NLS-1$ Element authorElement = documentationElement.addElement("author"); //$NON-NLS-1$ if (userSessionName != null) { authorElement.setText(userSessionName); } else {// w w w . ja va2 s . c om authorElement.setText("Web Query & Reporting"); //$NON-NLS-1$ } documentationElement.addElement("description") //$NON-NLS-1$ .setText("Temporary action sequence used by Web Query & Reporting"); //$NON-NLS-1$ documentationElement.addElement("result-type").setText("result-set"); //$NON-NLS-1$ //$NON-NLS-2$ Element outputsElement = actionSeqElement.addElement("outputs"); //$NON-NLS-1$ Element reportTypeElement = outputsElement.addElement("query_result"); //$NON-NLS-1$ reportTypeElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$ Element destinationsElement = reportTypeElement.addElement("destinations"); //$NON-NLS-1$ destinationsElement.addElement("response").setText("query_result"); //$NON-NLS-1$ //$NON-NLS-2$ Element actionsElement = actionSeqElement.addElement("actions"); //$NON-NLS-1$ Element actionDefinitionElement = actionsElement.addElement("action-definition"); //$NON-NLS-1$ Element actionOutputsElement = actionDefinitionElement.addElement("action-outputs"); //$NON-NLS-1$ Element ruleResultElement = actionOutputsElement.addElement("query-result"); //$NON-NLS-1$ ruleResultElement.addAttribute("type", "result-set"); //$NON-NLS-1$ //$NON-NLS-2$ ruleResultElement.addAttribute("mapping", "query_result"); //$NON-NLS-1$ //$NON-NLS-2$ actionDefinitionElement.addElement("component-name").setText("MQLRelationalDataComponent"); //$NON-NLS-1$ //$NON-NLS-2$ actionDefinitionElement.addElement("action-type").setText("MQL Query"); //$NON-NLS-1$ //$NON-NLS-2$ Element componentDefinitionElement = actionDefinitionElement.addElement("component-definition"); //$NON-NLS-1$ // log SQL flag if ("true".equals(PentahoSystem.getSystemSetting("adhoc-preview-log-sql", "false"))) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ componentDefinitionElement.addElement("logSql").addCDATA("true"); //$NON-NLS-1$ //$NON-NLS-2$ } // componentDefinitionElement.addElement("query").addCDATA(createMQLQueryXml(domainId, modelId, tableId, columnId, searchStr)); //$NON-NLS-1$ addMQLQueryXml(componentDefinitionElement, domainId, modelId, tableId, columnId, searchStr); // end action-definition for JFreeReportComponent OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(LocaleHelper.getSystemEncoding()); XMLWriter writer = new XMLWriter(outputStream, format); writer.write(document); writer.close(); }
From source file:org.pentaho.platform.plugin.adhoc.AdhocContentGenerator.java
License:Open Source License
protected ByteArrayOutputStream exportDocumentAsByteArrayOutputStream(Document document) throws IOException { ByteArrayOutputStream xactionOutputStream = new ByteArrayOutputStream(); // end action-definition for JFreeReportComponent OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(LocaleHelper.getSystemEncoding()); XMLWriter writer = new XMLWriter(xactionOutputStream, format); writer.write(document);/*from w w w . j a v a2 s . c o m*/ writer.close(); return xactionOutputStream; }
From source file:org.pentaho.platform.plugin.adhoc.AdhocWebService.java
License:Open Source License
/** * Create the JFreeReport file.//from www . j a v a2 s .co m * * NOTE on the merge precedence: this method should use properties set by the * WAQR UI. If the waqr UI did not set the property, then the property * should be set by the metadata. If the metadata did not set a property, * then the property should be set by the template. If the template * did not set the property, then use the default. * * NOTE on the merge algorithm: * For each of the attributes in the fields (aka columns) of the reportspec, * if the attribute is present in the reportspec that comes in from the client * (ie reportXML param), and the attribute has a non-default value, do not change it. * If the attribute is not present or has a default value, and if there is metadata * for that attribute, merge the metadata attribute. This take place inline in the * main loop of this method. If after the metadata merge the attribute * still does not have a value, merge the template value. This takes place * in the AdhocWebService.applyTemplate() method. * If the template does not have a value, do nothing (the default will be used). * * @param reportDoc * @param reportXML * @param templatePath * @param mqlNode * @param userSession * @return * @throws IOException * @throws AdhocWebServiceException * @throws PentahoMetadataException */ public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode, IPentahoSession userSession, OutputStream jfreeMergedOutputStream) throws IOException, AdhocWebServiceException, PentahoMetadataException { Map reportSpecTypeToElement = null; Document templateDoc = null; Element templateItems = null; boolean bUseTemplate = !StringUtils.isEmpty(templatePath); if (bUseTemplate) { templatePath = AdhocWebService.WAQR_REPOSITORY_PATH + templatePath; try { org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader(); reader.setEntityResolver(new SolutionURIResolver()); templateDoc = reader .read(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale())); } catch (Throwable t) { // XML document can't be read. We'll just return a null document. } templateItems = (Element) templateDoc.selectSingleNode("/report/items"); //$NON-NLS-1$ List nodes = templateItems.elements(); Iterator it = nodes.iterator(); reportSpecTypeToElement = new HashMap(); while (it.hasNext()) { Element element = (Element) it.next(); reportSpecTypeToElement.put(element.getName(), element); } } // get the business model from the mql statement String xml = mqlNode.asXML(); // first see if it's a thin model... QueryXmlHelper helper = new QueryXmlHelper(); IMetadataDomainRepository repo = PentahoSystem.get(IMetadataDomainRepository.class, null); Query queryObject = null; try { queryObject = helper.fromXML(repo, xml); } catch (Exception e) { String msg = Messages.getInstance() .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$ error(msg, e); throw new AdhocWebServiceException(msg, e); } LogicalModel model = null; if (queryObject != null) { model = queryObject.getLogicalModel(); } if (model == null) { throw new AdhocWebServiceException( Messages.getInstance().getErrorString("AdhocWebService.ERROR_0003_BUSINESS_VIEW_INVALID")); //$NON-NLS-1$ } String locale = LocaleHelper.getClosestLocale(LocaleHelper.getLocale().toString(), queryObject.getDomain().getLocaleCodes()); String reportXMLEncoding = XmlHelper.getEncoding(reportXML); ByteArrayInputStream reportSpecInputStream = new ByteArrayInputStream( reportXML.getBytes(reportXMLEncoding)); ReportSpec reportSpec = (ReportSpec) CastorUtility.getInstance().readCastorObject(reportSpecInputStream, ReportSpec.class, reportXMLEncoding); if (reportSpec == null) { throw new AdhocWebServiceException( Messages.getInstance().getErrorString("AdhocWebService.ERROR_0002_REPORT_INVALID")); //$NON-NLS-1$ } // ========== begin column width stuff // make copies of the business columns; in the next step we're going to fill out any missing column widths LogicalColumn[] columns = new LogicalColumn[reportSpec.getField().length]; for (int i = 0; i < reportSpec.getField().length; i++) { Field field = reportSpec.getField()[i]; String name = field.getName(); LogicalColumn column = model.findLogicalColumn(name); columns[i] = (LogicalColumn) column.clone(); } boolean columnWidthUnitsConsistent = AdhocWebService.areMetadataColumnUnitsConsistent(reportSpec, model); if (!columnWidthUnitsConsistent) { logger.error(Messages.getInstance() .getErrorString("AdhocWebService.ERROR_0013_INCONSISTENT_COLUMN_WIDTH_UNITS")); //$NON-NLS-1$ } else { double columnWidthScaleFactor = 1.0; int missingColumnWidthCount = 0; int columnWidthSumOfPercents; double defaultWidth; columnWidthSumOfPercents = AdhocWebService.getSumOfMetadataColumnWidths(reportSpec, model); missingColumnWidthCount = AdhocWebService.getMissingColumnWidthCount(reportSpec, model); // if there are columns with no column width specified, figure out what percent we should use for them if (missingColumnWidthCount > 0) { if (columnWidthSumOfPercents < 100) { int remainingPercent = 100 - columnWidthSumOfPercents; defaultWidth = remainingPercent / missingColumnWidthCount; columnWidthSumOfPercents = 100; } else { defaultWidth = 10; columnWidthSumOfPercents += (missingColumnWidthCount * 10); } // fill in columns without column widths for (int i = 0; i < columns.length; i++) { ColumnWidth property = (ColumnWidth) columns[i] .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId()); if (property == null) { property = new ColumnWidth(WidthType.PERCENT, defaultWidth); columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), property); } } } if (columnWidthSumOfPercents > 100) { columnWidthScaleFactor = 100.0 / (double) columnWidthSumOfPercents; } // now scale down if necessary if (columnWidthScaleFactor < 1.0) { for (int i = 0; i < columns.length; i++) { ColumnWidth property = (ColumnWidth) columns[i] .getProperty(DefaultPropertyID.COLUMN_WIDTH.getId()); ColumnWidth newProperty = new ColumnWidth(property.getType(), columnWidthScaleFactor * property.getWidth()); columns[i].setProperty(DefaultPropertyID.COLUMN_WIDTH.getId(), newProperty); } } } // ========== end column width stuff for (int i = 0; i < reportSpec.getField().length; i++) { Field field = reportSpec.getField()[i]; LogicalColumn column = columns[i]; applyMetadata(field, column, columnWidthUnitsConsistent, locale); // Template properties have the lowest priority, merge them last if (bUseTemplate) { Element templateDefaults = null; if (column.getDataType() != null) { templateDefaults = (Element) reportSpecTypeToElement .get(AdhocWebService.METADATA_TYPE_TO_REPORT_SPEC_TYPE.get(column.getDataType())); // sorry, this is ugly as hell } /* * NOTE: this merge of the template with the node's properties only sets the following properties: * format, fontname, fontsize, color, alignment, vertical-alignment, */ AdhocWebService.applyTemplate(field, templateDefaults); } AdhocWebService.applyDefaults(field); } // end for /* * Create the xml document (generatedJFreeDoc) containing the jfreereport definition using * the reportSpec as input. generatedJFreeDoc will have the metadata merged with it, * and some of the template. */ ByteArrayOutputStream jfreeOutputStream = new ByteArrayOutputStream(); ReportGenerationUtility.createJFreeReportXMLAsStream(reportSpec, reportXMLEncoding, (OutputStream) jfreeOutputStream); String jfreeXml = jfreeOutputStream.toString(reportXMLEncoding); Document generatedJFreeDoc = null; try { generatedJFreeDoc = XmlDom4JHelper.getDocFromString(jfreeXml, new PentahoEntityResolver()); } catch (XmlParseException e) { String msg = Messages.getInstance() .getErrorString("HttpWebService.ERROR_0001_ERROR_DURING_WEB_SERVICE"); //$NON-NLS-1$ error(msg, e); throw new AdhocWebServiceException(msg, e); } /* * Merge template's /report/items element's attributes into the * generated document's /report/items element's attributes. There should not be any * conflict with the metadata, or the xreportspec in the reportXML param */ if (bUseTemplate) { Element reportItems = (Element) generatedJFreeDoc.selectSingleNode("/report/items"); //$NON-NLS-1$ List templateAttrs = templateItems.attributes(); // from the template's /report/items element Iterator templateAttrsIt = templateAttrs.iterator(); while (templateAttrsIt.hasNext()) { Attribute attr = (Attribute) templateAttrsIt.next(); String name = attr.getName(); String value = attr.getText(); Node node = reportItems.selectSingleNode("@" + name); //$NON-NLS-1$ if (node != null) { node.setText(value); } else { reportItems.addAttribute(name, value); } } List templateElements = templateItems.elements(); Iterator templateElementsIt = templateElements.iterator(); while (templateElementsIt.hasNext()) { Element element = (Element) templateElementsIt.next(); element.detach(); reportItems.add(element); } /* * NOTE: this merging of the template (ReportGenerationUtility.mergeTemplate()) * with the generated document can wait until last because none of the * properties involved in this merge are settable by the metadata or the WAQR UI */ ReportGenerationUtility.mergeTemplateAsStream(templateDoc, generatedJFreeDoc, jfreeMergedOutputStream); } else { OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding(reportXMLEncoding); XMLWriter writer = new XMLWriter(jfreeMergedOutputStream, format); writer.write(generatedJFreeDoc); writer.close(); } }