List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:org.nuxeo.ecm.platform.ui.web.component.list.UIJavascriptList.java
/** * Renders an element using rowIndex -2 and client side marker {@link #TEMPLATE_INDEX_MARKER}. * <p>/*from w w w .j a va 2 s . c om*/ * This element will be used on client side by js code to handle addition of a new element. */ protected void encodeTemplate(FacesContext context) throws IOException { int oldIndex = getRowIndex(); Object requestMapValue = saveRequestMapModelValue(); Map<String, Object> requestMap = getFacesContext().getExternalContext().getRequestMap(); boolean hasVar = false; if (requestMap.containsKey(IS_LIST_TEMPLATE_VAR)) { hasVar = true; } Object oldIsTemplateBoolean = requestMap.remove(IS_LIST_TEMPLATE_VAR); try { setRowIndex(-2); // expose a boolean that can be used on client side to hide this element without disturbing the DOM requestMap.put(IS_LIST_TEMPLATE_VAR, Boolean.TRUE); // render the template as escaped html ResponseWriter oldResponseWriter = context.getResponseWriter(); StringWriter cacheingWriter = new StringWriter(); ResponseWriter newResponseWriter = context.getResponseWriter().cloneWithWriter(cacheingWriter); context.setResponseWriter(newResponseWriter); if (getChildCount() > 0) { for (UIComponent kid : getChildren()) { if (!kid.isRendered()) { continue; } try { ComponentSupport.encodeRecursive(context, kid); } catch (IOException err) { log.error("Error while rendering component " + kid); } } } cacheingWriter.flush(); cacheingWriter.close(); context.setResponseWriter(oldResponseWriter); String html = Functions.htmlEscape(cacheingWriter.toString()); ResponseWriter writer = context.getResponseWriter(); writer.write("<script type=\"text/x-html-template\">"); writer.write(html); writer.write("</script>"); } finally { setRowIndex(oldIndex); // restore if (hasVar) { requestMap.put(IS_LIST_TEMPLATE_VAR, oldIsTemplateBoolean); } else { requestMap.remove(IS_LIST_TEMPLATE_VAR); } restoreRequestMapModelValue(requestMapValue); } }
From source file:edu.harvard.hul.ois.fits.tools.exiftool.Exiftool.java
private Document createXml(String execOut) throws FitsToolException { StringWriter out = new StringWriter(); out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); out.write("\n"); out.write("<exiftool>"); out.write("\n"); out.write("<rawOutput>\n" + StringEscapeUtils.escapeXml(execOut)); out.write("</rawOutput>"); out.write("\n"); String[] lines = execOut.split("\n"); for (String line : lines) { String[] parts = line.split("\t"); String field = parts[0].trim(); if (parts.length > 1) { String value = parts[1].trim(); out.write("<" + field + ">" + StringEscapeUtils.escapeXml(value) + "</" + field + ">"); out.write("\n"); }/*from www . j ava2 s.co m*/ } out.write("</exiftool>"); out.write("\n"); out.flush(); try { out.close(); } catch (IOException e) { throw new FitsToolException("Error closing Exiftool XML output stream", e); } Document doc = null; try { doc = saxBuilder.build(new StringReader(out.toString())); } catch (Exception e) { throw new FitsToolException("Error parsing Exiftool XML Output", e); } return doc; }
From source file:org.craftercms.cstudio.loadtesting.actions.WriteContent.java
/** * convert InputStream to string/*from w w w.j a v a 2s . c o m*/ * @param internalName * * @param is * @return string */ public String getFileContent(String baseFileName, String fileName, String internalName) throws Exception { InputStream is = null; InputStreamReader isReader = null; StringWriter sw = null; XMLWriter writer = null; try { is = this.getClass().getResourceAsStream("/" + baseFileName); isReader = new InputStreamReader(is, "UTF-8"); SAXReader saxReader = new SAXReader(); Document document = saxReader.read(isReader); Element root = document.getRootElement(); Node node = root.selectSingleNode("file-name"); node.setText(fileName); Node node2 = root.selectSingleNode("internal-name"); node2.setText(internalName); sw = new StringWriter(); writer = new XMLWriter(sw); writer.write(document); writer.flush(); return sw.toString(); } finally { if (is != null) { is.close(); } if (isReader != null) { isReader.close(); } if (sw != null) { sw.close(); } if (writer != null) { writer.close(); } } }
From source file:org.apache.cayenne.modeler.dialog.ErrorDebugDialog.java
protected void setThrowable(Throwable throwable) { this.throwable = throwable; String text = null;//ww w .ja v a2 s. co m if (throwable != null) { StringWriter str = new StringWriter(); PrintWriter out = new PrintWriter(str); // first add extra diagnostics String version = LocalizedStringsHandler.getString("cayenne.version"); version = (version != null) ? version : "(unknown)"; String buildDate = LocalizedStringsHandler.getString("cayenne.build.date"); buildDate = (buildDate != null) ? buildDate : "(unknown)"; out.println("CayenneModeler Info"); out.println("Version: " + version); out.println("Build Date: " + buildDate); out.println("Exception: "); out.println("================================="); buildStackTrace(out, throwable); try { out.close(); str.close(); } catch (IOException ioex) { // this should never happen } text = str.getBuffer().toString(); } exText.setText(text); }
From source file:io.github.gsteckman.rpi_rest.SsdpHandler.java
private String generateNotify() throws IOException { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.printf("NOTIFY * HTTP/1.1\r\n"); pw.printf("HOST: %s:%d\r\n", MULTICAST_ADDRESS, MULTICAST_PORT); pw.printf("CACHE-CONTROL: max-age=%d\r\n", MAX_AGE); pw.printf("LOCATION: http://%s:8080\r\n", getServerAddress()); pw.printf("NT: %s\r\n", ST); pw.printf("NTS: ssdp:alive\r\n"); pw.print("SERVER: " + System.getProperty("os.name") + "/" + System.getProperty("os.version") + ", UPnP/1.1, rpi-rest/0.1\r\n"); pw.printf("USN: uuid:%s\r\n", getUuid().toString()); pw.printf("BOOTID.UPNP.ORG: %d\r\n", BOOTID); pw.printf("CONFIGID.UPNP.ORG: %d\r\n", CONFIGID); pw.printf("\r\n"); pw.flush();// w ww .j av a2s. c om String resp = sw.toString(); pw.close(); sw.close(); return resp; }
From source file:org.openmicroscopy.shoola.env.data.model.FileObject.java
/** * Parses the image's description.//from w ww . j a v a 2 s. co m * * @param xmlStr The string to parse. * @return See above. */ private Document xmlParser(String xmlStr) throws SAXException { InputSource stream = new InputSource(); stream.setCharacterStream(new StringReader(xmlStr)); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); DocumentBuilder builder; Document doc = null; try { builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); doc = builder.parse(stream); } catch (ParserConfigurationException e) { e.printStackTrace(pw); IJ.log(sw.toString()); } catch (IOException e) { e.printStackTrace(pw); IJ.log(sw.toString()); } finally { try { sw.close(); } catch (IOException e) { IJ.log("I/O Exception:" + e.getMessage()); } pw.close(); } return doc; }
From source file:com.jaeksoft.searchlib.parser.HtmlParser.java
@Override protected void parseContent(StreamLimiter streamLimiter, LanguageEnum forcedLang) throws IOException, SearchLibException { titleBoost = getFloatProperty(ClassPropertyEnum.TITLE_BOOST); boostTagMap = new TreeMap<String, BoostTag>(); boostTagMap.put("h1", new BoostTag(ClassPropertyEnum.H1_BOOST)); boostTagMap.put("h2", new BoostTag(ClassPropertyEnum.H2_BOOST)); boostTagMap.put("h3", new BoostTag(ClassPropertyEnum.H3_BOOST)); boostTagMap.put("h4", new BoostTag(ClassPropertyEnum.H4_BOOST)); boostTagMap.put("h5", new BoostTag(ClassPropertyEnum.H5_BOOST)); boostTagMap.put("h6", new BoostTag(ClassPropertyEnum.H6_BOOST)); ignoreMetaNoIndex = getBooleanProperty(ClassPropertyEnum.IGNORE_META_NOINDEX); ignoreMetaNoFollow = getBooleanProperty(ClassPropertyEnum.IGNORE_META_NOFOLLOW); ignoreLinkNoFollow = getBooleanProperty(ClassPropertyEnum.IGNORE_LINK_NOFOLLOW); ignoreUntitledDocuments = getBooleanProperty(ClassPropertyEnum.IGNORE_UNTITLED_DOCUMENTS); ignoreNonCanonical = getBooleanProperty(ClassPropertyEnum.IGNORE_NON_CANONICAL); String currentCharset = null; String headerCharset = null;//from www .j av a 2 s . co m String detectedCharset = null; IndexDocument sourceDocument = getSourceDocument(); if (sourceDocument != null) { FieldValueItem fieldValueItem = sourceDocument .getFieldValue(UrlItemFieldEnum.INSTANCE.contentTypeCharset.getName(), 0); if (fieldValueItem != null) headerCharset = fieldValueItem.getValue(); if (headerCharset == null) { fieldValueItem = sourceDocument.getFieldValue(UrlItemFieldEnum.INSTANCE.contentEncoding.getName(), 0); if (fieldValueItem != null) headerCharset = fieldValueItem.getValue(); } currentCharset = headerCharset; } if (currentCharset == null) { detectedCharset = streamLimiter.getDetectedCharset(); currentCharset = detectedCharset; } if (currentCharset == null) { currentCharset = getProperty(ClassPropertyEnum.DEFAULT_CHARSET).getValue(); } String xPathExclusions = getProperty(ClassPropertyEnum.XPATH_EXCLUSION).getValue(); Set<Object> xPathExclusionsSet = null; if (!StringUtils.isEmpty(xPathExclusions)) xPathExclusionsSet = new HashSet<Object>(); HtmlParserEnum htmlParserEnum = HtmlParserEnum.find(getProperty(ClassPropertyEnum.HTML_PARSER).getValue()); HtmlDocumentProvider htmlProvider = getHtmlDocumentProvider(htmlParserEnum, currentCharset, streamLimiter, xPathExclusions, xPathExclusionsSet); if (htmlProvider == null) return; URL currentURL = htmlProvider.getBaseHref(); IndexDocument srcDoc = getSourceDocument(); try { if (currentURL == null) currentURL = LinkUtils.newEncodedURL(streamLimiter.getOriginURL()); if (currentURL == null) { FieldValueItem fvi = srcDoc.getFieldValue(UrlItemFieldEnum.INSTANCE.url.getName(), 0); if (fvi != null) currentURL = LinkUtils.newEncodedURL(fvi.getValue()); } } catch (URISyntaxException e) { throw new IOException(e); } URL canonicalURL = htmlProvider.getCanonicalLink(currentURL); if (canonicalURL != null) { String canUrl = canonicalURL.toExternalForm(); addDetectedLink(canUrl); if (ignoreNonCanonical) { String curUrl = currentURL.toExternalForm(); if (!canUrl.equals(curUrl)) { isCanonical = false; return; } } } isCanonical = true; String title = htmlProvider.getTitle(); if (ignoreUntitledDocuments) if (title == null || title.length() == 0) return; ParserResultItem result = getNewParserResultItem(); addFieldTitle(result, title); result.addField(ParserFieldEnum.htmlProvider, htmlProvider.getName()); // Check ContentType charset in meta http-equiv String metaCharset = htmlProvider.getMetaCharset(); String selectedCharset = selectCharset(headerCharset, detectedCharset, metaCharset); if (selectedCharset != null) { if (!selectedCharset.equals(currentCharset)) { currentCharset = selectedCharset; htmlProvider = getHtmlDocumentProvider(htmlParserEnum, currentCharset, streamLimiter, xPathExclusions, xPathExclusionsSet); } } StringWriter writer = new StringWriter(); IOUtils.copy(streamLimiter.getNewInputStream(), writer, currentCharset); result.addField(ParserFieldEnum.htmlSource, writer.toString()); writer.close(); HtmlNodeAbstract<?> rootNode = htmlProvider.getRootNode(); if (rootNode == null) return; for (HtmlNodeAbstract<?> metaNode : htmlProvider.getMetas()) { String metaName = metaNode.getAttributeText("name"); if (metaName != null && metaName.startsWith(OPENSEARCHSERVER_FIELD)) { String field = metaName.substring(OPENSEARCHSERVER_FIELD_LENGTH); String[] fields = field.split("\\."); if (fields != null) { String content = metaNode.getAttributeText("content"); result.addDirectFields(fields, content); } } } result.addField(ParserFieldEnum.charset, currentCharset); String metaRobots = null; String metaDcLanguage = null; String metaContentLanguage = null; for (HtmlNodeAbstract<?> node : htmlProvider.getMetas()) { String attr_name = node.getAttributeText("name"); String attr_http_equiv = node.getAttributeText("http-equiv"); if ("keywords".equalsIgnoreCase(attr_name)) result.addField(ParserFieldEnum.meta_keywords, HtmlDocumentProvider.getMetaContent(node)); else if ("description".equalsIgnoreCase(attr_name)) result.addField(ParserFieldEnum.meta_description, HtmlDocumentProvider.getMetaContent(node)); else if ("robots".equalsIgnoreCase(attr_name)) metaRobots = HtmlDocumentProvider.getMetaContent(node); else if ("dc.language".equalsIgnoreCase(attr_name)) metaDcLanguage = HtmlDocumentProvider.getMetaContent(node); else if ("content-language".equalsIgnoreCase(attr_http_equiv)) metaContentLanguage = HtmlDocumentProvider.getMetaContent(node); } boolean metaRobotsFollow = true; boolean metaRobotsNoIndex = false; if (metaRobots != null) { metaRobots = metaRobots.toLowerCase(); if (metaRobots.contains("noindex") && !ignoreMetaNoIndex) { metaRobotsNoIndex = true; result.addField(ParserFieldEnum.meta_robots, "noindex"); } if (metaRobots.contains("nofollow") && !ignoreMetaNoFollow) { metaRobotsFollow = false; result.addField(ParserFieldEnum.meta_robots, "nofollow"); } } UrlFilterItem[] urlFilterList = getUrlFilterList(); boolean removeFragment = ClassPropertyEnum.KEEP_REMOVE_LIST[1] .equalsIgnoreCase(getProperty(ClassPropertyEnum.URL_FRAGMENT).getValue()); List<HtmlNodeAbstract<?>> nodes = rootNode.getAllNodes("a", "frame", "img"); if (srcDoc != null && nodes != null && metaRobotsFollow) { for (HtmlNodeAbstract<?> node : nodes) { String href = null; String rel = null; String nodeName = node.getNodeName(); if ("a".equals(nodeName)) { href = node.getAttributeText("href"); rel = node.getAttributeText("rel"); } else if ("frame".equals(nodeName) || "img".equals(nodeName)) { href = node.getAttributeText("src"); } boolean follow = true; if (rel != null) if (rel.contains("nofollow") && !ignoreLinkNoFollow) follow = false; URL newUrl = null; if (href != null) if (!href.startsWith("javascript:")) if (currentURL != null) { href = StringEscapeUtils.unescapeXml(href); newUrl = LinkUtils.getLink(currentURL, href, urlFilterList, removeFragment); } if (newUrl != null) { ParserFieldEnum field = null; if (newUrl.getHost().equalsIgnoreCase(currentURL.getHost())) { if (follow) field = ParserFieldEnum.internal_link; else field = ParserFieldEnum.internal_link_nofollow; } else { if (follow) field = ParserFieldEnum.external_link; else field = ParserFieldEnum.external_link_nofollow; } String link = newUrl.toExternalForm(); result.addField(field, link); if (follow) addDetectedLink(link); } } } if (!metaRobotsNoIndex) { nodes = rootNode.getNodes("html", "body"); if (nodes == null || nodes.size() == 0) nodes = rootNode.getNodes("html"); if (nodes != null && nodes.size() > 0) { StringBuilder sb = new StringBuilder(); getBodyTextContent(result, sb, nodes.get(0), true, null, 1024, xPathExclusionsSet); result.addField(ParserFieldEnum.body, sb); } } // Identification de la langue: Locale lang = null; String langMethod = null; String[] pathHtml = { "html" }; nodes = rootNode.getNodes(pathHtml); if (nodes != null && nodes.size() > 0) { langMethod = "html lang attribute"; String l = nodes.get(0).getAttributeText("lang"); if (l != null) lang = Lang.findLocaleISO639(l); } if (lang == null && metaContentLanguage != null) { langMethod = "meta http-equiv content-language"; lang = Lang.findLocaleISO639(metaContentLanguage); } if (lang == null && metaDcLanguage != null) { langMethod = "meta dc.language"; lang = Lang.findLocaleISO639(metaDcLanguage); } if (lang != null) { result.addField(ParserFieldEnum.lang, lang.getLanguage()); result.addField(ParserFieldEnum.lang_method, langMethod); } else if (!metaRobotsNoIndex) lang = result.langDetection(10000, ParserFieldEnum.body); if (getFieldMap().isMapped(ParserFieldEnum.generated_title)) { StringBuilder sb = new StringBuilder(); try { sb.append(new URI(streamLimiter.getOriginURL()).getHost()); } catch (URISyntaxException e) { Logging.error(e); } String generatedTitle = null; for (Map.Entry<String, BoostTag> entry : boostTagMap.entrySet()) { BoostTag boostTag = entry.getValue(); if (boostTag.firstContent != null) { generatedTitle = boostTag.firstContent; break; } } if (generatedTitle == null) { final String FIELD_TITLE = "contents"; MemoryIndex bodyMemoryIndex = new MemoryIndex(); Analyzer bodyAnalyzer = new WhitespaceAnalyzer(Version.LUCENE_36); String bodyText = result.getMergedBodyText(100000, " ", ParserFieldEnum.body); bodyMemoryIndex.addField(FIELD_TITLE, bodyText, bodyAnalyzer); IndexSearcher indexSearcher = bodyMemoryIndex.createSearcher(); IndexReader indexReader = indexSearcher.getIndexReader(); MoreLikeThis mlt = new MoreLikeThis(indexReader); mlt.setAnalyzer(bodyAnalyzer); mlt.setFieldNames(new String[] { FIELD_TITLE }); mlt.setMinWordLen(3); mlt.setMinTermFreq(1); mlt.setMinDocFreq(1); String[] words = mlt.retrieveInterestingTerms(0); if (words != null && words.length > 0) generatedTitle = words[0]; } if (generatedTitle != null) { if (sb.length() > 0) sb.append(" - "); sb.append(generatedTitle); } if (sb.length() > 67) { int pos = sb.indexOf(" ", 60); if (pos == -1) pos = 67; sb.setLength(pos); sb.append("..."); } result.addField(ParserFieldEnum.generated_title, sb.toString()); } }
From source file:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java
protected void processTempFile(final File df, final String fileEncoding, final String xmlVersion, final String header, final String footer, final TDocument persistenceConfig, final Pair collectivite, final Pair codeBudget, final File originalFile, final int docCount, final boolean shouldDelete, final int progress) { try {/* w w w .j av a 2s . co m*/ long startFile = System.currentTimeMillis(); String data = FileUtils.readTextFile(df, fileEncoding); StringBuilder fullText = new StringBuilder(); fullText.append("<?xml version=\"").append(xmlVersion).append("\" encoding=\"").append(fileEncoding) .append("\"?>"); fullText.append(header).append(data).append(footer); String sFullText = fullText.toString(); byte[] bData = sFullText.getBytes(fileEncoding); Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(bData)); // il faut retrouver de quel etat est ce document // on cherche si la balise root contient un // dm.getEtatxxx().getBalise() EtatModel currentEtat = null; for (EtatModel em : dm.getEtats()) { String balise = em.getBalise(); NodeList nl = doc.getElementsByTagName(balise); if (nl.getLength() > 0) { currentEtat = em; break; } else { nl = doc.getElementsByTagNameNS(em.getBaliseNamespace(), balise); if (nl.getLength() > 0) { currentEtat = em; break; } } } // traitement d'erreur, on n'arrive pas identifier l'etat if (currentEtat == null) { StringWriter sw = new StringWriter(); sw.append("Impossible de dterminer l'tat de ce document :\n"); TransformerFactory errorTransFactory = FactoryProvider.getTransformerFactory(); Transformer errorTransformer = errorTransFactory.newTransformer(); errorTransformer.transform(new DOMSource(doc), new StreamResult(sw)); sw.flush(); sw.close(); logger.error(sw.getBuffer().toString()); return; } // apply before-import xslt if (persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile() != null) { Transformer trans = importXsltCache .get(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile()); if (trans == null) { TransformerFactory tf = FactoryProvider.getTransformerFactory(); File directory = new File(currentEtat.getParent().getBaseDirectory()); File xslFile = new File(directory, persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile()); trans = tf.newTransformer(new StreamSource(xslFile)); importXsltCache.put(persistenceConfig.getEtat(currentEtat.getId()).getImportXsltFile(), trans); } // important, maintenant que c'est mis en cache ! trans.reset(); if (codeBudget != null) { trans.setParameter("CodeBudget", codeBudget.key); trans.setParameter("LibelleBudget", codeBudget.libelle); } if (collectivite != null) { trans.setParameter("CodeCollectivite", collectivite.key); trans.setParameter("LibelleCollectivite", collectivite.libelle); } if (getManifeste() != null) { trans.setParameter("manifeste", new DOMSource(getManifeste())); } // on passe en parametre le nom du fichier trans.setParameter("file.name", originalFile.getName()); trans.setOutputProperty(OutputKeys.ENCODING, fileEncoding); ByteArrayOutputStream baos = new ByteArrayOutputStream(); trans.transform(new StreamSource(new ByteArrayInputStream(sFullText.getBytes(fileEncoding))), new StreamResult(baos)); bData = baos.toByteArray(); } importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm()) .append(";XSL;").append(Long.toString(startFile)).append(";") .append(Long.toString(startFile = System.currentTimeMillis())); importTimingOS.println(); String docName = StringUtilities.removeFileNameSuffix(originalFile.getName()) + "-" + docCount + "." + dm.getExtension(); if (!isCancelled()) { try { if (!DataLayerManager.getImplementation().importElement(dm, currentEtat, codeBudget, collectivite, originalFile.getName(), docName, bData, fileEncoding, getArchiveName(), user)) { logger.warn(DataLayerManager.getImplementation().getWarnings()); warningCount++; } } catch (DataAccessException daEx) { logger.error("importing element:", daEx); throw (Exception) daEx; } catch (DataConfigurationException dcEx) { logger.error("importing element:", dcEx); throw (Exception) dcEx.getCause(); } } if (shouldDelete) { df.delete(); } importTimingOS.append(originalFile.getName()).append(";").append(df.toURI().toURL().toExternalForm()) .append(";IDX;").append(Long.toString(startFile)).append(";") .append(Long.toString(startFile = System.currentTimeMillis())); importTimingOS.println(); this.getImpSvcProvider().pushCurrentProgress(progress); } catch (Exception ex) { //TODO } }
From source file:org.dswarm.graph.resources.MaintainResource.java
/** * note utilise this endpoint with care, because it cleans your complete db! * * @param database the graph database/*from www . j a v a 2 s . c om*/ */ @DELETE @Path("/delete") @Produces("application/json") public Response cleanGraph(@Context final GraphDatabaseService database) throws IOException, DMPGraphException { MaintainResource.LOG.debug("start cleaning up the db"); final long deleted = deleteSomeStatements(database); MaintainResource.LOG.debug("finished delete-all-entities TXs"); MaintainResource.LOG.debug("start legacy indices clean-up"); // TODO: maybe separate index clean-up + observe index clean-up // => maybe we also need to do a label + relationship types clean-up ... => this is not supported right now ... deleteSomeLegacyIndices(database); MaintainResource.LOG.debug("finished legacy indices clean-up"); MaintainResource.LOG.debug("start schema indices clean-up"); deleteSomeSchemaIndices(database); MaintainResource.LOG.debug("finished schema indices clean-up"); MaintainResource.LOG.debug("finished cleaning up the db"); final StringWriter out = new StringWriter(); final JsonGenerator generator = simpleObjectMapper.getFactory().createGenerator(out); generator.writeStartObject(); generator.writeNumberField("deleted", deleted); generator.writeEndObject(); generator.flush(); generator.close(); final String result = out.toString(); out.flush(); out.close(); return Response.ok(result, MediaType.APPLICATION_JSON_TYPE).build(); }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
/** * certificationRequestToPEM - Convert a PKCS10CertificationRequest to PEM * format./*from w ww. j ava2 s.c o m*/ * * @param csr The Certificate to convert * @return An equivalent PEM format certificate. * @throws IOException */ private String certificationRequestToPEM(PKCS10CertificationRequest csr) throws IOException { PemObject pemCSR = new PemObject("CERTIFICATE REQUEST", csr.getEncoded()); StringWriter str = new StringWriter(); JcaPEMWriter pemWriter = new JcaPEMWriter(str); pemWriter.writeObject(pemCSR); pemWriter.close(); str.close(); return str.toString(); }