Java Code Examples for java.io.StringWriter
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/dbunit/.
Source file: DBUnitDataStateLogger.java

private DataDump createDataDump(final String path,final IDataSet dbContent) throws IOException, DataSetException { StringWriter stringWriter=new StringWriter(); FlatXmlDataSet.write(dbContent,stringWriter); DataDump dumpData=new DataDump(stringWriter.toString(),path); stringWriter.close(); return dumpData; }
Example 2
From project ajah, under directory /ajah-email/src/main/java/com/ajah/email/velocity/.
Source file: VelocityEmailMessage.java

/** * Constructs the message from the HTML template. * @see VelocityEngine#mergeTemplate(String,String,org.apache.velocity.context.Context,java.io.Writer) * @see com.ajah.email.EmailMessage#getHtml() * @return The output of the merged velocity template, if the text templateis null, will return null. */ @Override public String getHtml(){ if (StringUtils.isBlank(this.htmlTemplate)) { return null; } final VelocityContext context=new VelocityContext(this.model); final StringWriter w=new StringWriter(); this.velocityEngine.mergeTemplate(this.htmlTemplate,"UTF-8",context,w); return w.toString(); }
Example 3
From project apps-for-android, under directory /Translate/src/com/beust/android/translate/.
Source file: Entities.java

/** * <p> Escapes the characters in a <code>String</code>. </p> <p> For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return "&foo;" </p> * @param str The <code>String</code> to escape. * @return A new escaped <code>String</code>. */ public String escape(String str){ StringWriter stringWriter=createStringWriter(str); try { this.escape(stringWriter,str); } catch ( IOException e) { throw new RuntimeException(e); } return stringWriter.toString(); }
Example 4
From project 2Degrees-Toolbox, under directory /Toolbox/src/biz/shadowservices/DegreesToolbox/.
Source file: HttpGetter.java

public String execute() throws ClientProtocolException, IOException { if (response == null) { HttpClient httpClient=HttpClientSingleton.getInstance(); HttpResponse serverresponse=null; serverresponse=httpClient.execute(httpget); HttpEntity entity=serverresponse.getEntity(); StringWriter writer=new StringWriter(); IOUtils.copy(entity.getContent(),writer); response=writer.toString(); } return response; }
Example 5
From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/generic/.
Source file: Utils.java

public static void log(String message,Throwable throwable){ if (throwable != null) { StringWriter sw; PrintWriter pw=new PrintWriter(sw=new StringWriter()); throwable.printStackTrace(pw); message=message + '\n' + sw; } log(message,System.err); }
Example 6
From project Aardvark, under directory /aardvark-core/src/test/java/gw/vark/.
Source file: AardvarkHelpModeTest.java

@Test public void printHelp(){ StringWriter writer=new StringWriter(); PrintWriter out=new PrintWriter(writer); AardvarkHelpMode.printHelp(out); String eol=System.getProperty("line.separator"); assertEquals("Usage:" + eol + " vark [-f FILE] [options] [targets...]"+ eol+ ""+ eol+ "Options:"+ eol+ " -f, -file FILE load a file-based Gosu source"+ eol+ " -url URL load a url-based Gosu source"+ eol+ " -classpath PATH additional elements for the classpath, separated by commas"+ eol+ " -p, -projecthelp show project help (e.g. targets)"+ eol+ " -logger LOGGERFQN class name for a logger to use"+ eol+ " -q, -quiet run with logging in quiet mode"+ eol+ " -v, -verbose run with logging in verbose mode"+ eol+ " -d, -debug run with logging in debug mode"+ eol+ " -g, -graphical starts the graphical Aardvark editor"+ eol+ " -verify verifies the Gosu source"+ eol+ " -version displays the version of Aardvark"+ eol+ " -h, -help displays this command-line help"+ eol+ "",writer.toString()); }
Example 7
From project action-core, under directory /src/main/java/com/ning/metrics/action/hdfs/data/.
Source file: Row.java

public String toJSON() throws IOException { final StringWriter s=new StringWriter(); final JsonGenerator generator=new JsonFactory().createJsonGenerator(s); generator.setPrettyPrinter(new DefaultPrettyPrinter()); toJSON(generator); generator.close(); return s.toString(); }
Example 8
From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.
Source file: LazyList.java

/** * Generates a XML document from content of this list. * @param spaces by how many spaces to indent. * @param declaration true to include XML declaration at the top * @param attrs list of attributes to include. No arguments == include all attributes. * @return generated XML. */ public String toXml(int spaces,boolean declaration,String... attrs){ String topNode=Inflector.pluralize(Inflector.underscore(metaModel.getModelClass().getSimpleName())); hydrate(); StringWriter sw=new StringWriter(); if (declaration) sw.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + (spaces > 0 ? "\n" : "")); sw.write("<" + topNode + ">"+ (spaces > 0 ? "\n" : "")); for ( T t : delegate) { sw.write(t.toXml(spaces,false,attrs)); } sw.write("</" + topNode + ">"+ (spaces > 0 ? "\n" : "")); return sw.toString(); }
Example 9
From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/.
Source file: MarshallingServiceImpl.java

public String marshallWorkflow(KickstartWorkflow kickstartWorkflow){ try { JAXBContext jaxbContext=JAXBContext.newInstance(Definitions.class); Marshaller marshaller=jaxbContext.createMarshaller(); StringWriter writer=new StringWriter(); marshaller.marshal(convertToBpmn(kickstartWorkflow),writer); return writer.toString(); } catch ( JAXBException e) { throw new RuntimeException("Could not marshal workflow",e); } }
Example 10
From project AdServing, under directory /modules/utilities/common/src/main/java/net/mad/ads/common/template/impl/freemarker/.
Source file: FMTemplateManager.java

public String processTemplate(String name,Map<String,Object> parameters) throws IOException { try { Template temp=templates.get(name); StringWriter sw=new StringWriter(); BufferedWriter bw=new BufferedWriter(sw); temp.process(parameters,bw); bw.flush(); return sw.toString(); } catch ( Exception e) { throw new IOException(e); } }
Example 11
From project agile, under directory /agile-framework/src/main/java/org/headsupdev/agile/framework/error/.
Source file: ErrorInternalPage.java

