List of usage examples for java.io Writer toString
public String toString()
From source file:ca.uhn.fhir.parser.BaseParser.java
@Override public String encodeTagListToString(TagList theTagList) { Writer stringWriter = new StringWriter(); try {/* www . j a v a 2 s . c om*/ encodeTagListToWriter(theTagList, stringWriter); } catch (IOException e) { throw new Error("Encountered IOException during write to string - This should not happen!"); } return stringWriter.toString(); }
From source file:ca.uhn.fhir.parser.BaseParser.java
@Override public String encodeResourceToString(IBaseResource theResource) throws DataFormatException { Writer stringWriter = new StringWriter(); try {// www. java 2 s . com encodeResourceToWriter(theResource, stringWriter); } catch (IOException e) { throw new Error("Encountered IOException during write to string - This should not happen!"); } return stringWriter.toString(); }
From source file:org.jab.docsearch.converters.PDFConverter.java
/** * @see ConverterInterface#parse()/*from w ww . j a va 2 s.c om*/ */ @Override public void parse() throws ConverterException { if (StringUtils.isEmpty(filename)) { log.error("parse() filename is null"); throw new ConverterException("PDFConverter::parse() filename is null"); } // PD Document PDDocument document = null; Writer output = null; try { document = getPDDocument(); // check document is readable AccessPermission ap = document.getCurrentAccessPermission(); if (!ap.canExtractContent()) { log.info("parse() Document (" + filename + ") isn't readable for DocSearcher."); throw new ConverterException("parse() can't read PDF file"); } // write the text to temp file try { log.debug("parse() Attempting to extract text from (" + filename + ")"); output = new StringWriter(); PDFTextStripper stripper = new PDFTextStripper(); stripper.writeText(document, output); log.debug("parse() Successfully stripped out text from (" + filename + ")"); } catch (IOException ioe) { log.error("parse() failed", ioe); throw new ConverterException("PDFConverter::parse() failed", ioe); } // get the meta data PDDocumentInformation info = document.getDocumentInformation(); documentTitle = info.getTitle(); documentAuthor = info.getAuthor(); documentKeywords = info.getKeywords(); if (document != null) { documentText = output.toString(); } } catch (IOException ioe) { log.error("parse() failed", ioe); throw new ConverterException("parse() failed", ioe); } finally { // close stream IOUtils.closeQuietly(output); // close document try { if (document != null) { document.close(); } } catch (IOException ioe) { log.fatal("parse() can't close PDDocument", ioe); } } if (log.isDebugEnabled()) { log.debug("parse() PDF file='" + filename + "'" + Layout.LINE_SEP + "title='" + documentTitle + "'" + Layout.LINE_SEP + "author='" + documentAuthor + "'" + Layout.LINE_SEP + "keywords='" + documentKeywords + "'"); } }
From source file:org.alfresco.web.cmm.CMMService.java
/** * Construct the Surf Extension Module for a given model. * <p>//from w w w . j a v a 2s . c o m * A Freemarker template is used to build the final extension module config from a hiearchy of template objects. See the * various TEMPLATE_ constants and module-configuration.ftl for the template model object names and template structure. * <p> * Each model maps to an extension and associated Share Forms and Share Document Library configuration output. If the model * is active then a number of Share Forms may be generated from persisted JSON form layouts. The template model transforms * the generic JSON form structure to the esoteric Share Form XML configuration. * * @param status WebScript status object - used to set error codes * @param modelName Model name to construct extension config for * @param formOp Optional form operation to apply to current Forms before extension module is generated * @param active Model active/deactive status */ protected void buildExtensionModule(Status status, String modelName, FormOperation formOp, boolean active) { final String moduleId = buildModuleId(modelName); // construct the model used to render the module template configuration TWrapper model = new TWrapper(8); model.put(TEMPLATE_MODULE_NAME, moduleId); List<Object> typeList = new ArrayList<>(); model.put(TEMPLATE_TYPES, typeList); List<Object> subtypesList = new ArrayList<>(); model.put(TEMPLATE_SUBTYPES, subtypesList); List<Object> aspectsList = new ArrayList<>(); model.put(TEMPLATE_ASPECTS, aspectsList); List<Object> entitiesList = new ArrayList<>(); model.put(TEMPLATE_ENTITIES, entitiesList); // retrieve form configuration if present already for this module to update new module definition Map<String, String> formDefs = new HashMap<>(); ExtensionModule module = getExtensionModule(modelName); if (module != null) { // retrieve existing form definitions from extension configuration e.g. formDefs = getFormDefinitions(module); } // perform optional form CrUD operation if (formOp != null) { formOp.perform(formDefs); } // add form definitions to template model map for (String entityId : formDefs.keySet()) { TWrapper wrapper = new TWrapper(4); wrapper.put(TEMPLATE_NAME, entityId).put(TEMPLATE_FORM, formDefs.get(entityId)); entitiesList.add(wrapper); } // if the model is active, we want to generate the Share config for types/aspects/forms if (active) { // get all types and aspects for the model and process them Response response = getAPIConnector().call( "/-default-/private/alfresco/versions/1/cmm/" + URLEncoder.encode(modelName) + "?select=all"); if (response.getStatus().getCode() == Status.STATUS_OK) { JSONObject jsonData = getJsonBody(response); // process types final JSONArray types = (JSONArray) ((JSONObject) jsonData.get(JSON_ENTRY)).get(JSON_TYPES); // walk the types and use form definitions to generate the form config objects // and also generate the sub-types list Map<String, List<TWrapper>> subtypeMap = new HashMap<>(); for (final Object t : types) { final JSONObject type = (JSONObject) t; String typeName = (String) type.get(JSON_PREFIXEDNAME); // generate form wrapper objects for this type TWrapper formWrappers = processFormWidgets(formDefs, type); // form definition present for this type? if (formWrappers.size() != 0) { // add type wrapper for template output TWrapper typeWrapper = new TWrapper(8); typeWrapper.put(TEMPLATE_NAME, typeName).put(TEMPLATE_TITLE, (String) type.get(JSON_TITLE)); typeList.add(typeWrapper); // add all form wrapper objects for the type typeWrapper.putAll(formWrappers); // for each type, firstly ensure is subtype of cm:content, // then walk the parent hiearchy and add this type as a subtype of each parent type up to and including cm:content if (this.dictionary.isSubType(typeName, CM_CONTENT) || this.dictionary.isSubType(typeName, CM_FOLDER)) { String parentType = typeName; do { // walk hiearchy to prepare for next loop iteration parentType = this.dictionary.getParent(parentType); List<TWrapper> subtypes = subtypeMap.get(parentType); if (subtypes == null) { subtypes = new ArrayList<>(4); subtypeMap.put(parentType, subtypes); } // check for existing - hierachies of types can repeat the same type from other hierachy boolean found = false; for (TWrapper st : subtypes) { if (st.get(TEMPLATE_NAME).equals(typeName)) { found = true; break; } } // add subtype wrapper for template output if (!found) { TWrapper subtypeWrapper = new TWrapper(4); subtypeWrapper.put(TEMPLATE_NAME, typeName).put(TEMPLATE_TITLE, this.dictionary.getTitle(typeName)); subtypes.add(subtypeWrapper); } } while (!(CM_CONTENT.equals(parentType) || CM_FOLDER.equals(parentType))); } } } // convert map to List for templates - each parent type then has an associated list of sub-type wrappers for (final String type : subtypeMap.keySet()) { TWrapper stypeWrapper = new TWrapper(4); stypeWrapper.put(TEMPLATE_NAME, type).put(TEMPLATE_SUBTYPES, subtypeMap.get(type)); subtypesList.add(stypeWrapper); } // process aspects final JSONArray aspects = (JSONArray) ((JSONObject) jsonData.get(JSON_ENTRY)).get(TEMPLATE_ASPECTS); for (final Object a : aspects) { final JSONObject aspect = (JSONObject) a; final String aspectName = (String) aspect.get(JSON_PREFIXEDNAME); // generate form wrapper objects for this aspect TWrapper formWrappers = processFormWidgets(formDefs, aspect); // add aspect wrapper for template output TWrapper aspectWrapper = new TWrapper(8); aspectWrapper.put(TEMPLATE_NAME, aspectName).put(TEMPLATE_TITLE, (String) aspect.get(JSON_TITLE)); aspectsList.add(aspectWrapper); // add all form wrapper objects for the type aspectWrapper.putAll(formWrappers); } } else { throw new AlfrescoRuntimeException( "Unable to retrieve types and aspects for model id: " + modelName); } } // render the template to generate the final module configuration and persist it Writer out = new StringBuilderWriter(4096); try { this.templateProcessor.process(MODULE_TEMPLATE_PATH, model, out); if (logger.isDebugEnabled()) logger.debug("Attempting to save module config:\r\n" + out.toString()); if (module == null) { this.moduleDeploymentService.addModuleToExtension(out.toString()); } else { this.moduleDeploymentService.updateModuleToExtension(out.toString()); } if (logger.isDebugEnabled()) logger.debug("addModuleToExtension() completed."); } catch (WebScriptException | DocumentException | ModelObjectPersisterException err) { // template error - probably developer exception so report in log logger.error("Failed to execute template to construct module configuration.", err); errorResponse(status, err.getMessage()); } }
From source file:hoot.services.command.CommandRunner.java
public CommandResult exec(String[] pCmd, Writer pOut, Writer pErr) throws IOException, InterruptedException { ProcessBuilder builder = new ProcessBuilder(); Map<String, String> env = builder.environment(); int out = 0;//from www . jav a 2 s . c o m String pCmdString = ArrayUtils.toString(pCmd); logExec(pCmdString, env); StopWatch clock = new StopWatch(); clock.start(); try { process = Runtime.getRuntime().exec(pCmd); out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt); } catch (Exception e) { //System.out.println(e.fillInStackTrace().toString()); } finally { this.cleanUpProcess(); clock.stop(); if (_log.isInfoEnabled()) _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms"); } if (sig_interrupt.getValue() == true) { out = -9999; } CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString()); return result; }
From source file:org.artifactory.repo.webdav.methods.PropfindMethod.java
@Override public void handle(ArtifactoryRequest request, ArtifactoryResponse response) throws IOException { // Retrieve the resources log.debug("Handling {}", getName()); int depth = findDepth(request); List<String> properties = null; PropfindType propertyFindType = PropfindType.FIND_ALL_PROP; Node propNode = null;/*from w w w .j a v a2 s. c o m*/ //get propertyNode and type if (request.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource(request.getInputStream())); logWebdavRequest(document); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: propertyFindType = PropfindType.fromString(currentNode.getNodeName()); if (propertyFindType == PropfindType.FIND_BY_PROPERTY) { propNode = currentNode; } break; } } } catch (Exception e) { throw new RuntimeException("Webdav propfind failed.", e); } } if (propertyFindType == PropfindType.FIND_BY_PROPERTY) { properties = getPropertiesFromXml(propNode); } response.setStatus(HttpStatus.SC_MULTI_STATUS); response.setContentType("text/xml; charset=UTF-8"); // Create multistatus object Writer writer = response.getWriter(); if (log.isDebugEnabled()) { writer = new StringWriter(); // write to memory so we'll be able to log the result as string } XmlWriter generatedXml = new XmlWriter(writer); generatedXml.writeXMLHeader(); generatedXml.writeElement(DEFAULT_NS_ABBRV, "multistatus", XmlWriter.OPENING, DEFAULT_NS_ABBRV, DEFAULT_NAMESPACE, "ns0", DEFAULT_NAMESPACE); RepoPath repoPath = request.getRepoPath(); BrowsableItem rootItem = null; if (repoService.exists(repoPath)) { rootItem = repoBrowsing.getLocalRepoBrowsableItem(repoPath); } if (rootItem != null) { recursiveParseProperties(request, generatedXml, rootItem, propertyFindType, properties, depth); } else { log.warn("Item '" + request.getRepoPath() + "' not found."); } generatedXml.writeElement(DEFAULT_NS_ABBRV, "multistatus", XmlWriter.CLOSING); generatedXml.sendData(); if (log.isDebugEnabled()) { log.debug("Webdav response:\n" + writer.toString()); //response.setContentLength(writer.toString().getBytes().length); response.getWriter().append(writer.toString()); } response.flush(); }
From source file:org.broadleafcommerce.core.content.service.ContentServiceImpl.java
public String renderedContent(String styleSheetString, List<Content> contentList, int rowCount) throws Exception { Source xmlSource;//from www .j a v a 2s . c om int maxCount = (rowCount > -1 && contentList.size() > 0) ? rowCount : contentList.size(); Writer resultWriter = new StringWriter(); StreamResult result = new StreamResult(resultWriter); Source styleSheetSource = getSource(styleSheetString); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(styleSheetSource); //TODO: some code here to group and show random item within priority group Comparator<Content> cntntCompare = new ContentComparator(); Collections.sort(contentList, cntntCompare); for (int i = 0; i < maxCount; i++) { ContentDetails contentDetail = findContentDetailsById(contentList.get(i).getId()); xmlSource = getSource(contentDetail.getXmlContent()); try { transformer.transform(xmlSource, result); } catch (Exception e) { LOG.error("Error during transformation. ", e); throw e; } } return StringEscapeUtils.unescapeXml(resultWriter.toString()); }
From source file:de.shadowhunt.subversion.internal.LogOperation.java
@Override protected HttpUriRequest createRequest() { final Writer body = new StringBuilderWriter(); try {//from w ww. j a v a 2 s .c o m final XMLStreamWriter writer = XML_OUTPUT_FACTORY.createXMLStreamWriter(body); writer.writeStartDocument(XmlConstants.ENCODING, XmlConstants.VERSION_1_0); writer.writeStartElement("log-report"); writer.writeDefaultNamespace(XmlConstants.SVN_NAMESPACE); writer.writeStartElement("start-revision"); writer.writeCharacters(start.toString()); writer.writeEndElement(); // start-revision writer.writeStartElement("end-revision"); writer.writeCharacters(end.toString()); writer.writeEndElement(); // end-revision if (limit > 0) { writer.writeStartElement("limit"); writer.writeCharacters(Integer.toString(limit)); writer.writeEndElement(); // limit } writer.writeEmptyElement("discover-changed-paths"); writer.writeEmptyElement("all-revprops"); writer.writeEmptyElement("path"); writer.writeEndElement(); // log-report writer.writeEndDocument(); writer.close(); } catch (final XMLStreamException e) { throw new SubversionException("could not create request body", e); } final URI uri = URIUtils.createURI(repository, resource); final DavTemplateRequest request = new DavTemplateRequest("REPORT", uri); request.setEntity(new StringEntity(body.toString(), CONTENT_TYPE_XML)); return request; }
From source file:it.drwolf.ridire.session.async.Mapper.java
private StringWithEncoding transformDOC2HTML(File resourceFile, EntityManager entityManager) throws IOException, SAXException, TikaException, TransformerConfigurationException { ParseContext context = new ParseContext(); Parser parser = new AutoDetectParser(); context.set(Parser.class, parser); Metadata metadata = new Metadata(); Writer writer = null; if (resourceFile.isFile()) { metadata.set(TikaMetadataKeys.RESOURCE_NAME_KEY, resourceFile.getName()); InputStream input = new FileInputStream(resourceFile); try {//from w w w .ja v a2 s .c o m writer = new StringWriter(); parser.parse(input, this.HTML.getContentHandler(null, writer), metadata, context); } finally { input.close(); if (writer != null) { writer.close(); } } CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(writer.toString().getBytes()); String encoding = charsetDetector.detect().getName(); StringWithEncoding stringWithEncoding = new StringWithEncoding(writer.toString(), encoding); return stringWithEncoding; } return null; }
From source file:hoot.services.command.CommandRunner.java
public CommandResult exec(String[] pCmd, Map<String, String> pEnv, boolean useSysEnv, Writer pOut, Writer pErr) throws IOException, InterruptedException { int out = 0;/*from w ww .j a v a2 s.c o m*/ String pCmdString = ArrayUtils.toString(pCmd); ProcessBuilder builder = new ProcessBuilder(); builder.command(pCmd); Map<String, String> env = builder.environment(); if (!useSysEnv) env.clear(); for (String name : pEnv.keySet()) { env.put(name, pEnv.get(name)); } logExec(pCmdString, env); StopWatch clock = new StopWatch(); clock.start(); try { process = builder.start(); out = handleProcess(process, pCmdString, pOut, pErr, _outputList, sig_interrupt); } finally { this.cleanUpProcess(); clock.stop(); if (_log.isInfoEnabled()) _log.info("'" + pCmdString + "' completed in " + clock.getTime() + " ms"); } if (sig_interrupt.getValue() == true) { out = -9999; } CommandResult result = new CommandResult(pCmdString, out, pOut.toString(), pErr.toString()); return result; }