List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);/*from ww w. jav a 2 s. c o m*/ } CommandLine cmdLine; if (execPath != null) { // Run the configured calibre ebook-convert executable logger.info("Calibre ebook-convert will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Calibre ebook-convert will be run within the PATH variable."); cmdLine = new CommandLine(command); } // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString()); cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString()); // Output will be in format "KF8" only, old format does not allow external CSS files cmdLine.addArgument("--mobi-file-type=new"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter writer = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8")); ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err); executor.setStreamHandler(calibreStreamHandler); logger.debug("Launching calibres ebook-convert:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("calibres ebook-convert failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("calibre ebook-converts execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) { logger.error("calibres ebook-convert could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("calibre ebook-converts execution got interrupted: "); logger.error(e.getMessage(), e); } String output = ""; try { output += writer.getBuffer().toString(); writer.close(); } catch (IOException e) { logger.error("Error reading calibre ebook-converts output from buffer:"); logger.error(e.getMessage(), e); } logger.debug("Calibre ebook-convert output: \n" + output); return tempMobiFilepath.toFile(); }
From source file:edu.cornell.med.icb.goby.stats.TestAnnotationAveragingWriter.java
@Test // test writing counts public void testCaseEstimateP() throws IOException { String[] groups = new String[] { "group1", "group1", "group2", "group2" }; String[] samples = new String[] { "sample1", "sample2", "sample3", "sample4" }; int[] positions = new int[] { 6, 8, 14, 16 }; int[][] C = { { 5, 3, 9, 8 }, { 4, 6, 3, 2 }, { 8, 3, 8, 9 }, { 7, 4, 9, 7 } }; int[][] Cm = { { 9, 7, 1, 5 }, { 9, 7, 9, 3 }, { 2, 3, 2, 8 }, { 4, 1, 3, 6 } }; testSupport = new MethylCountProviderTestSupport(groups, samples, positions, "Case4", C, Cm); final StringWriter stringWriter = new StringWriter(); AnnotationAveragingWriter.doc().setValue("estimate-empirical-P", true); AnnotationAveragingWriter.doc().setValue("serialized-estimator-filename", makeDensityEstimator()); AnnotationAveragingWriter.doc().setValue("combinator", "sum"); AnnotationAveragingWriter testWriter = new AnnotationAveragingWriter(stringWriter, genome, testSupport); testWriter.setWriteNumSites(false);//from w w w . j a v a 2 s . c om testWriter.setAnnotationFilename("test-data/vcf-averaging/annotations-1.tsv"); testWriter.setAggregateAllContexts(true); testWriter.setSampleIndexToGroupIndex(new int[] { 0, 0, 1, 1 }); ArrayList<GroupComparison> groupComparisons = new ArrayList<GroupComparison>(); GroupComparison comparisonToMake = new GroupComparison("group1", "group2", 0, 1, 0); groupComparisons.add(comparisonToMake); testWriter.setGroupComparisons(groupComparisons); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.writeRecord(); testWriter.close(); assertEquals("Test Case 1 result: ", "Chromosome\tStart\tEnd\tFeature\tMR[sample1]\tMR[sample2]\tMR[sample3]\tMR[sample4]\tMR[group1]\tMR[group1]\tMR[group2]\tMR[group2]\tfisherP[group1/group2]\tdeltaMR[group1/group2]\tempiricalP[group1/group2]\n" + "Case4\t5\t9\tannotation7\t66.67\t61.54\t31.25\t31.25\t64.00\t31.25\t\t\t0.006227\t32.75\t0.0009995\n" + "Case4\t13\t17\tannotation8\t26.09\t70.59\t37.04\t36.00\t45.00\t36.54\t\t\t0.5205\t8.462\t0.0009995\n", stringWriter.getBuffer().toString()); }
From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java
@Override public File convertToMobi(File htmlFile) { logger.debug("Enter convertToMobi()..."); if (htmlFile == null) { logger.error("Document is null, aborting..."); System.exit(1);/*from www.j a v a 2 s .c o m*/ } CommandLine cmdLine; if (execPath != null) { // Run the configured kindlegen executable logger.info("Kindlegen will be run from: " + execPath.toString()); cmdLine = new CommandLine(execPath.toFile()); } else { // Run in system PATH environment logger.info("Kindlegen will be run within the PATH variable."); cmdLine = new CommandLine(command); } // Run configuration cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString()); cmdLine.addArgument("-c0"); DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler(); ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); Executor executor = new DefaultExecutor(); executor.setExitValue(1); executor.setWatchdog(watchdog); StringWriter stdoutWriter = new StringWriter(); StringWriter stderrWriter = new StringWriter(); WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8")); WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8")); ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream); executor.setStreamHandler(kindlegenStreamHandler); logger.debug("Launching kindlegen:"); logger.debug(cmdLine.toString()); try { executor.execute(cmdLine, resultHandler); } catch (IOException e) { logger.error("Kindlegen failed to execute:"); logger.error(e.getMessage(), e); System.exit(-1); } try { resultHandler.waitFor(); int exitValue = resultHandler.getExitValue(); logger.debug("Kindlegen execution's exit value: " + exitValue); ExecuteException executeException = resultHandler.getException(); if (executeException != null && executeException.getCause() != null) { String exceptionKlass = executeException.getCause().getClass().getCanonicalName(); String exceptionMessage = executeException.getCause().getMessage(); if (exceptionKlass.endsWith("IOException") || exceptionMessage.contains("Cannot run program \"kindlegen\"")) { logger.error("Kindlegen could not be run! Exiting..."); logger.debug(executeException); System.exit(1); } logger.debug(exceptionKlass + ": " + exceptionMessage); } } catch (InterruptedException e) { logger.error("Kindlegen's execution got interrupted: "); logger.error(e.getMessage(), e); } try { String stderrOutput = stderrWriter.getBuffer().toString(); stderrWriter.close(); if (stderrOutput.isEmpty() == false) { logger.error("Kindlegen logged some errors:"); logger.error(stderrOutput); } } catch (IOException e) { logger.error("Error closing kindlegen's stderr buffer"); logger.error(e.getMessage(), e); } String output = ""; try { output += stdoutWriter.getBuffer().toString(); stdoutWriter.close(); } catch (IOException e) { logger.error("Error closing kindlegen's stdout buffer:"); logger.error(e.getMessage(), e); } logger.debug("Kindlegen output: \n" + output); String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString(); logger.debug("Moving Kindlegen output file: " + mobiFilename); Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename); return tempMobiFilepath.toFile(); }
From source file:com.stratelia.webactiv.yellowpages.control.YellowpagesSessionController.java
private List<StringBuilder> exportAllDataAsCSV() { Collection<ContactFatherDetail> contacts = getAllContactDetails(currentTopic.getNodePK()); StringBuilder csvRow = new StringBuilder(); List<StringBuilder> csvRows = new ArrayList<StringBuilder>(); // Can't export all columns because data are heterogenous csvRow = getCSVCols();/*w ww . j av a 2 s. c om*/ // csvRows.add(csvRow); for (ContactFatherDetail contactFatherDetail : contacts) { ContactDetail contact = contactFatherDetail.getContactDetail(); if (contact != null) { csvRow = new StringBuilder(); addCSVValue(csvRow, contact.getLastName()); addCSVValue(csvRow, contact.getFirstName()); addCSVValue(csvRow, contact.getEmail()); addCSVValue(csvRow, contact.getPhone()); addCSVValue(csvRow, contact.getFax()); // adding userFull data UserFull userFull = contact.getUserFull(); if (userFull != null) { String[] properties = userFull.getPropertiesNames(); for (String property : properties) { if (!property.startsWith("password")) { addCSVValue(csvRow, userFull.getValue(property)); } } } // adding xml data String modelId = "unknown"; try { modelId = getNodeBm().getDetail(new NodePK(contactFatherDetail.getNodeId(), getComponentId())) .getModelId(); if (StringUtil.isDefined(modelId) && modelId.endsWith(".xml")) { String xmlFormName = modelId; String xmlFormShortName = xmlFormName.substring(0, xmlFormName.indexOf(".")); PublicationTemplateImpl pubTemplate = (PublicationTemplateImpl) getPublicationTemplateManager() .getPublicationTemplate(getComponentId() + ":" + xmlFormShortName, xmlFormName); // get template and data AbstractForm formView = (AbstractForm) pubTemplate.getViewForm(); RecordSet recordSet = pubTemplate.getRecordSet(); DataRecord data = recordSet.getRecord(contact.getPK().getId()); List<FieldTemplate> fields = formView.getFieldTemplates(); for (FieldTemplate fieldTemplate : fields) { String fieldType = fieldTemplate.getTypeName(); StringWriter sw = new StringWriter(); PrintWriter out = new PrintWriter(sw, true); Field field = data.getField(fieldTemplate.getFieldName()); if (field != null) { if (!fieldType.equals(Field.TYPE_FILE)) { FieldDisplayer fieldDisplayer = TypeManager.getInstance() .getDisplayer(fieldType, "simpletext"); if (fieldDisplayer != null) { fieldDisplayer.display(out, field, fieldTemplate, new PagesContext()); } String fieldValue = sw.getBuffer().toString(); // removing ending carriage return appended by out.println() of displayers if (fieldValue.endsWith("\r\n")) { fieldValue = fieldValue.substring(0, fieldValue.length() - 2); } addCSVValue(csvRow, fieldValue); } } } } } catch (Exception e) { SilverTrace.warn("yellowpages", "YellowpagesSessionController.exportAllDataAsCSV", "yellowpages.EX_GET_USER_DETAIL_FAILED", "modelId = " + modelId + ", contactId = " + contact.getPK().getId()); } // Remove final "," csvRow.deleteCharAt(csvRow.lastIndexOf(",")); csvRows.add(csvRow); } } return csvRows; }
From source file:org.ajax4jsf.context.ViewResources.java
public void processHeadResources(FacesContext context) throws FacesException { RenderKitFactory rkFactory = (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY); renderKit = rkFactory.getRenderKit(context, context.getViewRoot().getRenderKitId()); boolean scriptsOff = false; processStyles = true;/*from ww w .j a v a2 s. c o m*/ processScripts = true; useSkinning = false; ajaxRequest = AjaxContext.getCurrentInstance(context).isAjaxRequest(context); if (log.isDebugEnabled()) { log.debug("Process component tree for collect used scripts and styles"); } String skinStyleSheetUri = null; String skinExtendedStyleSheetUri = null; Skin skin = null; try { skin = SkinFactory.getInstance().getSkin(context); // For a "NULL" skin, do not collect components stylesheets if ("false".equals(skin.getParameter(context, Skin.loadStyleSheets))) { processStyles = false; } // Set default style sheet for current skin. skinStyleSheetUri = (String) skin.getParameter(context, Skin.generalStyleSheet); // Set default style sheet for current skin. skinExtendedStyleSheetUri = (String) skin.getParameter(context, Skin.extendedStyleSheet); } catch (SkinNotFoundException e) { if (log.isWarnEnabled()) { log.warn("Current Skin is not found", e); } } resourceBuilder = InternetResourceBuilder.getInstance(); ResponseWriter oldResponseWriter = context.getResponseWriter(); componentWriter = new HeadResponseWriter("component"); userWriter = new HeadResponseWriter("user"); try { componentWriter.startDocument(); userWriter.startDocument(); context.setResponseWriter(componentWriter); // Check init parameters for a resources processing. if (null != scriptStrategy) { if (InternetResourceBuilder.LOAD_NONE.equals(scriptStrategy)) { scriptsOff = true; processScripts = false; } else if (InternetResourceBuilder.LOAD_ALL.equals(scriptStrategy)) { processScripts = false; // For an "ALL" strategy, it is not necessary to load scripts in the ajax request if (!ajaxRequest) { try { resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT) .encode(context, null); resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_UI_SCRIPT) .encode(context, null); } catch (ResourceNotFoundException e) { if (log.isWarnEnabled()) { log.warn("No aggregated javaScript library found " + e.getMessage()); } } } } } if (InternetResourceBuilder.LOAD_NONE.equals(styleStrategy)) { processStyles = false; } else if (InternetResourceBuilder.LOAD_ALL.equals(styleStrategy)) { processStyles = false; // For an "ALL" strategy, it is not necessary to load styles // in the ajax request if (!ajaxRequest) { try { useSkinning = encodeSkinningResources(context, resourceBuilder); resourceBuilder.createResource(this, InternetResourceBuilder.COMMON_STYLE).encode(context, null); } catch (ResourceNotFoundException e) { if (log.isWarnEnabled()) { log.warn("No stylesheet found " + e.getMessage()); } } } } else { useSkinning = encodeSkinningResources(context, resourceBuilder); } //traverse components traverse(context, context.getViewRoot()); context.setResponseWriter(componentWriter); QueueRegistry queueRegistry = QueueRegistry.getInstance(context); if (Boolean.valueOf(getInitParameterValue(context, "org.richfaces.queue.global.enabled"))) { queueRegistry.setShouldCreateDefaultGlobalQueue(); } if (queueRegistry.hasQueuesToEncode()) { InternetResource queueScriptResource = resourceBuilder.getResource(QUEUE_SCRIPT_RESOURCE); queueScriptResource.encode(context, null); } // Append Skin StyleSheet after a if (null != skinStyleSheetUri) { String resourceURL = context.getApplication().getViewHandler().getResourceURL(context, skinStyleSheetUri); URIInternetResource resourceImpl = new URIInternetResource(); resourceImpl.setUri(resourceURL); resourceImpl.setRenderer(resourceBuilder.getStyleRenderer()); resourceImpl.encode(context, null); useSkinning = true; } if (null != skinExtendedStyleSheetUri && extendedSkinningAllowed) { String resourceURL = context.getApplication().getViewHandler().getResourceURL(context, skinExtendedStyleSheetUri); URIInternetResource resourceImpl = new URIInternetResource(); resourceImpl.setUri(resourceURL); resourceImpl.setRenderer(resourceBuilder.getStyleRenderer()); resourceImpl.encode(context, null, EXTENDED_SKINNING); useSkinning = true; } if (useSkinning && extendedSkinningAllowed) { if (!ajaxRequest) { if (!scriptsOff) { //skinning levels aren't dynamic, page-level setting cannot be changed //by AJAX request EXTENDED_SKINNING_ON_RESOURCE.encode(context, null); } else { Map<String, Object> applicationMap = context.getExternalContext().getApplicationMap(); if (applicationMap.get(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY) == null) { //do it once per application life - strategies can be changed dynamically ResponseWriter writer = context.getResponseWriter(); try { StringWriter stringWriter = new StringWriter(); if (oldResponseWriter != null) { context.setResponseWriter(oldResponseWriter.cloneWithWriter(stringWriter)); } else { context.setResponseWriter(this.renderKit.createResponseWriter(stringWriter, "text/html", "US-ASCII")); } EXTENDED_SKINNING_ON_RESOURCE.encode(context, null); stringWriter.flush(); if (log.isInfoEnabled()) { log.info( "Extended skinning is on and NONE scripts loading strategy was detected. " + "Do not forget that one of " + InternetResourceBuilder.SKINNING_SCRIPT + " or " + InternetResourceBuilder.COMMON_FRAMEWORK_SCRIPT + " resources should be presented " + "on the page together with the following code: \n" + stringWriter.getBuffer().toString() + "\nfor extended level of skinning to work."); } } finally { if (writer != null) { context.setResponseWriter(writer); } } applicationMap.put(EXTENDED_SKINNING_ON_NO_SCRIPTS_INFO_KEY, Boolean.TRUE); } } } if (processScripts) { InternetResource resource = resourceBuilder.createResource(null, InternetResourceBuilder.SKINNING_SCRIPT); resource.encode(context, null); } } componentWriter.endDocument(); userWriter.endDocument(); } catch (IOException e) { throw new FacesException(e.getLocalizedMessage(), e); } finally { if (oldResponseWriter != null) { context.setResponseWriter(oldResponseWriter); } } }
From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java
/** * Parse an identify stdOut result (from in) and convert it to an XML content * * @param in identify response/*from w w w.j a va 2 s. co m*/ * @return XML content * @throws XMLStreamException on errors * @throws IOException on errors */ public static String parse(InputStream in) throws XMLStreamException, IOException { StringWriter sw = new StringWriter(2000); BufferedReader br = new BufferedReader(new InputStreamReader(in)); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); writer.writeStartDocument(); int lastLevel = 0, level, lastNonValueLevel = 1; boolean valueEntry; String curr = null; String[] entry; try { while ((curr = br.readLine()) != null) { level = getLevel(curr); if (level == 0 && curr.startsWith("Image:")) { writer.writeStartElement("Image"); entry = curr.split(": "); if (entry.length >= 2) writer.writeAttribute("source", entry[1]); lastLevel = level; continue; } if (!(valueEntry = pNumeric.matcher(curr).matches())) { while (level < lastLevel--) writer.writeEndElement(); lastNonValueLevel = level; } else level = lastNonValueLevel + 1; if (curr.endsWith(":")) { writer.writeStartElement( curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-")); lastLevel = level + 1; continue; } else if (pColormap.matcher(curr).matches()) { writer.writeStartElement( curr.substring(0, curr.lastIndexOf(':')).trim().replaceAll("[ :]", "-")); writer.writeAttribute("colors", curr.split(": ")[1].trim()); lastLevel = level + 1; continue; } entry = curr.split(": "); if (entry.length == 2) { if (!valueEntry) { writer.writeStartElement(entry[0].trim().replaceAll("[ :]", "-")); writer.writeCharacters(entry[1]); writer.writeEndElement(); } else { writer.writeEmptyElement("value"); writer.writeAttribute("key", entry[0].trim().replaceAll("[ :]", "-")); writer.writeAttribute("data", entry[1]); // writer.writeEndElement(); } } else { // System.out.println("unknown line: "+curr); } lastLevel = level; } } catch (Exception e) { LOG.error("Error at [" + curr + "]:" + e.getMessage(), e); } writer.writeEndDocument(); writer.flush(); writer.close(); return sw.getBuffer().toString(); }
From source file:com.flexive.core.IMParser.java
/** * Parse an identify stdOut result (from in) and convert it to an XML content * * @param in identify response/*from w ww . j a v a 2s .c o m*/ * @return XML content * @throws XMLStreamException on errors * @throws IOException on errors */ public static String parse(InputStream in) throws XMLStreamException, IOException { StringWriter sw = new StringWriter(2000); BufferedReader br = new BufferedReader(new InputStreamReader(in)); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(sw); writer.writeStartDocument(); int lastLevel = 0, level, lastNonValueLevel = 1; boolean valueEntry; String curr = null; String[] entry; try { while ((curr = br.readLine()) != null) { if (curr.indexOf(':') == -1 || curr.trim().length() == 0) { System.out.println("skipping: [" + curr + "]"); continue; //ignore lines without ':' } level = getLevel(curr); curr = curr.trim(); if (level == 0 && curr.startsWith("Image:")) { writer.writeStartElement("Image"); entry = curr.split(": "); if (entry.length >= 2) writer.writeAttribute("source", entry[1]); lastLevel = level; continue; } if (!(valueEntry = pNumeric.matcher(curr).matches())) { while (level < lastLevel--) writer.writeEndElement(); lastNonValueLevel = level; } else level = lastNonValueLevel + 1; if (curr.endsWith(":")) { writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':')))); lastLevel = level + 1; continue; } else if (pColormap.matcher(curr).matches()) { writer.writeStartElement(cleanElement(curr.substring(0, curr.lastIndexOf(':')))); writer.writeAttribute("colors", curr.split(": ")[1].trim()); lastLevel = level + 1; continue; } entry = curr.split(": "); if (entry.length == 2) { if (!valueEntry) { writer.writeStartElement(cleanElement(entry[0])); writer.writeCharacters(entry[1]); writer.writeEndElement(); } else { writer.writeEmptyElement("value"); writer.writeAttribute("key", cleanElement(entry[0])); writer.writeAttribute("data", entry[1]); // writer.writeEndElement(); } } else { // System.out.println("unknown line: "+curr); } lastLevel = level; } } catch (Exception e) { System.err.println("Error at [" + curr + "]:" + e.getMessage()); e.printStackTrace(); } writer.writeEndDocument(); writer.flush(); writer.close(); return sw.getBuffer().toString(); }
From source file:com.silverpeas.jobDomainPeas.control.JobDomainPeasSessionController.java
public String getSynchroReport() { if (m_ErrorOccured != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); m_ErrorOccured.printStackTrace(pw); return m_ErrorOccured.toString() + "\n" + sw.getBuffer().toString(); }//from w w w . j a v a2 s. c om return m_SynchroReport; }
From source file:org.apereo.portal.layout.dlm.RDBMDistributedLayoutStore.java
private org.dom4j.Element getExportLayoutDom(IPerson person, IUserProfile profile) { if (!this.layoutExistsForUser(person)) { return null; }/* w ww.ja v a2 s .co m*/ org.dom4j.Document layoutDoc = null; try { final Document layoutDom = this._safeGetUserLayout(person, profile); person.setAttribute(Constants.PLF, layoutDom); layoutDoc = this.reader.get().read(layoutDom); } catch (final Throwable t) { final String msg = "Unable to obtain layout & profile for user '" + person.getUserName() + "', profileId " + profile.getProfileId(); throw new RuntimeException(msg, t); } if (logger.isDebugEnabled()) { // Write out this version of the layout to the log for dev purposes... final StringWriter str = new StringWriter(); final XMLWriter xml = new XMLWriter(str, new OutputFormat(" ", true)); try { xml.write(layoutDoc); xml.close(); } catch (final Throwable t) { throw new RuntimeException( "Failed to write the layout for user '" + person.getUserName() + "' to the DEBUG log", t); } logger.debug("Layout for user: {}\n{}", person.getUserName(), str.getBuffer().toString()); } /* * Attempt to detect a corrupted layout; return null in such cases */ if (isLayoutCorrupt(layoutDoc)) { logger.warn("Layout for user: {} is corrupt; layout structures will not be exported.", person.getUserName()); return null; } /* * Clean up the DOM for export. */ // (1) Add structure & theme attributes... final int structureStylesheetId = profile.getStructureStylesheetId(); this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, structureStylesheetId, "structure"); final int themeStylesheetId = profile.getThemeStylesheetId(); this.addStylesheetUserPreferencesAttributes(person, profile, layoutDoc, themeStylesheetId, "theme"); // (2) Remove locale info... final Iterator<org.dom4j.Attribute> locale = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@locale").iterator(); while (locale.hasNext()) { final org.dom4j.Attribute loc = locale.next(); loc.getParent().remove(loc); } // (3) Scrub unnecessary channel information... for (final Iterator<org.dom4j.Element> orphanedChannels = (Iterator<org.dom4j.Element>) layoutDoc .selectNodes("//channel[@fname = '']").iterator(); orphanedChannels.hasNext();) { // These elements represent UP_LAYOUT_STRUCT rows where the // CHAN_ID field was not recognized by ChannelRegistryStore; // best thing to do is remove the elements... final org.dom4j.Element ch = orphanedChannels.next(); ch.getParent().remove(ch); } final List<String> channelAttributeWhitelist = Arrays.asList(new String[] { "fname", "unremovable", "hidden", "immutable", "ID", "dlm:plfID", "dlm:moveAllowed", "dlm:deleteAllowed" }); final Iterator<org.dom4j.Element> channels = (Iterator<org.dom4j.Element>) layoutDoc .selectNodes("//channel").iterator(); while (channels.hasNext()) { final org.dom4j.Element oldCh = channels.next(); final org.dom4j.Element parent = oldCh.getParent(); final org.dom4j.Element newCh = this.fac.createElement("channel"); for (final String aName : channelAttributeWhitelist) { final org.dom4j.Attribute a = (org.dom4j.Attribute) oldCh.selectSingleNode("@" + aName); if (a != null) { newCh.addAttribute(a.getQName(), a.getValue()); } } parent.elements().add(parent.elements().indexOf(oldCh), newCh); parent.remove(oldCh); } // (4) Convert internal DLM noderefs to external form (pathrefs)... for (final Iterator<org.dom4j.Attribute> origins = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:origin").iterator(); origins.hasNext();) { final org.dom4j.Attribute org = origins.next(); final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), org.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... org.setValue(dlmPathref.toString()); } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", org.getUniquePath(), person.getAttribute(IPerson.USERNAME), org.getValue()); } } } for (final Iterator<org.dom4j.Attribute> it = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:target").iterator(); it.hasNext();) { final org.dom4j.Attribute target = it.next(); final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), target.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... target.setValue(dlmPathref.toString()); } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", target.getUniquePath(), person.getAttribute(IPerson.USERNAME), target.getValue()); } } } for (final Iterator<org.dom4j.Attribute> names = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//dlm:*/@name").iterator(); names.hasNext();) { final org.dom4j.Attribute n = names.next(); if (n.getValue() == null || n.getValue().trim().length() == 0) { // Outer <dlm:positionSet> elements don't seem to use the name // attribute, though their childern do. Just skip these so we // don't send a false WARNING. continue; } final Pathref dlmPathref = this.nodeReferenceFactory.getPathrefFromNoderef( (String) person.getAttribute(IPerson.USERNAME), n.getValue(), layoutDoc.getRootElement()); if (dlmPathref != null) { // Change the value only if we have a valid pathref... n.setValue(dlmPathref.toString()); // These *may* have fnames... if (dlmPathref.getPortletFname() != null) { n.getParent().addAttribute("fname", dlmPathref.getPortletFname()); } } else { if (logger.isWarnEnabled()) { logger.warn("Layout element '{}' from user '{}' failed to match noderef '{}'", n.getUniquePath(), person.getAttribute(IPerson.USERNAME), n.getValue()); } } } // Remove synthetic Ids, but from non-fragment owners only... if (!this.isFragmentOwner(person)) { /* * In the case of fragment owners, the original database Ids allow * us keep (not break) the associations that subscribers have with * nodes on the fragment layout. */ // (5) Remove dlm:plfID... for (final Iterator<org.dom4j.Attribute> plfid = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@dlm:plfID").iterator(); plfid.hasNext();) { final org.dom4j.Attribute plf = plfid.next(); plf.getParent().remove(plf); } // (6) Remove database Ids... for (final Iterator<org.dom4j.Attribute> ids = (Iterator<org.dom4j.Attribute>) layoutDoc .selectNodes("//@ID").iterator(); ids.hasNext();) { final org.dom4j.Attribute a = ids.next(); a.getParent().remove(a); } } return layoutDoc.getRootElement(); }
From source file:com.redhat.rhn.frontend.taglibs.list.ListTag.java
private void doAfterBodyRenderTopAddons() throws JspException { ListTagUtil.setCurrentCommand(pageContext, getUniqueName(), ListCommand.TBL_ADDONS); StringWriter topAlphaBarContent = new StringWriter(); StringWriter topPaginationContent = new StringWriter(); StringWriter topAddonsContent = new StringWriter(); StringWriter topExtraContent = new StringWriter(); pageContext.pushBody(topAlphaBarContent); if (!manip.isListEmpty() && !StringUtils.isBlank(alphaBarColumn)) { AlphaBarHelper.getInstance().writeAlphaBar(pageContext, manip.getAlphaBarIndex(), getUniqueName()); }//from w w w . j a v a 2 s . c om pageContext.popBody(); pageContext.pushBody(topPaginationContent); if (!isEmpty()) { for (ListDecorator dec : getDecorators()) { dec.beforeTopPagination(); } } if (filter != null && manip.getUnfilteredDataSize() != 0) { ListTagUtil.renderFilterSubmit(pageContext, getUniqueName()); } renderTopPaginationControls(); pageContext.popBody(); pageContext.pushBody(topAddonsContent); if (!isEmpty()) { for (ListDecorator dec : getDecorators()) { dec.onTopExtraAddons(); } } pageContext.popBody(); int topContentLength = topAddonsContent.getBuffer().length() + topAlphaBarContent.getBuffer().length() + topPaginationContent.getBuffer().length() + topExtraContent.getBuffer().length(); if (topContentLength > 0) { ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-top-addons\">"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-alphabar\">"); ListTagUtil.write(pageContext, topAlphaBarContent.toString()); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-pagination\">"); ListTagUtil.write(pageContext, topPaginationContent.toString()); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-top-addons-extra\">"); ListTagUtil.write(pageContext, topAddonsContent.toString()); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-top-extra\">"); ListTagUtil.write(pageContext, "</div>"); } ListTagUtil.write(pageContext, "<div class=\"panel panel-default\">"); // as the header addons is populated with decorators, we don't // know if there will be content or not, but we want to avoid // writing the head tag at all if there is none, so we push a // buffer into the stack, and empty it later. StringWriter headAddons = new StringWriter(); StringWriter headFilterContent = new StringWriter(); StringWriter headExtraContent = new StringWriter(); pageContext.pushBody(headAddons); if (!isEmpty()) { for (ListDecorator dec : getDecorators()) { dec.onHeadExtraAddons(); } } pageContext.popBody(); pageContext.pushBody(headFilterContent); if (filter != null && manip.getUnfilteredDataSize() != 0) { ListTagUtil.renderFilterUI(pageContext, filter, getUniqueName(), width, columnCount, searchParent, searchChild); } pageContext.popBody(); pageContext.pushBody(headExtraContent); if (!isEmpty()) { for (ListDecorator dec : getDecorators()) { dec.onHeadExtraContent(); } } pageContext.popBody(); int headContentLength = headFilterContent.getBuffer().length() + headAddons.getBuffer().length() + headExtraContent.getBuffer().length(); if (!StringUtils.isBlank(title)) { headContentLength += title.length(); } // this avoid render the row is there is no content at all if (headContentLength > 0) { ListTagUtil.write(pageContext, "<div class=\"panel-heading\">"); // only if there is a title, add a panel-heading if (!StringUtils.isBlank(title)) { HtmlTag h3 = new HtmlTag("h3"); h3.setAttribute("class", "panel-title"); h3.addBody(title); ListTagUtil.write(pageContext, h3.render()); } // render the navigation and filters as a row of the header ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-head-addons\">"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-filter\">"); ListTagUtil.write(pageContext, headFilterContent.toString()); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-head-addons-extra\">"); ListTagUtil.write(pageContext, headAddons.toString()); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "</div>"); ListTagUtil.write(pageContext, "<div class=\"spacewalk-list-head-extra\">"); ListTagUtil.write(pageContext, headExtraContent.toString()); ListTagUtil.write(pageContext, "</div>"); // close the panel heading ListTagUtil.write(pageContext, "</div>"); } HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); manip.bindPaginationInfo(); request.setAttribute("dataSize", String.valueOf(pageData.size() + 1)); if (pageData != null && pageData.size() > 0) { iterator = pageData.iterator(); } else { iterator = null; } }