@SuppressWarnings({"ThrowableResultOfMethodCallIgnored"}) protected String getStack(){ if (getError() == null) { return "No stack provided"; } StringWriter writer=new StringWriter(); getError().printStackTrace(new PrintWriter(writer)); return writer.toString(); }
Example 12
From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/.
Source file: CreateTracking.java

@Override public String toString(){ if (this.createStr == null) { StringWriter sw=new StringWriter(); e.printStackTrace(new PrintWriter(sw)); this.createStr=sw.toString(); } return this.createStr; }
Example 13
From project android-client, under directory /xwiki-android-rest/src/org/xwiki/android/rest/.
Source file: AttachmentResources.java

/** * Generate XML content from the Attachments object * @param attachments Attachments Object to be serialized into XML * @return XML content of the provided Attachments object */ private String buildXmlAttachments(Attachments attachments){ Serializer serializer=new Persister(); StringWriter result=new StringWriter(); try { serializer.write(attachments,result); } catch ( Exception e) { e.printStackTrace(); } return result.toString(); }
Example 14
From project androidannotations, under directory /AndroidAnnotations/androidannotations/src/main/java/com/googlecode/androidannotations/.
Source file: AndroidAnnotationProcessor.java

private String stackTraceToString(Throwable e){ StringWriter writer=new StringWriter(); PrintWriter pw=new PrintWriter(writer); e.printStackTrace(pw); return writer.toString(); }
Example 15
From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/examples/.
Source file: AddressExample.java

public static void main(String[] args) throws IOException { CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE)); String[] nextLine; while ((nextLine=reader.readNext()) != null) { System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]"); } CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE)); List<String[]> allElements=reader2.readAll(); StringWriter sw=new StringWriter(); CSVWriter writer=new CSVWriter(sw); writer.writeAll(allElements); System.out.println("\n\nGenerated CSV File:\n\n"); System.out.println(sw.toString()); }
Example 16
From project ANNIS, under directory /annis-service/src/main/java/annis/ql/parser/.
Source file: AnnisParser.java

public static String dumpTree(Start start){ try { StringWriter result=new StringWriter(); start.apply(new TreeDumper(new PrintWriter(result))); return result.toString(); } catch ( RuntimeException e) { String errorMessage="could not serialize syntax tree"; log.warn(errorMessage,e); return errorMessage; } }
Example 17
From project ant4eclipse, under directory /org.ant4eclipse.ant.core/src/org/ant4eclipse/ant/core/.
Source file: AbstractAnt4EclipseTask.java

/** * Delegates to the <code>doExecute()</code> method where the actual task logic should be implemented. */ @Override public final void execute() throws BuildException { try { AbstractAnt4EclipseDataType.validateAll(); preconditions(); doExecute(); } catch ( Exception ex) { StringWriter sw=new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); A4ELogging.error("Execute of %s failed: %s%n%s",getClass().getName(),ex,sw); throw new BuildException(ex.toString(),ex); } }
Example 18
From project any23, under directory /core/src/test/java/org/apache/any23/extractor/html/.
Source file: AbstractExtractorTestCase.java

/** * Dumps the extracted model in <i>Turtle</i> format. * @return a string containing the model in Turtle. * @throws RepositoryException */ protected String dumpModelToTurtle() throws RepositoryException { StringWriter w=new StringWriter(); try { conn.export(Rio.createWriter(RDFFormat.TURTLE,w)); return w.toString(); } catch ( RDFHandlerException ex) { throw new RuntimeException(ex); } }
Example 19
From project apb, under directory /modules/apb-base/src/apb/utils/.
Source file: StringUtils.java

public static String getStackTrace(Throwable t){ StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw,true); t.printStackTrace(pw); pw.flush(); pw.close(); return sw.toString(); }
Example 20
From project api-sdk-java, under directory /api-sdk/src/main/java/com/smartling/api/sdk/file/.
Source file: FileApiClientAdapterImpl.java

private StringResponse inputStreamToString(InputStream inputStream,String encoding) throws FileApiException { StringWriter writer=new StringWriter(); try { String responseEncoding=(null == encoding || !encoding.toUpperCase().contains(UTF_16) ? DEFAULT_ENCODING : UTF_16); IOUtils.copy(inputStream,writer,responseEncoding); return new StringResponse(writer.toString(),responseEncoding); } catch ( IOException e) { throw new FileApiException(e); } }
Example 21
From project ardverk-commons, under directory /src/main/java/org/ardverk/lang/.
Source file: ExceptionUtils.java

public static String toString(Throwable t){ if (t == null) { return null; } StringWriter out=new StringWriter(); PrintWriter pw=new PrintWriter(out); t.printStackTrace(pw); pw.close(); return out.toString(); }
Example 22
From project Arecibo, under directory /event/src/main/java/com/ning/arecibo/event/transport/.
Source file: EventSerializerUDPUtil.java

public static byte[] toUDPPacket(Map<String,String> headers,Event event,EventSerializer serializer) throws IOException { byte[] payload=toByteArray(serializer,event); StringWriter sw=new StringWriter(); for ( Map.Entry<String,String> entry : headers.entrySet()) { sw.write(String.format("%s: %s\n",entry.getKey(),entry.getValue())); } byte[] top=sw.toString().getBytes(); byte[] packet=new byte[top.length + payload.length + 2]; packet[1]=(byte)(top.length >>> 0); packet[0]=(byte)(top.length >>> 8); System.arraycopy(top,0,packet,2,top.length); System.arraycopy(payload,0,packet,top.length + 2,payload.length); return packet; }
Example 23
From project arquillian-graphene, under directory /graphene-selenium/graphene-selenium-api/src/main/java/org/jboss/arquillian/ajocado/javascript/.
Source file: JavaScript.java

private static String inputStreamToString(InputStream inputStream) throws IOException { StringWriter output=new StringWriter(); InputStreamReader input=new InputStreamReader(inputStream); char[] buffer=new char[DEFAULT_BUFFER_SIZE]; int n=0; while (-1 != (n=input.read(buffer))) { output.write(buffer,0,n); } return output.toString(); }
Example 24
From project as3-commons-jasblocks, under directory /src/main/java/org/as3commons/asblocks/impl/.
Source file: ASTUtils.java

