articles
15 уровень

Java Code Examples for java.io.StringWriter. Часть 3

Пост из группы Архив info.javarush.ru
3681 участников
The following are top voted examples for showing how to use java.io.StringWriter. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples. Example 41 Project: OpenClinica File: SecureController.java public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString(); } Example 42 Project: sql-layer File: MultipleCauseException.java @Override public String toString() { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); printWriter.printf("%d cause%s%n", causes.size(), causes.size() == 1 ? ":" : "s:"); for (Enumerated cause : EnumeratingIterator.of(causes)) { printWriter.printf("%d:%n----------------------------%n", cause.count()); cause.get().printStackTrace(printWriter); } printWriter.flush(); stringWriter.flush(); return stringWriter.toString(); } Example 43 Project: jeboorker File: IOUtil.java public static byte[] toByteArray(Reader in, String encoding) throws IOException { StringWriter out = new StringWriter(); copy(in, out); out.flush(); return out.toString().getBytes(encoding); } Example 44 Project: aws-sdk-android File: XMLWriterTests.java @Test public void testEscapeXMLEntitiesProperlyEscapedFromString() { String expectedString = "quote "" apostrophe '' lessthan << greaterthan >> ampersand &&"; StringWriter sw = new StringWriter(); XMLWriter xw = new XMLWriter(sw); xw.startElement("Test"); xw.value("quote "\" apostrophe '' lessthan << greaterthan >> ampersand &&"); xw.endElement(); sw.flush(); assertEquals(sw.toString(), expectedString); } Example 45 Project: hise File: DOMUtils.java static public String domToString(Node node) { if (node == null) { throw new IllegalArgumentException("Cannot stringify null Node!"); } String value = null; short nodeType = node.getNodeType(); if (nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE) { // serializer doesn't handle Node type well, only Element DOMSerializerImpl ser = new DOMSerializerImpl(); ser.setParameter(Constants.DOM_NAMESPACES, Boolean.TRUE); ser.setParameter(Constants.DOM_WELLFORMED, Boolean.FALSE ); ser.setParameter(Constants.DOM_VALIDATE, Boolean.FALSE); // create a proper XML encoding header based on the input document; // default to UTF-8 if the parent document's encoding is not accessible String usedEncoding = "UTF-8"; Document parent = node.getOwnerDocument(); if (parent != null) { String parentEncoding = parent.getXmlEncoding(); if (parentEncoding != null) { usedEncoding = parentEncoding; } } // the receiver of the DOM DOMOutputImpl out = new DOMOutputImpl(); out.setEncoding(usedEncoding); // we write into a String StringWriter writer = new StringWriter(4096); out.setCharacterStream(writer); // out, ye characters! ser.write(node, out); writer.flush(); // finally get the String value = writer.toString(); } else { value = node.getNodeValue(); } return value; } Example 46 Project: extdirectspring File: ExtDirectSpringUtil.java public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw); pw.flush(); sw.flush(); return sw.toString(); } Example 47 Project: octarine File: Serialiser.java default String toString(T value) { StringWriter writer = new StringWriter(); try { toWriter(writer, value); } catch (IOException e) { throw new RuntimeException(e); } writer.flush(); return writer.toString(); } Example 48 Project: jasper-xml-to-pdf-generator File: JasperPdfGenerator.java private String applyVelocityTemplate(String templateData) throws Exception { Properties properties = new Properties(); properties.setProperty("resource.loader", "string"); properties.setProperty("string.resource.loader.class", "org.apache.velocity.runtime.resource.loader.StringResourceLoader"); properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); properties.setProperty("userdirective", "com.github.xmltopdf.MoneyUAHDirective," + "com.github.xmltopdf.MoneyToStrDirective," + "com.github.xmltopdf.DateDirective," + "com.github.xmltopdf.UkrToLatinDirective"); Velocity.init(properties); StringResourceRepository repo = StringResourceLoader.getRepository(); repo.putStringResource("template", templateData); Template template = Velocity.getTemplate("template", "UTF-8"); StringWriter writer = new StringWriter(); VelocityContext context = new VelocityContext(); context.put("xml", xmlTag); template.merge(context, writer); writer.flush(); writer.close(); return writer.toString(); } Example 49 Project: nuxeo-jsf File: UICellExcel.java public static String cmp2String(FacesContext facesContext, UIComponent component) throws IOException { ResponseWriter oldResponseWriter = facesContext.getResponseWriter(); String contentType = oldResponseWriter != null ? oldResponseWriter.getContentType() : DEFAULT_CONTENT_TYPE; String characterEncoding = oldResponseWriter != null ? oldResponseWriter.getCharacterEncoding() : DEFAULT_CHARACTER_ENCODING; StringWriter cacheingWriter = new StringWriter(); // XXX: create a response writer by hand, to control html escaping of // iso characters // take default values for these confs Boolean scriptHiding = Boolean.FALSE; Boolean scriptInAttributes = Boolean.TRUE; // force escaping to true WebConfiguration.DisableUnicodeEscaping escaping = WebConfiguration.DisableUnicodeEscaping.True; ResponseWriter newResponseWriter = new NXHtmlResponseWriter( cacheingWriter, contentType, characterEncoding, scriptHiding, scriptInAttributes, escaping); // ResponseWriter newResponseWriter = renderKit.createResponseWriter( // cacheingWriter, contentType, characterEncoding); facesContext.setResponseWriter(newResponseWriter); JSF.renderChild(facesContext, component); if (oldResponseWriter != null) { facesContext.setResponseWriter(oldResponseWriter); } cacheingWriter.flush(); cacheingWriter.close(); return cacheingWriter.toString(); } Example 50 Project: bigtable-sql File: OverviewCtrl.java private void onReport() { try { DataScaleTableModel dstm = _overviewHolder.getDataScaleTable().getDataScaleTableModel(); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.println(""); pw.println(""); for( int i = 0; i < dstm.getRowCount(); i++ ) { DataScale dataScale = dstm.getDataScaleAt(i); pw.println("Column name " + dataScale.getColumn() +":"); pw.println(""); pw.println(""); ArrayList intervalReports = dataScale.getIntervalReports(); for( String toolTip : intervalReports ) { pw.println(""); } pw.println(""); pw.println("" + toolTip + ""); pw.println(); } pw.println(""); pw.println(""); pw.flush(); sw.flush(); pw.close(); sw.close(); Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard(); StringSelection data = new StringSelection(sw.getBuffer().toString()); clip.setContents(data, data); } catch(IOException e) { throw new RuntimeException(e); } } Example 51 Project: HR-WebServices-Examples-Java File: EchoBlockingWsaBasedClient.java public static void main(String[] args) throws Exception { Options options = new Options(); options.setTo(targetEPR); options.setTransportInProtocol(Constants.TRANSPORT_HTTP); //Blocking invocation via wsa mapping options.setAction("urn:echo"); ServiceClient sender = new ServiceClient(); sender.setOptions(options); OMElement result = sender.sendReceive(getBody()); StringWriter writer = new StringWriter(); result.serialize(writer); writer.flush(); System.out.println(writer.toString()); } Example 52 Project: nmonvisualizer File: BasicFormatter.java @Override public String format(LogRecord record) { StringWriter buffer = new StringWriter(256); buffer.append(format.format(record.getMillis())); buffer.append(" "); buffer.append(record.getLevel().getName()); buffer.append(" "); buffer.append(record.getSourceClassName()); buffer.append("."); buffer.append(record.getSourceMethodName()); buffer.append(": "); buffer.append(record.getMessage()); buffer.append("\n"); if (record.getThrown() != null) { PrintWriter pw = new PrintWriter(buffer); record.getThrown().printStackTrace(pw); pw.close(); } // else nothing since StringWriter.close() is a no-op return buffer.toString(); } Example 53 Project: genome-weaver-align File: SequenceBoundary.java public String toSAMHeader() { StringWriter buf = new StringWriter(); for (SequenceIndex each : index) { buf.append(String.format("@SQ\tSN:%s\tLN:%d\n", each.name, each.length)); } return buf.toString(); } Example 54 Project: airlift File: StaticFormatter.java @Override public String format(LogRecord record) { ZonedDateTime timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(record.getMillis()), SYSTEM_ZONE); StringWriter stringWriter = new StringWriter() .append(TIMESTAMP_FORMATTER.format(timestamp)) .append('\t') .append(Level.fromJulLevel(record.getLevel()).name()) .append('\t') .append(Thread.currentThread().getName()) .append('\t') .append(record.getLoggerName()) .append('\t') .append(record.getMessage()); if (record.getThrown() != null) { stringWriter.append('\n'); record.getThrown().printStackTrace(new PrintWriter(stringWriter)); stringWriter.append('\n'); } stringWriter.append('\n'); return stringWriter.toString(); } Example 55 Project: JerseyTest File: FormDataMultiPartReaderWriterTest.java private void checkEntity(String expected, BodyPartEntity entity) throws IOException { // Convert the raw bytes into a String InputStreamReader sr = new InputStreamReader(entity.getInputStream()); StringWriter sw = new StringWriter(); while (true) { int ch = sr.read(); if (ch < 0) { break; } sw.append((char) ch); } // Perform the comparison assertEquals(expected, sw.toString()); } Example 56 Project: galen File: XmlBuilder.java public void toXml(String indentation, StringWriter sw) { if (type == XmlNodeType.TEXT) { sw.append(StringEscapeUtils.escapeXml(name)); } else if (type == XmlNodeType.TEXT_UNESCAPED) { sw.append(name); } else { if (parent != null) { sw.append("\n"); } sw.append(indentation); sw.append("<"); sw.append(name); writeAttributes(sw); sw.append(">"); writeChildren(indentation + INDENTATION, sw); if (childNodes != null && childNodes.size() > 0 && !containsOnlyText()) { sw.append("\n"); sw.append(indentation); } sw.append(""); } } Example 57 Project: tapestry-facebook File: FBAsyncSupportImpl.java String initString() { String sep = ""; StringWriter s = new StringWriter(); //s.append("({"); if ( fbinit.getAppID() != null ) { s.append(sep); sep = ","; s.append("appId: '"); s.append(fbinit.getAppID()); s.append("'"); } if ( fbinit.getCookie() != null ) { s.append(sep); sep = ","; s.append("cookie: " + fbinit.getCookie()); } if ( fbinit.getLogging() != null ) { s.append(sep); sep = ","; s.append("logging: " + fbinit.getLogging()); } if ( fbinit.getStatus() != null ) { s.append(sep); sep = ","; s.append("status: " + fbinit.getStatus()); } if ( fbinit.getXfbml() != null ) { s.append(sep); sep = ","; s.append("xfbml: " + fbinit.getXfbml()); } return s.toString(); } Example 58 Project: android-platform-tools-base File: JarFileIssueRegistryTest.java public void testCached() throws Exception { File targetDir = Files.createTempDir(); File file1 = getTestfile(targetDir, "rules/appcompat.jar.data"); File file2 = getTestfile(targetDir, "apicheck/unsupported.jar.data"); assertTrue(file1.getPath(), file1.exists()); final StringWriter mLoggedWarnings = new StringWriter(); TestLintClient client = new TestLintClient() { @Override public void log(@NonNull Severity severity, @Nullable Throwable exception, @Nullable String format, @Nullable Object... args) { if (format != null) { mLoggedWarnings.append(String.format(format, args)); } } }; IssueRegistry registry1 = JarFileIssueRegistry.get(client, file1); IssueRegistry registry2 = JarFileIssueRegistry.get(client, new File(file1.getPath())); assertSame(registry1, registry2); IssueRegistry registry3 = JarFileIssueRegistry.get(client, file2); assertNotSame(registry1, registry3); assertEquals(1, registry1.getIssues().size()); assertEquals("AppCompatMethod", registry1.getIssues().get(0).getId()); assertEquals( "Custom lint rule jar " + file2.getPath() + " does not contain a valid " + "registry manifest key (Lint-Registry).\n" + "Either the custom jar is invalid, or it uses an outdated API not " + "supported this lint client", mLoggedWarnings.toString()); } Example 59 Project: Desktop File: MapStyle.java public void writeContent(final ITreeWriter writer, final Object object, final IExtension extension) throws IOException { final MapStyleModel mapStyleModel = (MapStyleModel) extension; final MapModel styleMap = mapStyleModel.getStyleMap(); final String el = System.getProperty("line.separator"); if (styleMap == null) { return; } final MapWriter mapWriter = Controller.getCurrentModeController().getMapController().getMapWriter(); final StringWriter sw = new StringWriter(); sw.append(el); sw.append(""); sw.append(el); final NodeModel rootNode = styleMap.getRootNode(); final boolean forceFormatting = Boolean.TRUE.equals(writer.getHint(MapWriter.WriterHint.FORCE_FORMATTING)); try { mapWriter.writeNodeAsXml(sw, rootNode, Mode.STYLE, true, true, forceFormatting); } catch (final IOException e) { e.printStackTrace(); } sw.append(""); sw.append(el); final XMLElement element = new XMLElement("hook"); saveExtension(extension, element); writer.addElement(sw.toString(), element); } Example 60 Project: appengine-java-vm-runtime File: VmRuntimeWebAppContext.java @Override public void log(String message, Throwable throwable) { StringWriter writer = new StringWriter(); writer.append("javax.servlet.ServletContext log: "); writer.append(message); if (throwable != null) { writer.append("\n"); throwable.printStackTrace(new PrintWriter(writer)); } LogRecord.Level logLevel = throwable == null ? LogRecord.Level.info : LogRecord.Level.error; ApiProxy.log(new ApiProxy.LogRecord(logLevel, System.currentTimeMillis() * 1000L, writer.toString())); } Example 61 Project: i2p.android.base File: PeersFragment.java public void update() { WebView wv = (WebView) getActivity().findViewById(R.id.peers_webview); wv.clearHistory(); // fixes having to hit back. CommSystemFacade comm = getCommSystem(); String data; if (comm != null) { StringWriter out = new StringWriter(32*1024); out.append(HEADER); try { comm.renderStatusHTML(out, "http://thiswontwork.i2p/peers", 0); out.append(FOOTER); data = out.toString().replaceAll("/themes", "themes"); } catch (IOException ioe) { data = HEADER + "Error: " + ioe + FOOTER; } } else { data = HEADER + "No peer data available. The router is not running." + FOOTER; } try { // wv.loadData(data, "text/html", "UTF-8"); // figure out a way to get /themes/console/images/outbound.png to load // String url = "file://" + _myDir + "/docs/"; String url = "file:///android_asset/"; wv.loadDataWithBaseURL(url, data, "text/html", "UTF-8", url); } catch (Exception e) { } } Example 62 Project: Curators-Workbench File: MdSecTypePropertySection.java String getXMLText(MdSecType mdSec) { StringWriter sw = new StringWriter(); try { EObject o = (EObject) mdSec.getMdWrap().getXmlData().getAny().getValue(0); Map options = new HashMap(); options.put(XMLResource.OPTION_ENCODING, "utf-8"); options.put(XMLResource.OPTION_LINE_WIDTH, new Integer(80)); options.put(XMLResource.OPTION_ROOT_OBJECTS, Collections.singletonList(o)); ((XMLResource) o.eResource()).save(sw, options); } catch (Exception ignored) { sw.append("failed to serialize XML for model object"); } return sw.toString(); } Example 63 Project: JFugue-for-Android File: TransformerImpl.java public String transformToString(ElemTemplateElement elem) throws TransformerException { ElemTemplateElement firstChild = elem.getFirstChildElem(); if(null == firstChild) return ""; if(elem.hasTextLitOnly() && m_optimizer) { return ((ElemTextLiteral)firstChild).getNodeValue(); } // Save the current result tree handler. SerializationHandler savedRTreeHandler = this.m_serializationHandler; // Create a Serializer object that will handle the SAX events // and build the ResultTreeFrag nodes. StringWriter sw = (StringWriter) m_stringWriterObjectPool.getInstance(); m_serializationHandler = (ToTextStream) m_textResultHandlerObjectPool.getInstance(); if (null == m_serializationHandler) { // if we didn't get one from the pool, go make a new one Serializer serializer = org.apache.xml.serializer.SerializerFactory.getSerializer( m_textformat.getProperties()); m_serializationHandler = (SerializationHandler) serializer; } m_serializationHandler.setTransformer(this); m_serializationHandler.setWriter(sw); String result; try { /* Don't call startDocument, the SerializationHandler will * generate its own internal startDocument call anyways */ // this.m_serializationHandler.startDocument(); // Do the transformation of the child elements. executeChildTemplates(elem, true); this.m_serializationHandler.endDocument(); result = sw.toString(); } catch (SAXException se) { throw new TransformerException(se); } finally { sw.getBuffer().setLength(0); try { sw.close(); } catch (Exception ioe){} m_stringWriterObjectPool.freeInstance(sw); m_serializationHandler.reset(); m_textResultHandlerObjectPool.freeInstance(m_serializationHandler); // Restore the previous result tree handler. m_serializationHandler = savedRTreeHandler; } return result; } Example 64 Project: CaptureJSP File: SwallowingJspRenderer.java public String render(String viewName, Map modelMap, Locale locale) throws IOException { String result = null; if(locale == null) { locale = Locale.getDefault(); } // These String objects are used to capture the output // of SwallowingHttpServletResponse StringWriter sout = new StringWriter(); StringBuffer sbuffer = sout.getBuffer(); // Set up a fake request and response. We need the mock response // so that we can create the Swallowing response HttpServletRequest request = new MockIncludedHttpServletRequest(); HttpServletResponse response = new MockHttpServletResponse(); HttpServletResponse swallowingResponse = new SwallowingHttpServletResponse(response, sout, "UTF-8"); // Use our own LocaleResolver here, or Spring will try to meddle with it LocaleResolver localeResolver = new JspLocaleResolver(); localeResolver.setLocale(request, swallowingResponse, locale); try { //Add the modelMap to the request as attributes addModelAsRequestAttributes(request, modelMap); // Push our LocaleResolver into the request request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, localeResolver); // Push our Locale into the request LocalizationContext localizationContext = new LocalizationContext(null, locale); request.setAttribute(Config.FMT_LOCALIZATION_CONTEXT+".request", localizationContext); request.setAttribute(Config.FMT_LOCALE, locale); // Make sure we are using UTF-8 for the rendered JSP swallowingResponse.setContentType("text/html; charset=utf-8"); // "include" the file (but not really an include) with the dispatcher // The resulting rendering will come out in swallowing response, // via sbuffer RequestDispatcher dispatcher = servletContext.getRequestDispatcher(viewResolver.urlForView(viewName)); dispatcher.include(request, swallowingResponse); result = sbuffer.toString(); } catch(Exception e) { throw new IOException(e); } return result; } Example 65 Project: AdminCMD-Bukkit File: LogFormatter.java @Override public String format(final LogRecord record) { final String[] arguments = new String[9]; // %L arguments[0] = record.getLevel().toString(); arguments[1] = record.getMessage(); // sometimes the message is empty, but there is a throwable if (arguments[1] == null || arguments[1].length() == 0) { final Throwable thrown = record.getThrown(); if (thrown != null) { arguments[1] = thrown.getMessage(); } } // %m arguments[1] = record.getMessage(); // %M if (record.getSourceMethodName() != null) { arguments[2] = record.getSourceMethodName(); } else { arguments[2] = "?"; } // %t final Date date = new Date(record.getMillis()); synchronized (dateFormat) { arguments[3] = dateFormat.format(date); } // %c if (record.getSourceClassName() != null) { arguments[4] = record.getSourceClassName(); } else { arguments[4] = "?"; } // %T arguments[5] = Integer.valueOf(record.getThreadID()).toString(); // %n arguments[6] = record.getLoggerName(); // %C final int start = arguments[4].lastIndexOf(".") + 1; if (start > 0 && start < arguments[4].length()) { arguments[7] = arguments[4].substring(start); } else { arguments[7] = arguments[4]; } // %E final Throwable throwable = record.getThrown(); if (throwable != null) { final StringWriter stringwriter = new StringWriter(); stringwriter.append("\n"); throwable.printStackTrace(new PrintWriter(stringwriter)); arguments[8] = stringwriter.toString(); } else { arguments[8] = ""; } synchronized (messageFormat) { return messageFormat.format(arguments); } } Example 66 Project: keycloak File: StackoverflowIdentityProvider.java public static final String unescapeHtml3(final String input) { if (input == null) return null; StringWriter writer = null; int len = input.length(); int i = 1; int st = 0; while (true) { // look for '&' while (i < len && input.charAt(i - 1) != '&') i++; if (i >= len) break; // found '&', look for ';' int j = i; while (j < len && j < i + MAX_ESCAPE + 1 && input.charAt(j) != ';') j++; if (j == len || j < i + MIN_ESCAPE || j == i + MAX_ESCAPE + 1) { i++; continue; } // found escape if (input.charAt(i) == '#') { // numeric escape int k = i + 1; int radix = 10; final char firstChar = input.charAt(k); if (firstChar == 'x' || firstChar == 'X') { k++; radix = 16; } try { int entityValue = Integer.parseInt(input.substring(k, j), radix); if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); if (entityValue > 0xFFFF) { final char[] chrs = Character.toChars(entityValue); writer.write(chrs[0]); writer.write(chrs[1]); } else { writer.write(entityValue); } } catch (NumberFormatException ex) { i++; continue; } } else { // named escape CharSequence value = lookupMap.get(input.substring(i, j)); if (value == null) { i++; continue; } if (writer == null) writer = new StringWriter(input.length()); writer.append(input.substring(st, i - 1)); writer.append(value); } // skip escape st = j + 1; i = st; } if (writer != null) { writer.append(input.substring(st, len)); return writer.toString(); } return input; } Ссылка на первоисточник: http://www.programcreek.com/java-api-examples/index.php?api=java.io.StringWriter
Комментарии (0)
  • популярные
  • новые
  • старые
Для того, что бы оставить комментарий вы должны авторизироваться
У этой страницы еще нет ни одного комментария