List of usage examples for org.dom4j.io OutputFormat setEncoding
public void setEncoding(String encoding)
From source file:org.pentaho.platform.web.http.api.resources.XactionUtil.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) public static String executeXml(RepositoryFile file, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, IPentahoSession userSession) throws Exception { try {/*w w w. j a v a 2 s .c o m*/ HttpSessionParameterProvider sessionParameters = new HttpSessionParameterProvider(userSession); HttpRequestParameterProvider requestParameters = new HttpRequestParameterProvider(httpServletRequest); Map parameterProviders = new HashMap(); parameterProviders.put("request", requestParameters); //$NON-NLS-1$ parameterProviders.put("session", sessionParameters); //$NON-NLS-1$ List messages = new ArrayList(); IParameterProvider requestParams = new HttpRequestParameterProvider(httpServletRequest); httpServletResponse.setContentType("text/xml"); //$NON-NLS-1$ httpServletResponse.setCharacterEncoding(LocaleHelper.getSystemEncoding()); boolean forcePrompt = "true".equalsIgnoreCase(requestParams.getStringParameter("prompt", "false")); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ OutputStream contentStream = new ByteArrayOutputStream(); SimpleOutputHandler outputHandler = new SimpleOutputHandler(contentStream, false); IRuntimeContext runtime = null; try { runtime = executeInternal(file, requestParams, httpServletRequest, outputHandler, parameterProviders, userSession, forcePrompt, messages); Document responseDoc = SoapHelper.createSoapResponseDocument(runtime, outputHandler, contentStream, messages); OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); format.setEncoding("utf-8"); //$NON-NLS-1$ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(outputStream, format); writer.write(responseDoc); writer.flush(); return outputStream.toString("utf-8"); //$NON-NLS-1$ } finally { if (runtime != null) { runtime.dispose(); } } } catch (Exception e) { logger.warn(Messages.getInstance().getString("XactionUtil.XML_OUTPUT_NOT_SUPPORTED")); //$NON-NLS-1$ throw e; } }
From source file:org.pentaho.platform.web.http.api.resources.XactionUtil.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) public static String doParameter(final RepositoryFile file, IParameterProvider parameterProvider, final IPentahoSession userSession) throws IOException { ActionSequenceJCRHelper helper = new ActionSequenceJCRHelper(); final IActionSequence actionSequence = helper.getActionSequence(file.getPath(), PentahoSystem.loggingLevel, RepositoryFilePermission.READ); final Document document = DocumentHelper.createDocument(); try {// w w w . j a v a2s . c o m final Element parametersElement = document.addElement("parameters"); // noinspection unchecked final Map<String, IActionParameter> params = actionSequence .getInputDefinitionsForParameterProvider(IParameterProvider.SCOPE_REQUEST); for (final Map.Entry<String, IActionParameter> entry : params.entrySet()) { final String paramName = entry.getKey(); final IActionParameter paramDef = entry.getValue(); final String value = paramDef.getStringValue(); final Class type; // yes, the actual type-code uses equals-ignore-case and thus allows the user // to specify type information in a random case. sTrInG is equal to STRING is equal to the value // defined as constant (string) if (IActionParameter.TYPE_LIST.equalsIgnoreCase(paramDef.getType())) { type = String[].class; } else { type = String.class; } final String label = paramDef.getSelectionDisplayName(); final String[] values; if (StringUtils.isEmpty(value)) { values = new String[0]; } else { values = new String[] { value }; } createParameterElement(parametersElement, paramName, type, label, "user", "parameters", values); } createParameterElement(parametersElement, "path", String.class, null, "system", "system", new String[] { file.getPath() }); createParameterElement(parametersElement, "prompt", String.class, null, "system", "system", new String[] { "yes", "no" }); createParameterElement(parametersElement, "instance-id", String.class, null, "system", "system", new String[] { parameterProvider.getStringParameter("instance-id", null) }); // no close, as far as I know tomcat does not like it that much .. OutputFormat format = OutputFormat.createCompactFormat(); format.setSuppressDeclaration(true); format.setEncoding("utf-8"); //$NON-NLS-1$ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); XMLWriter writer = new XMLWriter(outputStream, format); writer.write(document); writer.flush(); return outputStream.toString("utf-8"); } catch (Exception e) { logger.warn(Messages.getInstance().getString("HttpWebService.ERROR_0003_UNEXPECTED"), e); return null; } }
From source file:org.pentaho.platform.web.servlet.AdhocWebService.java
License:Open Source License
/** * Create the JFreeReport file.//from w ww.j a va 2 s . c o m * * NOTE on the merge precedence: this method should use properties set by the * WAQR UI. If the waqr UI did not set the property, then the property * should be set by the metadata. If the metadata did not set a property, * then the property should be set by the template. If the template * did not set the property, then use the default. * * NOTE on the merge algorithm: * For each of the attributes in the fields (aka columns) of the reportspec, * if the attribute is present in the reportspec that comes in from the client * (ie reportXML param), and the attribute has a non-default value, do not change it. * If the attribute is not present or has a default value, and if there is metadata * for that attribute, merge the metadata attribute. This take place inline in the * main loop of this method. If after the metadata merge the attribute * still does not have a value, merge the template value. This takes place * in the AdhocWebService.applyTemplate() method. * If the template does not have a value, do nothing (the default will be used). * * @param reportDoc * @param reportXML * @param templatePath * @param mqlNode * @param repository * @param userSession * @return * @throws IOException * @throws AdhocWebServiceException * @throws PentahoMetadataException */ public void createJFreeReportDefinitionAsStream(String reportXML, String templatePath, Element mqlNode, 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.pms.ui.QueryBuilderDialog.java
License:Open Source License
public Document prettyPrint(Document document) { try {//from ww w . ja va2s. co m 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 = DocumentHelper.parseText(stringWriter.toString()); } catch (Exception e) { e.printStackTrace(); return (null); } return (document); }
From source file:org.ranji.longan.skeleton.ParentSkeleton.java
private static void createPomXmlFile(String projectName, String projectSimpleName, File projectDir) { File pomFile = new File(projectDir, "pom.xml"); URL url = ParentSkeleton.class.getClassLoader().getResource("parent/pom.rj"); SAXReader reader = new SAXReader(); try {//from ww w . j av a2 s . com Document doc = reader.read(url); Element rootElm = doc.getRootElement(); //-- 1. groupId Element groupIdElm = rootElm.element("groupId"); groupIdElm.setText(projectName.trim()); //-- 2. artifactId Element artifactIdElm = rootElm.element("artifactId"); artifactIdElm.setText(projectSimpleName); //-- 3. name Element nameElm = rootElm.element("name"); nameElm.setText(projectSimpleName); //-- 4. ? OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("UTF-8"); try { XMLWriter writer = new XMLWriter(new FileWriter(pomFile), format); writer.write(doc); writer.close(); } catch (IOException e) { e.printStackTrace(); } } catch (DocumentException e) { e.printStackTrace(); } }
From source file:org.richie.codeGen.ui.util.XmlParse.java
License:Apache License
/** * xml?/* w w w. j a v a2 s . c o m*/ * * @param document ? * @param outFile ? * @throws IOException */ public static void writeDocument(Document document, String outFile) throws IOException { XMLWriter xmlWriter = null; try { // ? OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"); // ? OutputFormat xmlFormat = new OutputFormat(); xmlFormat.setEncoding("UTF-8"); // xmlWriter = new XMLWriter(out, xmlFormat); // xmlWriter.write(document); } catch (IOException e) { throw e; } finally { // if (xmlWriter != null) xmlWriter.close(); } }
From source file:org.snipsnap.snip.storage.XMLFileSnipStorage.java
License:Open Source License
protected void storeSnip(snipsnap.api.snip.Snip snip, OutputStream out) { Document snipDocument = DocumentHelper.createDocument(); snipDocument.add(serializer.serialize(snip)); try {//from www .ja v a 2 s. com OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); XMLWriter xmlWriter = new XMLWriter(out, outputFormat); xmlWriter.write(snipDocument); xmlWriter.flush(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.snipsnap.snip.XMLSnipExport.java
License:Open Source License
public static void store(OutputStream out, List snips, List users, String filter, List ignoreElements, File fileStore) {/*from w w w.ja va2s. c o m*/ try { OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); outputFormat.setNewlines(true); XMLWriter xmlWriter = new XMLWriter(out, outputFormat); Element root = DocumentHelper.createElement("snipspace"); xmlWriter.writeOpen(root); storeUsers(xmlWriter, users); storeSnips(xmlWriter, snips, filter, ignoreElements, fileStore); xmlWriter.writeClose(root); xmlWriter.flush(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.snipsnap.util.JDBCDatabaseExport.java
License:Open Source License
/** * Store snips and users from the SnipSpace to an xml document into a stream. * @param out outputstream to write to//from w w w. j ava2s . c o m */ public static void store(OutputStream out, String appOid, Connection connection) { try { OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); outputFormat.setNewlines(true); XMLWriter xmlWriter = new XMLWriter(out, outputFormat); xmlWriter.startDocument(); Element root = DocumentHelper.createElement("snipspace"); xmlWriter.writeOpen(root); // storeUsers(xmlWriter, connection); storeSnips(xmlWriter, appOid, connection); xmlWriter.writeClose(root); xmlWriter.endDocument(); xmlWriter.flush(); xmlWriter.close(); } catch (Exception e) { System.err.println("JDBCDatabaseExport: error while writing document: " + e.getMessage()); } }
From source file:org.snipsnap.util.XMLSnipRepair.java
License:Open Source License
public static void repair(File input, File output, File webAppDir) { System.err.println("STEP 1: parsing input file ..."); Document document = null;/* w ww . ja va 2 s. co m*/ try { document = load(input); } catch (Exception e) { System.err.println("Unable to read input document: " + e); System.err.println( "This is usually the case for illegal XML characters, please manually edit the file and remove them."); System.exit(0); } System.err.println("STEP 2: checking SnipSpace consistency ..."); Document repaired = repair(document, webAppDir); System.err.println("STEP 3: writing output file ..."); OutputFormat outputFormat = new OutputFormat(); outputFormat.setEncoding("UTF-8"); outputFormat.setNewlines(true); try { XMLWriter xmlWriter = new XMLWriter( null == output ? System.out : (OutputStream) new FileOutputStream(output)); xmlWriter.write(repaired); xmlWriter.flush(); xmlWriter.close(); } catch (Exception e) { System.err.println("Error: unable to write data: " + e); } System.err.println("Finished."); }