public static String print(IASCompilationUnit unit){ StringWriter writer=new StringWriter(); try { new ASFactory().newWriter().write(writer,unit); } catch ( IOException e) { } return writer.toString(); }
Example 25
From project autopsy, under directory /thirdparty/pasco2/src/isi/pasco2/model/.
Source file: UnknownRecord.java

public String toString(){ StringWriter output=new StringWriter(); output.write("Unknown record type at offset: " + Integer.toHexString(offset) + "\r\n"); output.write(HexFormatter.convertBytesToString(record)); output.write("\r\n"); return output.toString(); }
Example 26
From project avro, under directory /lang/java/avro/src/main/java/org/apache/avro/.
Source file: Protocol.java

public String toString(){ try { StringWriter writer=new StringWriter(); JsonGenerator gen=Schema.FACTORY.createJsonGenerator(writer); toJson(gen); gen.flush(); return writer.toString(); } catch ( IOException e) { throw new AvroRuntimeException(e); } }
Example 27
From project azkaban, under directory /azkaban-common/src/java/azkaban/common/utils/.
Source file: Utils.java

public static String stackTrace(Throwable t){ if (t == null) { return "Utils.stackTrace(...) -- Throwable was null."; } StringWriter writer=new StringWriter(); t.printStackTrace(new PrintWriter(writer)); return writer.toString(); }
Example 28
From project b3log-latke, under directory /latke/src/main/java/org/b3log/latke/servlet/renderer/freemarker/.
Source file: AbstractFreeMarkerRenderer.java

/** * Processes the specified FreeMarker template with the specified request, data model. * @param request the specified request * @param dataModel the specified data model * @param template the specified FreeMarker template * @return generated HTML * @throws Exception exception */ protected String genHTML(final HttpServletRequest request,final Map<String,Object> dataModel,final Template template) throws Exception { final StringWriter stringWriter=new StringWriter(); template.setOutputEncoding("UTF-8"); template.process(dataModel,stringWriter); final StringBuilder pageContentBuilder=new StringBuilder(stringWriter.toString()); final long endimeMillis=System.currentTimeMillis(); final String dateString=DateFormatUtils.format(endimeMillis,"yyyy/MM/dd HH:mm:ss"); final long startTimeMillis=(Long)request.getAttribute(Keys.HttpRequest.START_TIME_MILLIS); final String msg=String.format("<!-- Generated by B3log Latke(%1$d ms), %2$s -->",endimeMillis - startTimeMillis,dateString); pageContentBuilder.append(msg); final String ret=pageContentBuilder.toString(); request.setAttribute(PageCaches.CACHED_CONTENT,ret); return ret; }
Example 29
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/util/.
Source file: Markdowns.java

/** * Converts the specified markdown text to HTML. * @param markdownText the specified markdown text * @return converted HTML, returns {@code null} if the specified markdown text is "" or {@code null} * @throws Exception exception */ public static String toHTML(final String markdownText) throws Exception { if (Strings.isEmptyOrNull(markdownText)) { return null; } final StringWriter writer=new StringWriter(); final Markdown markdown=new Markdown(); markdown.transform(new StringReader(markdownText),writer); return writer.toString(); }
Example 30
public static String toString(Throwable t){ StringWriter stringWriter=new StringWriter(); PrintWriter printWriter=new PrintWriter(stringWriter); t.printStackTrace(printWriter); printWriter.close(); return stringWriter.toString(); }
Example 31
From project big-data-plugin, under directory /shims/common/src/org/pentaho/hadoop/shim/common/.
Source file: CommonPigShim.java

@Override public String substituteParameters(URL pigScript,List<String> paramList) throws IOException, ParseException { final InputStream inStream=pigScript.openStream(); StringWriter writer=new StringWriter(); ParameterSubstitutionPreprocessor psp=new ParameterSubstitutionPreprocessor(50); psp.genSubstitutedFile(new BufferedReader(new InputStreamReader(inStream)),writer,paramList.size() > 0 ? paramList.toArray(EMPTY_STRING_ARRAY) : null,null); return writer.toString(); }
Example 32
From project Bio-PEPA, under directory /uk.ac.ed.inf.biopepa.ui/lib/opencsv-2.1/examples/.
Source file: AddressExample.java

public static void main(String[] args) throws IOException { CSVReader reader=new CSVReader(new FileReader(ADDRESS_FILE)); String[] nextLine; while ((nextLine=reader.readNext()) != null) { System.out.println("Name: [" + nextLine[0] + "]\nAddress: ["+ nextLine[1]+ "]\nEmail: ["+ nextLine[2]+ "]"); } CSVReader reader2=new CSVReader(new FileReader(ADDRESS_FILE)); List<String[]> allElements=reader2.readAll(); StringWriter sw=new StringWriter(); CSVWriter writer=new CSVWriter(sw); writer.writeAll(allElements); System.out.println("\n\nGenerated CSV File:\n\n"); System.out.println(sw.toString()); }
Example 33
From project bioclipse.opentox, under directory /plugins/net.bioclipse.opentox/src/net/bioclipse/opentox/api/.
Source file: Dataset.java

public static void addMolecule(String datasetURI,IMolecule mol) throws Exception { StringWriter strWriter=new StringWriter(); SDFWriter writer=new SDFWriter(strWriter); writer.write(cdk.asCDKMolecule(mol).getAtomContainer()); writer.close(); addMolecules(datasetURI,strWriter.toString(),null); }
Example 34
From project bioclipse.speclipse, under directory /plugins/net.bioclipse.spectrum/src/spok/utils/.
Source file: SpectrumUtils.java

public static Element readJCampDict() throws ValidityException, ParsingException, IOException { Builder builder=new Builder(); URL varPluginUrl=Platform.getBundle("net.bioclipse.cml").getEntry("/dict10/simple/"); String varInstallPath=null; try { varInstallPath=Platform.asLocalURL(varPluginUrl).getFile(); } catch ( IOException e) { StringWriter strWr=new StringWriter(); PrintWriter prWr=new PrintWriter(strWr); } Document jcampDict=builder.build(varInstallPath + "jcampDXDict.xml"); return jcampDict.getRootElement(); }
Example 35
From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.
Source file: WindowForView.java

@Override public String toString(){ StringWriter sw=new StringWriter(getContentLength() >= 0 ? getContentLength() : 16); PrintWriter out=new PrintWriter(sw); try { render(out); } catch ( IOException e) { e.printStackTrace(out); } out.flush(); return sw.getBuffer().toString(); }
Example 36
From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.
Source file: PoolUtil.java

/** * For backwards compatibility with JDK1.5 (SQLException doesn't accept the original exception). * @param t exception * @return printStackTrace converted to a string */ public static String stringifyException(Throwable t){ StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); t.printStackTrace(pw); String result=""; result="------\r\n" + sw.toString() + "------\r\n"; return result; }
Example 37
From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/model/test/data/.
Source file: DataSpecification.java

protected String expandTemplateToString(VelocityContextProvider context,String template) throws DataSourceException { Context velocityCtx=CLONER.deepClone(context.createVelocityContext()); velocityCtx.put("xpath",new XPathTool(getNamespaceContext())); velocityCtx.put("printer",new XMLPrinterTool()); StringWriter writer=new StringWriter(); Velocity.evaluate(velocityCtx,writer,"expandTemplate",template); return writer.toString(); }
Example 38
From project BPMN2-Editor-for-Eclipse, under directory /org.eclipse.bpmn2.modeler.ui/src/org/eclipse/bpmn2/modeler/ui/wizards/.
Source file: FileService.java

private static String getExceptionAsString(Throwable t){ final StringWriter stringWriter=new StringWriter(); final PrintWriter printWriter=new PrintWriter(stringWriter); t.printStackTrace(printWriter); final String result=stringWriter.toString(); try { stringWriter.close(); } catch ( final IOException e) { } printWriter.close(); return result; }
Example 39
From project build-info, under directory /build-info-client/src/main/java/org/jfrog/build/client/.
Source file: ArtifactoryBuildInfoClient.java

String toJsonString(Object object) throws IOException { JsonFactory jsonFactory=httpClient.createJsonFactory(); StringWriter writer=new StringWriter(); JsonGenerator jsonGenerator=jsonFactory.createJsonGenerator(writer); jsonGenerator.useDefaultPrettyPrinter(); jsonGenerator.writeObject(object); String result=writer.getBuffer().toString(); return result; }
Example 40
From project byteman, under directory /agent/src/main/java/org/jboss/byteman/agent/.
Source file: RuleScript.java

public String toString(){ StringWriter stringWriter=new StringWriter(); PrintWriter writer=new PrintWriter(stringWriter); writeTo(writer); writer.flush(); return stringWriter.toString(); }
Example 41
From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/writer/.
Source file: C24ItemWriter.java

/** * Writes the contents of the StringWriter to our output file * @param writer The StringWriter to read the data from */ private void write(Sink sink) throws IOException { StringWriter writer=(StringWriter)sink.getWriter(); writer.flush(); StringBuffer buffer=writer.getBuffer(); String element=buffer.toString(); Writer outputWriter=writerSource.getWriter(); synchronized (outputWriter) { outputWriter.write(element); } buffer.setLength(0); }
Example 42
/** * Handy function to get a loggable stack trace from a Throwable * @param tr An exception to log */ public static String getStackTraceString(Throwable tr){ if (tr == null) { return ""; } StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); tr.printStackTrace(pw); return sw.toString(); }
Example 43
From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.
Source file: ScreenScrapingService.java

/** * Get portlet-specific XML for clean, valid HTML. * @param cleanHtml * @return * @throws TransformerException * @throws IOException */ protected String getXml(String cleanHtml) throws TransformerException, IOException { final StreamSource xsltSource=new StreamSource(xslt.getInputStream()); final Transformer identityTransformer=transformerFactory.newTransformer(xsltSource); identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); final StringWriter outputWriter=new StringWriter(); final StreamResult outputTarget=new StreamResult(outputWriter); final StreamSource xmlSource=new StreamSource(new StringReader(cleanHtml)); identityTransformer.transform(xmlSource,outputTarget); final String content=outputWriter.toString(); return content; }
Example 44
From project candlepin, under directory /src/test/java/org/candlepin/audit/.
Source file: ListenerWrapperTest.java

private String eventJson() throws Exception { StringWriter sw=new StringWriter(); Event e=new Event(); e.setId("10"); e.setConsumerId("20"); e.setPrincipal(new PrincipalData("5678","910112")); mapper.writeValue(sw,e); return sw.toString(); }
Example 45
From project capedwarf-blue, under directory /datastore/src/main/java/org/jboss/capedwarf/datastore/query/.
Source file: Projections.java

/** * Store bridges to document. * @param document the Lucene document */ void finish(Document document){ try { StringWriter writer=new StringWriter(); bridges.store(writer,null); document.add(new Field(TYPES_FIELD,writer.toString(),Field.Store.YES,Field.Index.NO)); } catch ( IOException e) { throw new IllegalArgumentException("Cannot store bridges!",e); } }
Example 46
From project Carnivore, under directory /net/sourceforge/jpcap/util/.
Source file: AsciiHelper.java

/** * Returns a text representation of a byte array. Bytes in the array which don't convert to text in the range a..Z are dropped. * @param bytes a byte array * @return a string containing the text equivalent of the bytes. */ public static String toText(byte[] bytes){ StringWriter sw=new StringWriter(); int length=bytes.length; if (length > 0) { for (int i=0; i < length; i++) { byte b=bytes[i]; if (b > 64 && b < 91 || b > 96 && b < 123) sw.write((char)b); } } return (sw.toString()); }
Example 47
From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/util/.
Source file: SOAPUtil.java

public static String getString(SOAPMessage msg){ StringWriter w=new StringWriter(); StreamResult result=new StreamResult(w); print(msg,result); w.flush(); return w.toString(); }
Example 48
From project cas, under directory /cas-server-core/src/main/java/org/jasig/cas/util/.
Source file: SamlUtils.java

private static org.w3c.dom.Document toDom(final Document doc){ try { final XMLOutputter xmlOutputter=new XMLOutputter(); final StringWriter elemStrWriter=new StringWriter(); xmlOutputter.output(doc,elemStrWriter); final byte[] xmlBytes=elemStrWriter.toString().getBytes(); final DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); return dbf.newDocumentBuilder().parse(new ByteArrayInputStream(xmlBytes)); } catch ( final Exception e) { return null; } }
Example 49
From project cascading, under directory /src/xml/cascading/operation/xml/.
Source file: XPathOperation.java

protected String writeAsXML(Node node){ StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); Source source=new DOMSource(node); try { getTransformer().transform(source,result); } catch ( TransformerException exception) { throw new OperationException("writing to xml failed",exception); } return stringWriter.toString(); }
Example 50
From project cdk, under directory /attributes/src/test/java/org/richfaces/cdk/attributes/.
Source file: AttributesTest.java

private String marshal(SchemaSet schemaSet) throws Exception { StringWriter writer=new StringWriter(); JAXBContext jc=JAXBContext.newInstance(SchemaSet.class); Marshaller marshaller=jc.createMarshaller(); marshaller.setProperty("jaxb.formatted.output",Boolean.TRUE); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); marshaller.marshal(schemaSet,new StreamResult(writer)); return writer.toString(); }
Example 51
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: DataManagement.java

/** * Based on http://www.vogella.de/articles/RSSFeed/article.html */ private String generateRSS(AppUserInfo user,BaseReportInfo report,List<DataRowInfo> reportDataRows) throws XMLStreamException, ObjectNotFoundException { XMLOutputFactory outputFactory=XMLOutputFactory.newInstance(); StringWriter stringWriter=new StringWriter(); XMLEventWriter eventWriter=outputFactory.createXMLEventWriter(stringWriter); XMLEventFactory eventFactory=XMLEventFactory.newInstance(); XMLEvent end=eventFactory.createDTD("\n"); StartDocument startDocument=eventFactory.createStartDocument(); eventWriter.add(startDocument); eventWriter.add(end); StartElement rssStart=eventFactory.createStartElement("","","rss"); eventWriter.add(rssStart); eventWriter.add(eventFactory.createAttribute("version","2.0")); eventWriter.add(end); eventWriter.add(eventFactory.createStartElement("","","channel")); eventWriter.add(end); this.createNode(eventWriter,"title",report.getModule().getModuleName() + " - " + report.getReportName()); String reportLink="https://appserver.gtportalbase.com/agileBase/AppController.servlet?return=gui/display_application&set_table=" + report.getParentTable().getInternalTableName() + "&set_report="+ report.getInternalReportName(); this.createNode(eventWriter,"link",reportLink); this.createNode(eventWriter,"description","A live data feed from www.agilebase.co.uk"); DateFormat dateFormatter=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); Date lastDataChangeDate=new Date(getLastCompanyDataChangeTime(user.getCompany())); this.createNode(eventWriter,"pubdate",dateFormatter.format(lastDataChangeDate)); for ( DataRowInfo reportDataRow : reportDataRows) { eventWriter.add(eventFactory.createStartElement("","","item")); eventWriter.add(end); this.createNode(eventWriter,"title",buildEventTitle(report,reportDataRow,false)); this.createNode(eventWriter,"description",reportDataRow.toString()); String rowLink=reportLink + "&set_row_id=" + reportDataRow.getRowId(); this.createNode(eventWriter,"link",rowLink); this.createNode(eventWriter,"guid",rowLink); eventWriter.add(end); eventWriter.add(eventFactory.createEndElement("","","item")); eventWriter.add(end); } eventWriter.add(eventFactory.createEndElement("","","channel")); eventWriter.add(end); eventWriter.add(eventFactory.createEndElement("","","rss")); eventWriter.add(end); return stringWriter.toString(); }
Example 52
From project AirReceiver, under directory /src/main/java/org/phlo/AirReceiver/.
Source file: LogFormatter.java

@Override public String format(final LogRecord record){ final StringBuilder s=new StringBuilder(); s.append(DateFormater.format(new Date(record.getMillis()))); s.append(" "); s.append(record.getLevel() != null ? record.getLevel().getName() : "?"); s.append(" "); s.append(record.getLoggerName() != null ? record.getLoggerName() : ""); s.append(" "); s.append(record.getMessage() != null ? record.getMessage() : ""); if (record.getThrown() != null) { String stackTrace; { final Throwable throwable=record.getThrown(); final StringWriter stringWriter=new StringWriter(); final PrintWriter stringPrintWriter=new PrintWriter(stringWriter); throwable.printStackTrace(stringPrintWriter); stringPrintWriter.flush(); stackTrace=stringWriter.toString(); } s.append(String.format("%n")); s.append(stackTrace); } s.append(String.format("%n")); return s.toString(); }
Example 53
From project android-bankdroid, under directory /src/com/liato/bankdroid/banking/banks/.
Source file: Rikslunchen.java

@Override protected LoginPackage preLogin() throws BankException, ClientProtocolException, IOException { urlopen=new Urllib(true,true); List<NameValuePair> postData=new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("c0-param0","string:" + password)); postData.add(new BasicNameValuePair("callCount","1")); postData.add(new BasicNameValuePair("windowName","")); postData.add(new BasicNameValuePair("c0-scriptName","cardUtil")); postData.add(new BasicNameValuePair("c0-methodName","getCardData")); postData.add(new BasicNameValuePair("c0-id","0")); postData.add(new BasicNameValuePair("batchId","1")); postData.add(new BasicNameValuePair("page","%2Friks-cp%2Fcheck_balance.html")); postData.add(new BasicNameValuePair("httpSessionId","")); postData.add(new BasicNameValuePair("scriptSessionId","")); HttpClient httpclient=new DefaultHttpClient(); HttpPost httppost=new HttpPost("http://www.rikslunchen.se/riks-cp/dwr/call/plaincall/cardUtil.getCardData.dwr"); httppost.setEntity(new UrlEncodedFormEntity(postData)); HttpResponse response=httpclient.execute(httppost); InputStream streamResponse=response.getEntity().getContent(); StringWriter writer=new StringWriter(); IOUtils.copy(streamResponse,writer); return new LoginPackage(urlopen,postData,writer.toString(),"http://www.rikslunchen.se/riks-cp/dwr/call/plaincall/cardUtil.getCardData.dwr"); }
Example 54
From project Android-Flashcards, under directory /src/com/secretsockssoftware/androidflashcards/filters/.
Source file: CSVColFilter.java

public String filterLine(String in,int lineNum){ try { String[] toks=parser.parseLine(in); if (rowTest != null && !rowTest.keepRow(toks)) return null; for (int i=0, j=0; i < outRow.length; j++) if ((keepMask & (1 << j)) != 0) if (outOrder != null) outRow[outOrder[i++]]=toks[j]; else outRow[i++]=toks[j]; StringWriter sw=new StringWriter(); CSVWriter cw=new CSVWriter(sw); cw.writeNext(outRow); return sw.toString(); } catch ( Exception e) { return null; } }
Example 55
From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/synchronisation/tracks/.
Source file: ContextSynchronizer.java

@Override protected String createDocumentForEntity(Context localContext){ XmlSerializer serializer=Xml.newSerializer(); StringWriter writer=new StringWriter(); try { serializer.setOutput(writer); String now=DateUtils.formatIso8601Date(System.currentTimeMillis()); serializer.startTag("","context"); serializer.startTag("","created-at").attribute("","type","datetime").text(now).endTag("","created-at"); serializer.startTag("","hide").attribute("","type","boolean").text("false").endTag("","hide"); serializer.startTag("","name").text(localContext.getName()).endTag("","name"); serializer.startTag("","position").attribute("","type","integer").text("12").endTag("","position"); serializer.startTag("","updated-at").attribute("","type","datetime").text(now).endTag("","updated-at"); serializer.endTag("","context"); serializer.flush(); } catch ( IOException ignored) { } return writer.toString(); }
Example 56
private String serialize(Element e,int intent){ try { XmlSerializer s=Xml.newSerializer(); StringWriter sw=new StringWriter(); s.setOutput(sw); s.startDocument("utf-8",null); String spaces=null; if (intent > 0) { char[] chars=new char[intent]; Arrays.fill(chars,' '); spaces=new String(chars); } serialize(root,s,0,spaces); s.endDocument(); return sw.toString(); } catch ( Exception ex) { ex.printStackTrace(); } return null; }
Example 57
From project asadmin, under directory /asadmin-java/src/main/java/org/n0pe/asadmin/commands/.
Source file: CreateAuthRealm.java

public String[] getParameters(){ if (StringUtils.isEmpty(className)) { throw new IllegalStateException(); } final String[] params; if (properties != null && !properties.isEmpty()) { final StringWriter sw=new StringWriter(); String key; for (final Iterator it=properties.keySet().iterator(); it.hasNext(); ) { key=(String)it.next(); sw.append(key).append("=").append(Util.quoteCommandArgument((String)properties.get(key))); if (it.hasNext()) { sw.append(":"); } } params=new String[]{CLASSNAME_OPT,className,PROPERTY_OPT,sw.toString(),realmName}; } else { params=new String[]{CLASSNAME_OPT,className,realmName}; } return params; }
Example 58
From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.
Source file: OrderbookExternalListener.java

private void doHandle(TradeExecutedEvent event) throws IOException { String jsonObjectAsString=createJsonInString(event); HttpPost post=new HttpPost(remoteServerUri); post.setEntity(new StringEntity(jsonObjectAsString)); post.addHeader("Content-Type","application/json"); HttpClient client=new DefaultHttpClient(); HttpResponse response=client.execute(post); if (response.getStatusLine().getStatusCode() != 200) { Writer writer=new StringWriter(); IOUtils.copy(response.getEntity().getContent(),writer); logger.warn("Error while sending event to external system: {}",writer.toString()); } }
Example 59
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.
Source file: ErrorDisplayer.java

private static String StackStraceTostring(Exception e){ try { final Writer result=new StringWriter(); final PrintWriter printWriter=new PrintWriter(result); e.printStackTrace(printWriter); return result.toString(); } catch ( Exception ex) { ex.printStackTrace(); } return ""; }
Example 60
From project BHT-FPA, under directory /mailer-common/de.bht.fpa.mail.common/src/de/bht/fpa/mail/s000000/common/internal/.
Source file: Activator.java

/** * Logs an {@link Exception} to the eclipse workbench. * @param e the {@link Exception} to log */ public static void logException(Exception e){ if (getInstance() == null) { final Writer result=new StringWriter(); e.printStackTrace(new PrintWriter(result)); System.err.println(result.toString()); } else { getInstance().getLog().log(new Status(IStatus.ERROR,Activator.PLUGIN_ID,-1,e.getMessage(),e)); } }
Example 61
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.
Source file: PubchemStructureGenerator.java

/** * convert an XML {@link Document} into a {@link String}. * @return String containg the document. */ private static String getXMLString(Document requestDocument){ try { TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(requestDocument); StringWriter stringWriter=new StringWriter(); StreamResult streamResult=new StreamResult(stringWriter); transformer.transform(source,streamResult); return stringWriter.toString(); } catch ( Exception e) { e.printStackTrace(); return ""; } }
Example 62
From project bioportal-service, under directory /src/test/java/edu/mayo/cts2/framework/plugin/service/bioportal/service/transform/.
Source file: AssociationTransformTest.java

@Before public void buildTransform() throws Exception { this.associationTransform=new AssociationTransform(); IdentityConverter idConverter=EasyMock.createMock(IdentityConverter.class); UrlConstructor urlConstructor=EasyMock.createNiceMock(UrlConstructor.class); EasyMock.expect(idConverter.ontologyIdToCodeSystemName("1104")).andReturn("testCsName").anyTimes(); EasyMock.expect(idConverter.ontologyVersionIdToCodeSystemVersionName("1104","44450")).andReturn("testCsVersionName").anyTimes(); EasyMock.expect(idConverter.getCodeSystemAbout("csName","http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes(); EasyMock.expect(idConverter.getCodeSystemAbout("ICD10","http://purl.bioontology.org/ontology/")).andReturn("http://test.doc.uri").anyTimes(); EasyMock.expect(idConverter.codeSystemVersionNameToVersion("ICD10")).andReturn("ICD10").anyTimes(); EasyMock.replay(idConverter,urlConstructor); this.associationTransform.setIdentityConverter(idConverter); this.associationTransform.setUrlConstructor(urlConstructor); Resource resource=new ClassPathResource("bioportalXml/entityDescription.xml"); StringWriter sw=new StringWriter(); IOUtils.copy(resource.getInputStream(),sw); this.xml=sw.toString(); }
Example 63
From project Birthdays, under directory /src/com/rexmenpara/birthdays/util/.
Source file: ErrorReportHandler.java

private String generateDebugReport(Throwable e){ String report=""; report+="-------------------------------\n\n"; report+="--------- Device ---------\n\n"; report+="Brand: " + Build.BRAND + "\n"; report+="Device: " + Build.DEVICE + "\n"; report+="Model: " + Build.MODEL + "\n"; report+="Id: " + Build.ID + "\n"; report+="Product: " + Build.PRODUCT + "\n"; report+="-------------------------------\n\n"; report+="--------- Firmware ---------\n\n"; report+="SDK: " + Build.VERSION.SDK + "\n"; report+="Release: " + Build.VERSION.RELEASE + "\n"; report+="Incremental: " + Build.VERSION.INCREMENTAL + "\n"; report+="-------------------------------\n\n"; report+="--------- Exception ---------\n\n"; report+="Message: " + e.getMessage() + "\n"; StringWriter sw=new StringWriter(); e.printStackTrace(new PrintWriter(sw)); String stacktrace=sw.toString(); report+="StackTrace: " + stacktrace + "\n"; report+="-------------------------------\n\n"; report+="--------- Cause ---------\n\n"; Throwable cause=e.getCause(); if (cause != null) { sw=new StringWriter(); cause.printStackTrace(new PrintWriter(sw)); stacktrace=sw.toString(); report+="Message: " + cause.getMessage() + "\n"; report+="StackTrace: " + cause.getStackTrace() + "\n"; report+="-------------------------------\n\n"; } return report; }
Example 64
From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.
Source file: WalletActivity.java

private void exportPrivateKeys(final String password){ try { Constants.EXTERNAL_WALLET_BACKUP_DIR.mkdirs(); final File file=new File(Constants.EXTERNAL_WALLET_BACKUP_DIR,Constants.EXTERNAL_WALLET_KEY_BACKUP + "-" + Iso8601Format.newDateFormat().format(new Date())); final Wallet wallet=getWalletApplication().getWallet(); final ArrayList<ECKey> keys=wallet.keychain; final StringWriter plainOut=new StringWriter(); WalletUtils.writeKeys(plainOut,keys); plainOut.close(); final String plainText=plainOut.toString(); final String cipherText=EncryptionUtils.encrypt(plainText,password.toCharArray()); final Writer cipherOut=new FileWriter(file); cipherOut.write(cipherText); cipherOut.close(); new AlertDialog.Builder(this).setInverseBackgroundForced(true).setMessage(getString(R.string.wallet_export_keys_dialog_success,file)).setNeutralButton(R.string.button_dismiss,null).show(); } catch ( final IOException x) { new AlertDialog.Builder(this).setInverseBackgroundForced(true).setIcon(android.R.drawable.ic_dialog_alert).setTitle(R.string.wallet_import_export_keys_dialog_failure_title).setMessage(getString(R.string.wallet_export_keys_dialog_failure,x.getMessage())).setNeutralButton(R.string.button_dismiss,null).show(); x.printStackTrace(); } }
Example 65
From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.
Source file: BlacktieStompAdministrationService.java

String printNode(Node node){ try { TransformerFactory transfac=TransformerFactory.newInstance(); Transformer trans=transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); trans.setOutputProperty(OutputKeys.INDENT,"yes"); StringWriter sw=new StringWriter(); StreamResult result=new StreamResult(sw); DOMSource source=new DOMSource(node); trans.transform(source,result); String xmlString=sw.toString(); return xmlString; } catch ( TransformerException e) { log.error(e); } return null; }
Example 66
From project BMach, under directory /src/jsyntaxpane/actions/.
Source file: XmlPrettifyAction.java

@Override public void actionPerformed(ActionEvent e){ if (transformer == null) { return; } JTextComponent target=getTextComponent(e); try { SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target); StringWriter out=new StringWriter(sdoc.getLength()); StringReader reader=new StringReader(target.getText()); InputSource src=new InputSource(reader); Document doc=getDocBuilder().parse(src); getTransformer().transform(new DOMSource(doc),new StreamResult(out)); target.setText(out.toString()); } catch ( SAXParseException ex) { showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber())); ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1); } catch ( TransformerException ex) { showErrorMessage(target,ex.getMessageAndLocation()); } catch ( SAXException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } catch ( IOException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } }
Example 67
private String getStackTrace(Throwable t){ if (t == null) { return "No exception trace is available"; } final Writer sw=new StringWriter(); final PrintWriter pw=new PrintWriter(sw); t.printStackTrace(pw); return sw.toString(); }
Example 68
From project Book-Catalogue, under directory /src/com/eleybourn/bookcatalogue/.
Source file: Logger.java

/** * Write the exception stacktrace to the error log file * @param e The exception to log */ public static void logError(Exception e,String msg){ DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date=new Date(); String now=dateFormat.format(date); StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); e.printStackTrace(pw); String error="An Exception Occured @ " + now + "\n"+ "In Phone "+ Build.MODEL+ " ("+ Build.VERSION.SDK_INT+ ") \n"+ msg+ "\n"+ sw.toString(); try { Log.e("BC Logger",error); BufferedWriter out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(StorageUtils.getErrorLog()),"utf8"),8192); out.write(error); out.close(); } catch ( Exception e1) { } }
Example 69
From project bundlemaker, under directory /main/org.bundlemaker.core/src/org/bundlemaker/core/internal/projectdescription/.
Source file: XmlProjectDescriptionExporterUtils.java

/** * <p> </p> * @param xmlProjectDescription * @param outputStream */ public static String marshal(XmlProjectDescriptionType xmlProjectDescription){ try { ProjectContentProviderExtension.getAllProjectContentProviderExtension(); JaxbCompoundClassLoader jaxbCompoundClassLoader=new JaxbCompoundClassLoader(); JAXBContext jaxbContext=JAXBContext.newInstance(jaxbCompoundClassLoader.getPackageString(),jaxbCompoundClassLoader.getCompoundClassLoader()); Marshaller marshaller=jaxbContext.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); StringWriter result=new StringWriter(); marshaller.marshal(new ObjectFactory().createXmlProjectDescription(xmlProjectDescription),result); return result.toString(); } catch ( Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage(),e); } }
Example 70
From project c3p0, under directory /src/java/com/mchange/v2/c3p0/stmt/.
Source file: GooGooStatementCache.java

public synchronized String dumpStatementCacheStatus(){ if (isClosed()) return this + "status: Closed."; else { StringWriter sw=new StringWriter(2048); IndentedWriter iw=new IndentedWriter(sw); try { iw.print(this); iw.println(" status:"); iw.upIndent(); iw.println("core stats:"); iw.upIndent(); iw.print("num cached statements: "); iw.println(this.countCachedStatements()); iw.print("num cached statements in use: "); iw.println(checkedOut.size()); iw.print("num connections with cached statements: "); iw.println(cxnStmtMgr.getNumConnectionsWithCachedStatements()); iw.downIndent(); iw.println("cached statement dump:"); iw.upIndent(); for (Iterator ii=cxnStmtMgr.connectionSet().iterator(); ii.hasNext(); ) { Connection pcon=(Connection)ii.next(); iw.print(pcon); iw.println(':'); iw.upIndent(); for (Iterator jj=cxnStmtMgr.statementSet(pcon).iterator(); jj.hasNext(); ) iw.println(jj.next()); iw.downIndent(); } iw.downIndent(); iw.downIndent(); return sw.toString(); } catch ( IOException e) { if (logger.isLoggable(MLevel.SEVERE)) logger.log(MLevel.SEVERE,"Huh? We've seen an IOException writing to s StringWriter?!",e); return e.toString(); } } }
Example 71
From project cascading-avro, under directory /cascading-avro-maven-plugin/src/test/java/com/maxpoint/cascading/avro/.
Source file: CascadingFieldsGeneratorTest.java

@Test public void testGenerate() throws Exception { final CascadingFieldsGenerator gen=new CascadingFieldsGenerator(); final Schema schema=getSchema(); final Writer writer=new StringWriter(); gen.generate(schema,writer); writer.close(); final String actual=writer.toString(); final String expected=Resources.toString(getClass().getResource("expected.txt"),Charsets.UTF_8); assertEquals(expected,actual); }
Example 72
From project CCR-Validator, under directory /src/main/java/org/openhealthdata/.
Source file: OpenHealthSimpleLogFormatter.java

@Override public String format(LogRecord record){ String loggerName=record.getLoggerName(); if (loggerName == null) { loggerName="root"; } StringBuilder output=new StringBuilder().append(loggerName).append("-").append(record.getSourceMethodName()).append("[").append(record.getLevel()).append('|').append(Thread.currentThread().getName()).append('|').append(format.format(new Date(record.getMillis()))).append("]: ").append(record.getMessage()).append(' ').append(lineSep); if (record.getThrown() != null) { try { StringWriter sw=new StringWriter(); PrintWriter pw=new PrintWriter(sw); record.getThrown().printStackTrace(pw); pw.close(); output.append(sw.toString()); } catch ( Exception ex) { } } return output.toString(); }
Example 73
From project Anki-Android, under directory /src/com/ichi2/anki/.
Source file: CustomExceptionHandler.java

@Override public void uncaughtException(Thread t,Throwable e){ Log.i(AnkiDroidApp.TAG,"uncaughtException"); collectInformation(); Date currentDate=new Date(); SimpleDateFormat df1=new SimpleDateFormat("EEE MMM dd HH:mm:ss ",Locale.US); SimpleDateFormat df2=new SimpleDateFormat(" yyyy",Locale.US); TimeZone tz=TimeZone.getDefault(); StringBuilder reportInformation=new StringBuilder(10000); reportInformation.append(String.format("Report Generated: %s%s%s\nBegin Collected Information\n\n",df1.format(currentDate),tz.getID(),df2.format(currentDate))); for ( String key : mInformation.keySet()) { String value=mInformation.get(key); reportInformation.append(String.format("%s = %s\n",key,value)); } reportInformation.append(String.format("End Collected Information\n\nBegin Stacktrace\n\n")); final Writer result=new StringWriter(); final PrintWriter printWriter=new PrintWriter(result); e.printStackTrace(printWriter); reportInformation.append(String.format("%s\n",result.toString())); reportInformation.append(String.format("End Stacktrace\n\nBegin Inner exceptions\n\n")); Throwable cause=e.getCause(); while (cause != null) { cause.printStackTrace(printWriter); reportInformation.append(String.format("%s\n",result.toString())); cause=cause.getCause(); } reportInformation.append(String.format("End Inner exceptions")); printWriter.close(); Log.i(AnkiDroidApp.TAG,"report infomation string created"); saveReportToFile(reportInformation.toString()); mPreviousHandler.uncaughtException(t,e); }
Example 74
From project airlift, under directory /dbpool/src/test/java/io/airlift/dbpool/.
Source file: ManagedDataSourceTest.java

@Test public void testLogWriterIsNeverSet() throws SQLException { MockConnectionPoolDataSource mockConnectionPoolDataSource=new MockConnectionPoolDataSource(); PrintWriter expectedLogWriter=new PrintWriter(new StringWriter()); mockConnectionPoolDataSource.logWriter=expectedLogWriter; ManagedDataSource dataSource=new MockManagedDataSource(mockConnectionPoolDataSource,1,new Duration(10,MILLISECONDS)); assertNull(dataSource.getLogWriter()); PrintWriter newWriter=new PrintWriter(new StringWriter()); dataSource.setLogWriter(newWriter); assertNull(dataSource.getLogWriter()); assertSame(mockConnectionPoolDataSource.logWriter,expectedLogWriter); }