Java Code Examples for java.io.Writer

The following are top voted examples for showing how to use java.io.Writer. 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 1
Project: jbosgi   File: WebBundleServlet.java View source code 7 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String bundleSource = "";
    ClassLoader classLoader = WebBundleServlet.class.getClassLoader();
    try {
        if (classLoader instanceof BundleReference) {
            Bundle bundle = ((BundleReference)classLoader).getBundle();
            bundleSource = " from " + bundle.getSymbolicName();
        }
    } catch (Throwable th) {
        // ignore because the plain war does not see the OSGi API
    }

    String msg = req.getParameter("input");
    Writer writer = resp.getWriter();
    writer.write(msg + bundleSource);
}
 
Example 2
Project: jentrata-msh   File: MessageListenerJMSClient.java View source code 6 votes vote down vote up
private String convertStreamToString(InputStream is) throws IOException {
	if (is != null) {
		Writer writer = new StringWriter();

		char[] buffer = new char[1024];
		try {
			Reader reader = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			int n;
			while ((n = reader.read(buffer)) != -1) {
				writer.write(buffer, 0, n);
			}
		} finally {
			is.close();
		}
		return writer.toString();
	} else {
		return "";
	}
}
 
Example 3
Project: 2014-sling-rookie-session   File: DiscussionComment.java View source code 6 votes vote down vote up
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
  Writer out = response.getWriter();

  // read comment via Sling Model
  Comment comment = request.getResource().adaptTo(Comment.class);

  // output comment as HTML
  out.write("<p>");
  out.write("<em>" + escapeHtml(comment.getAuthor())
      + " (" + DateFormat.getDateTimeInstance().format(comment.getCreated()) + ")</em><br/>");
  out.write(escapeHtml(comment.getText()));
  out.write("</p>");

}
 
Example 4
Project: apache-james-mime4j-groundhog   File: StringTextBody.java View source code 6 votes vote down vote up
@Override
public void writeTo(OutputStream out) throws IOException {
    if (out == null)
        throw new IllegalArgumentException();

    Reader reader = new StringReader(text);
    Writer writer = new OutputStreamWriter(out, charset);

    char buffer[] = new char[1024];
    while (true) {
        int nChars = reader.read(buffer);
        if (nChars == -1)
            break;

        writer.write(buffer, 0, nChars);
    }

    reader.close();
    writer.flush();
}
 
Example 5
Project: hitchfs   File: StubFileSystemTest.java View source code 6 votes vote down vote up
@Test
public void testGetWriter() throws Exception {
	String message = "fake file with text.";
	ByteArrayOutputStream out = new ByteArrayOutputStream(message.length());
	final MessageDigestOutputStream md5 = md5().setOutput(out);
	StubFileSystem fs = new StubFileSystem() {
		@Override
		public OutputStream getOutputStream(FakeFile fake, boolean append) throws IOException {
			return md5;
		}
	};
	FakeFile file = fs.file("fakedir/fakefile2.txt");
	Writer writer = fs.writer(file);
	writer.write(message);
	writer.close();
	assertEquals("9d2110c9a94894f10cfee35afaf8ceb2", md5.getDigestAsHex());
	assertEquals(message, new String(out.toByteArray()));
}
 
Example 6
Project: netlib   File: FileUtil.java View source code 6 votes vote down vote up
/**
 * Change the contents of text file in its entirety, overwriting any existing text.
 *
 * Do nothing in the case of an error.
 *     
 * @param file       file to write; not null
 * @param content    String to write; not null
 * @throws IOException 
 */
public void writeFile(File file, String content) throws IOException {
    Writer output = new BufferedWriter(new OutputStreamWriter(
            new FileOutputStream(file), FILE_CHARSET_NAME));
    try {
        output.write(content);
    } finally {
        output.close();
    }
}
 
Example 7
Project: virgo.kernel   File: NestedPlanIntegrationTests.java View source code 6 votes vote down vote up
public static TestPlanArtifactInfo createPlanFile(String planName, Version planVersion, boolean scoped, boolean atomic, TestArtifactInfo... children) throws IOException {
    StringBuffer planContent = new StringBuffer(1024);
    planContent.append(XML_HEADER);
    planContent.append("<plan name=\"" + planName + "\" version=\"" + planVersion + "\" scoped=\"" + new Boolean(scoped) + "\" atomic=\"" + new Boolean(atomic) + "\" \n" + NAMESPACES + ">\n");

    for (TestArtifactInfo childInfo : children) {
        Version childVersion = childInfo.getVersion();
        planContent.append("    <artifact type=\"" + childInfo.getType() + "\" name=\"" + childInfo.getName() + "\" version=\"[" + childVersion + ", " + childVersion + "]\"/>\n");
    }

    planContent.append("</plan>");

    TestPlanArtifactInfo info = new TestPlanArtifactInfo(planName, planVersion, scoped, atomic, children);

    String fileName = planName + "-" + planVersion + PLAN_EXTENSION;
    File planFile = new File(GENERATED_PLAN_DIRECTORY + fileName);
    Writer writer = new FileWriter(planFile);
    try {
        writer.write(planContent.toString());
    } finally {
        writer.close();
    }

    info.setFile(planFile);

    return info;
}
 
Example 8
Project: richfaces   File: JSONArray.java View source code 6 votes vote down vote up
/**
 * Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
 * <p/>
 * Warning: This method assumes that the data structure is acyclical.
 *
 * @return The writer.
 * @throws JSONException
 */
public Writer write(Writer writer) throws JSONException {
    try {
        boolean b = false;
        int len = length();

        writer.write('[');

        for (int i = 0; i < len; i += 1) {
            if (b) {
                writer.write(',');
            }

            Object v = this.myArrayList.get(i);

            if (v instanceof JSONObject) {
                ((JSONObject) v).write(writer);
            } else if (v instanceof JSONArray) {
                ((JSONArray) v).write(writer);
            } else {
                writer.write(JSONObject.valueToString(v));
            }

            b = true;
        }

        writer.write(']');

        return writer;
    } catch (IOException e) {
        throw new JSONException(e);
    }
}
 
Example 9
Project: netlib   File: TorHiddenServiceServerRemoteTest.java View source code 6 votes vote down vote up
/**
 * Handle one server-side connection of the hidden service.
 * Read the request and write a HTTP response.
 * 
 * @param netSocket    freshly opened connection to a (HTTP?) client
 * @throws Exception
 */
private void processOneServerSideConnection(NetSocket netSocket, String responseStr) throws Exception {
    // read the first request line
    BufferedReader reader = new BufferedReader(new InputStreamReader(netSocket.getInputStream()));
    log.info("TOR HIDDEN SERVICE - SERVER SIDE: wait for first line");
    String firstLine = reader.readLine();
    log.info("TOR HIDDEN SERVICE - SERVER SIDE: firstLine="+firstLine);

    // send response
    String response =
        "HTTP/1.1 200 OK\n\r"+
        "Content-Type: text/xml; charset=utf-8\n\r"+
        "\n\r"+
        "<html><body>This is my response\nwith two lines\n"+responseStr+"\ndate/time="+getCurrentTime()+"</body></html>";
    Writer writer = new OutputStreamWriter(netSocket.getOutputStream());
    writer.append(response);
    writer.flush();
    log.info("TOR HIDDEN SERVICE - SERVER SIDE: send response="+response);
    
    Thread.sleep(5000);
    
    writer.close();
    reader.close();
    netSocket.close();
}
 
Example 10
Project: jbosgi   File: SimpleServlet.java View source code 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Writer writer = resp.getWriter();
    XBundle bundle = (XBundle) context.getBundle();
    writer.write(bundle.getCanonicalName());
    writer.close();
}
 
Example 11
Project: phonegap-geolocation   File: DiskLruCache.java View source code 6 votes vote down vote up
/**
 * Creates a new journal that omits redundant information. This replaces the
 * current journal if it exists.
 */
private synchronized void rebuildJournal() throws IOException {
  if (journalWriter != null) {
    journalWriter.close();
  }

  Writer writer = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
  try {
    writer.write(MAGIC);
    writer.write("\n");
    writer.write(VERSION_1);
    writer.write("\n");
    writer.write(Integer.toString(appVersion));
    writer.write("\n");
    writer.write(Integer.toString(valueCount));
    writer.write("\n");
    writer.write("\n");

    for (Entry entry : lruEntries.values()) {
      if (entry.currentEditor != null) {
        writer.write(DIRTY + ' ' + entry.key + '\n');
      } else {
        writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
      }
    }
  } finally {
    writer.close();
  }

  if (journalFile.exists()) {
    renameTo(journalFile, journalFileBackup, true);
  }
  renameTo(journalFileTmp, journalFile, false);
  journalFileBackup.delete();

  journalWriter = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
}
 
Example 12
Project: webstart   File: AbstractGenerator.java View source code 6 votes vote down vote up
/**
 * Generate the JNLP file.
 *
 * @throws Exception
 */
public final void generate()
    throws Exception
{
    VelocityContext context = createAndPopulateContext();

    Writer writer = WriterFactory.newWriter( config.getOutputFile(), config.getEncoding() );

    try
    {
        velocityTemplate.merge( context, writer );
        writer.flush();
    }
    catch ( Exception e )
    {
        throw new Exception(
            "Could not generate the template " + velocityTemplate.getName() + ": " + e.getMessage(), e );
    }
    finally
    {
        writer.close();
    }

}
 
Example 13
Project: aipo   File: JetspeedContentAdmin.java View source code 6 votes vote down vote up
/**
Save this JCM (hopefully updated JCM) to disk.
*/
public synchronized void save() throws Exception {

    DiskCacheEntry  pde = JetspeedDiskCache.getInstance()
        .getEntry( this.url );
    Writer filewriter = pde.getWriter();
    this.content.marshal( filewriter );
    filewriter.close();

}
 
Example 14
Project: tio_patinhas   File: INIFile.java View source code 6 votes vote down vote up
/**
 * Helper function to close a writer object.
 * @param pobjWriter the writer to be closed.
 */
private void closeWriter(Writer pobjWriter)
{
    if (pobjWriter == null) return;

    try
    {
        pobjWriter.close();
    }
    catch (IOException IOExIgnore)
    {
    }
}
 
Example 15
Project: ilarkesto   File: IO.java View source code 6 votes vote down vote up
public static void close(Writer out) {
	if (out == null) return;
	try {
		out.close();
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 16
Project: XBatis-Code-Generator   File: CharsetConvert.java View source code 6 votes vote down vote up
/**
 * ??????
 * @param src ????
 * @param des ????
 * @return true or false
 */
private boolean copySingleFile(File src, File des){
	try {
		//??????
		if (!des.exists()) des.createNewFile();
		//??????
		Reader in = new BufferedReader(new InputStreamReader(new FileInputStream(src)));
		//?????????
		String encodingUse = ((encoding == null) ? DEFAULT_ENCODING : encoding);
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(des), encodingUse));
		//???????????????
		char[] buffer = new char[4096];
		int readBytes = -1;
		while ((readBytes = in.read(buffer)) != -1) {
			out.write(buffer, 0, readBytes);
		}
		//???????
		out.flush();
		out.close();
		in.close();
	} catch (IOException e) {
		logger.error("???????????????:", e);
		return false;
	}
	return true;
}
 
Example 17
Project: angularjs-navigation-master-detail   File: DiskLruCache.java View source code 6 votes vote down vote up
/**
 * Creates a new journal that omits redundant information. This replaces the
 * current journal if it exists.
 */
private synchronized void rebuildJournal() throws IOException {
  if (journalWriter != null) {
    journalWriter.close();
  }

  Writer writer = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII));
  try {
    writer.write(MAGIC);
    writer.write("\n");
    writer.write(VERSION_1);
    writer.write("\n");
    writer.write(Integer.toString(appVersion));
    writer.write("\n");
    writer.write(Integer.toString(valueCount));
    writer.write("\n");
    writer.write("\n");

    for (Entry entry : lruEntries.values()) {
      if (entry.currentEditor != null) {
        writer.write(DIRTY + ' ' + entry.key + '\n');
      } else {
        writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
      }
    }
  } finally {
    writer.close();
  }

  if (journalFile.exists()) {
    renameTo(journalFile, journalFileBackup, true);
  }
  renameTo(journalFileTmp, journalFile, false);
  journalFileBackup.delete();

  journalWriter = new BufferedWriter(
      new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII));
}
 
Example 18
Project: jentrata-msh   File: IOHandler.java View source code 6 votes vote down vote up
/**
 * Pipes a reader to a writer. 
 * 
 * @param reader the reader to be read.
 * @param writer the writer to be written.
 * @throws IOException if there is IO error occurred during the operation.
 */
public static void pipe(Reader reader, Writer writer) throws IOException {
    char[] buffer = new char[BUFFER_SIZE];

    int len = reader.read(buffer);
    while (len != -1) {
        writer.write(buffer, 0, len);
        len = reader.read(buffer);
    }
    writer.flush();
}
 
Example 19
Project: iswc2012metadata   File: ToolJena.java View source code 6 votes vote down vote up
public static boolean printModelToWriter(Model m, String sz_rdfsyntax, String sz_namespace, Writer out) throws IOException {
	if (null==m || null==out)
		return false;
	
	if (ToolSafe.isEmpty(sz_rdfsyntax))
		sz_rdfsyntax = RDFSYNTAX.RDFXML;

	if (ToolSafe.isEmpty(sz_namespace))
		sz_namespace = "";

	RDFWriter writer = m.getWriter(sz_rdfsyntax);
	if (RDFSYNTAX.RDFXML.equals(sz_rdfsyntax)||RDFSYNTAX.RDFXML_ABBREV.equals(sz_rdfsyntax)){
		writer.setProperty("showXmlDeclaration", "true");
		writer.setProperty("allowBadURIs", "true");
		writer.setProperty("relativeURIs","same-document");
	}
	if (RDFSYNTAX.TURTLE.equals(sz_rdfsyntax)){
		writer.setProperty("usePropertySymbols", "false");
		writer.setProperty("useTripleQuotedStrings", "false");
		writer.setProperty("useDoubles", "false");
	}
	writer.write(m, out, sz_namespace);
	out.flush();
	return true;
}
 
Example 20
Project: jena   File: JenaWriterBase.java View source code 6 votes vote down vote up
@Override
public void write(Model model, OutputStream out, String base)
{
    Writer w = IO.asBufferedUTF8(out) ; 
    write(model.getGraph(), w, base) ;
    try { w.flush() ; } catch (Exception e) {}
}
 
Example 21
Project: JsonPullParser   File: JsonModelCoder.java View source code 6 votes vote down vote up
/**
 * Encodes the given [email protected] List} of values into the JSON format, and writes it using the given writer.<br>
 * Writes "[]" if null is given.
 * 
 * @param writer [email protected] Writer} to be used for writing value
 * @param list [email protected] List} of values to be encoded
 * @throws IOException 
 */
public void encodeListNullToBlank(Writer writer, List<? extends T> list) throws IOException {
	if (list == null) {
		writer.write("[]");
		writer.flush();
		return;
	}

	encodeListNullToNull(writer, list);
}
 
Example 22
Project: jeql   File: ManGenerator.java View source code 6 votes vote down vote up
void generate(Writer wr)
{
  writer = new TextManWriter(wr);
  writer.writeTitle("Functions");
  writeFunctions();
  writer.writeTitle("Commands");
  writeCommands();
  try {
    wr.flush();
  }
  catch (IOException e) {
    // do nothing
  }
}
 
Example 23
Project: ilarkesto   File: XStreamSerializer.java View source code 6 votes vote down vote up
@Override
public void serialize(Object bean, OutputStream out) {
	try {
		Writer writer = new OutputStreamWriter(out, encoding);
		writer.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
		xstream.toXML(bean, writer);
		writer.flush();
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 24
Project: vraptor-templates   File: VelocityRenderer.java View source code 6 votes vote down vote up
private void merge(Writer writer){
	try {
		template.merge(context, writer);
		writer.flush();
	} catch (IOException e) {
		throw new RuntimeException(e);
	}
}
 
Example 25
Project: k3po   File: Control.java View source code 6 votes vote down vote up
private void writeCommand(PrepareCommand prepare) throws Exception {
    OutputStream bytesOut = connection.getOutputStream();
    CharsetEncoder encoder = UTF_8.newEncoder();
    Writer textOut = new OutputStreamWriter(bytesOut, encoder);

    Iterable<String> names = prepare.getNames();

    textOut.append("PREPARE\n");
    textOut.append("version:2.0\n");
    for (String name : names) {
        textOut.append(format("name:%s\n", name));
    }
    textOut.append("\n");
    textOut.flush();
}
 
Example 26
Project: genome-weaver-align   File: FASTA.java View source code 6 votes vote down vote up
public void toFASTA(Writer out) throws IOException {
    List<String> chrList = new ArrayList<String>(sequenceTable.keySet());
    Collections.sort(chrList, new Comparator4ChrName());

    final int width = 50;

    for (String chr : chrList) {
        ACGTSequence seq = sequenceTable.get(chr);
        out.append(String.format(">%s\n", chr));
        for (long i = 0; i < seq.length(); i += width) {
            long seqEnd = Math.min(i + width, seq.length());
            ACGTSequence line = seq.subString(i, seqEnd);
            out.append(line.toString());
            out.append("\n");
        }
    }
    out.flush();
}
 
Example 27
Project: fiji   File: MeshExporter.java View source code 6 votes vote down vote up
static public void writeDXF(final Collection contents, final Writer w) throws IOException {
	w.write("0\nSECTION\n2\nENTITIES\n");   //header of file
	for (Iterator it = contents.iterator(); it.hasNext(); ) {
		Content ob = (Content)it.next();

		CustomMesh cmesh=null;

		if (ob.getContent() instanceof CustomMeshNode) {
			CustomMeshNode cmeshnode = (CustomMeshNode) ob.getContent();
			cmesh = cmeshnode.getMesh();
		} else if (ob.getContent() instanceof MeshGroup) {
			MeshGroup mg = (MeshGroup)ob.getContent();
			cmesh = mg.getMesh();
		} else
			continue;

		final List triangles = cmesh.getMesh();

		String title = ob.getName().replaceAll(" ", "_").replaceAll("#", "--");
		Mtl mat = new Mtl(1 - ob.getTransparency(), cmesh.getColor());
		writeTrianglesDXF(w, triangles, title, "" + mat.getAsSingle());
	}
	w.append("0\nENDSEC\n0\nEOF\n");         //TRAILER of the file
}
 
Example 28
Project: btpka3.github.com   File: ExportLine.java View source code 6 votes vote down vote up
public static void main(String[] args) throws IOException {

        Writer out = new FileWriter("/tmp/insert1.sql");
        Scanner sc = new Scanner(fromLargeFile());

        try {
            String str = null;
            while ((str = sc.findWithinHorizon(prefix, bufSize)) == null) {
                try {
                    sc.skip("(?s).{1," + (bufSize - prefix.length()) + "}");
                } catch (NoSuchElementException e) {
                    break;
                }
            }
            if (str != null) {
                out.append(str);

                String lineEnd = ".*\\);";
                while ((str = sc.findWithinHorizon(lineEnd, bufSize)) == null) {
                    out.append(sc.findWithinHorizon("(?s).{1," + (bufSize - 2) + "}", bufSize));
                }
                out.append(str);

            } else {
                System.out.println("Not found.");
            }
        } finally {
            out.flush();
            out.close();
            sc.close();
            System.out.println("Done.");
        }
    }
 
Example 29
Project: socom   File: BatchAccount.java View source code 6 votes vote down vote up
public void writeTo(Writer writer) throws IOException {
	writer.append(firstname).append(SEPERATOR);
	writer.append(lastname).append(SEPERATOR);
	writer.append(password);
	writeIfNotEmpty(writer,getGroupID());
	writeIfNotEmpty(writer,getSocomID());
	writeIfNotEmpty(writer,getFacebookID());
	writeIfNotEmpty(writer,getFbEmail());
	writeIfNotEmpty(writer,getSocomFbAccessToken());
}
 
Example 30
Project: avaje-ebeanorm   File: PlatformDdlWriter.java View source code 6 votes vote down vote up
/**
 * Write the 'Apply' DDL buffers to the writer.
 */
protected void writeApplyDdl(Writer writer, DdlWrite write) throws IOException {

  // merge the apply buffers in the appropriate order
  writer.append(write.apply().getBuffer());
  writer.append(write.applyForeignKeys().getBuffer());
  writer.append(write.applyHistory().getBuffer());
}
 
Example 31
Project: android-platform-tools-base   File: FilterDataPersistence.java View source code 6 votes vote down vote up
public void persist(List<FileSupplier> fileSuppliers, Writer writer) throws IOException {
    Gson gson = new Gson();
    ImmutableList.Builder<Record> records = ImmutableList.builder();
    for (FileSupplier fileSupplier : fileSuppliers) {
        if (fileSupplier instanceof SplitFileSupplier) {
            records.add(new Record(
                    ((SplitFileSupplier) fileSupplier).getFilterData().getFilterType(),
                    ((SplitFileSupplier) fileSupplier).getFilterData().getIdentifier(),
                    fileSupplier.get().getName()));
        }
    }
    String recordsAsString = gson.toJson(records.build());
    try {
        writer.append(recordsAsString);
    } finally {
        writer.close();
    }
}
 
Example 32
Project: spatial4j   File: JtsGeoJSONWriter.java View source code 6 votes vote down vote up
protected void write(Writer output, NumberFormat nf, Coordinate[] coord) throws IOException {
  output.write('[');
  for (int i = 0; i < coord.length; i++) {
    if (i > 0) {
      output.append(',');
    }
    write(output, nf, coord[i]);
  }
  output.write(']');
}
 
Example 33
Project: extension-aws   File: WikiGenerator.java View source code 6 votes vote down vote up
protected void markLinks(String[] words, Writer inOutput) throws IOException
{
	for (int i = 0; i < words.length; i++)
	{
		String word = words[i];
		
		//break this into more parts based on html and other tags?
		StringBuffer part = new StringBuffer();
		for (int j = 0; j < word.length(); j++)
		{
			//build up a word
			if ( Character.isLetter( word.charAt(j) ) )
			{
				part.append(word.charAt(j));
			}
			else
			{
				if ( part.length() > 0 )
				{
					dumpWord(inOutput, part.toString());					
					part = new StringBuffer();
				}
				inOutput.append(word.charAt(j));
			}					
		}
		if ( part.length() > 0 )
		{
			dumpWord(inOutput, part.toString());					
		}

		inOutput.write(' ');
	}
}
 
Example 34
Project: freemind-mmx   File: MapNodePositionHolder.java View source code 6 votes vote down vote up
public void saveHtml(Writer pFileout) throws IOException {
	super.saveHtml(pFileout);
	if (sMapLocationGif == null) {
		sMapLocationGif = getController().getFrame().getProperty(
				MAP_LOCATION);
	}
	String link = FreeMindMapController.getLink(mTileSource, mPosition,
			mMapCenter, mZoom);
	// to embed the original thumb nail: getImageTag() +
	pFileout.append("<a href=\"" + link + "\">" + "<img src=\""
			+ sMapLocationGif + "\"/></a>");
}
 
Example 35
Project: tcf   File: TerminalsStreamsListener.java View source code 6 votes vote down vote up
/**
 * Notify the data receiver that some data has been received.
 *
 * @param data The data or <code>null</code>.
 */
protected final void notifyReceiver(final String data, final StreamsDataReceiver[] receivers) {
	if (data == null) return;
	// Notify the data receiver
	for (StreamsDataReceiver receiver : receivers) {
		try {
			// Get the writer
			Writer writer = receiver.getWriter();
			// Append the data
			writer.append(data);
			// And flush it
			writer.flush();
		} catch (IOException e) {
			if (CoreBundleActivator.getTraceHandler().isSlotEnabled(1, null)) {
				IStatus status = new Status(IStatus.WARNING, CoreBundleActivator.getUniqueIdentifier(),
											NLS.bind(Messages.TerminalsStreamReaderRunnable_error_appendFailed, streamId, data),
											e);
				Platform.getLog(CoreBundleActivator.getContext().getBundle()).log(status);
			}
		}
	}
}
 
Example 36
Project: wso2-synapse   File: SimpleXMLEventAllocator.java View source code 6 votes vote down vote up
@Override
public String toString() {
    try {
        Writer writer = new StringWriter();
        writer.write(getClass().getSimpleName());
        writer.write('(');
        writeAsEncodedUnicodeInternal(writer);
        writer.write(')');
        return writer.toString();
    } catch (IOException e) {
        return super.toString();
    }
}
 
Example 37
Project: Magnolia   File: FreemarkerUtil.java View source code 6 votes vote down vote up
/**
 * Uses the class of the object to create the templates name, passes the object under the name 'this'
 * and returns the result in a String.
 * Used only in DialogMultiSelect - VersionCommentPopup - Inbox - SubPagesControl
 */
public static String process(Object thisObj) {
    final Writer writer = new StringWriter();
    process(thisObj, writer);
    return writer.toString();
}
 
Example 38
Project: OpenClinica   File: FormBuilderTest.java View source code 6 votes vote down vote up
public String createTable() {
    Element root = new Element("table");
    root.setAttribute("border", "0");
    Document doc = new Document(root);
    Element thead = new Element("thead");
    Element th = new Element("th");
    th.addContent("A header");
    th.setAttribute("class", "aka_header_border");
    thead.addContent(th);
    Element th2 = new Element("th");
    th2.addContent("Another header");
    th2.setAttribute("class", "aka_header_border");
    thead.addContent(th2);
    root.addContent(thead);
    Element tr1 = new Element("tr");
    Element td1 = new Element("td");
    td1.setAttribute("valign", "top");
    td1.setAttribute("class", "cellBorders");
    td1.setText("cell contents");
    tr1.addContent(td1);
    root.addContent(tr1);
    XMLOutputter outp = new XMLOutputter();
    Format format = Format.getPrettyFormat();
    format.setOmitDeclaration(true);
    outp.setFormat(format);
    Writer writer = new StringWriter();
    try {
        outp.output(doc, writer);
    } catch (IOException e) {
        e.printStackTrace(); // To change body of catch statement use
        // File | Settings | File Templates.
    }
    return writer.toString();
}
 
Example 39
Project: JerseyTest   File: Jackson2StaxReaderTest.java View source code 6 votes vote down vote up
private void _testBean(Class clazz, Object bean) throws Exception {
        Map<String, Object> props = new HashMap<String, Object>();

        props.put(JAXBContextImpl.RETAIN_REFERENCE_TO_INFO, Boolean.TRUE);
        Class[] classes = new Class[]{clazz};

        JAXBContext ctx = JAXBContext.newInstance(classes, props);

        JsonFactory factory = new JsonFactory();
        Writer sWriter = new StringWriter();
        JsonGenerator g;

        g = factory.createJsonGenerator(sWriter);

        Marshaller marshaller = ctx.createMarshaller();
//        marshaller.marshal(bean, System.out);
        marshaller.marshal(bean, new Stax2JacksonWriter(g));

        g.flush();

        String jsonExpression = sWriter.toString();
        System.out.println(jsonExpression);

        JsonParser parser = factory.createJsonParser(new StringReader(jsonExpression));

        Unmarshaller unmarshaller = ctx.createUnmarshaller();
        Object unmarshalledBean = unmarshaller.unmarshal(new Jackson2StaxReader(parser));

        System.out.println(String.format("Unmarshalled bean = %s", unmarshalledBean));

        assertEquals(bean, unmarshalledBean);
    }
 
Example 40
Project: p4   File: SearchConnection.java View source code 6 votes vote down vote up
public static String solrSuggest(P4Service service, final String term) {
	Writer writer = new StringWriter();

	String results = "";
	try {
		StringBuilder sb = new StringBuilder();
		sb.append(service.getURL());
		sb.append(SUGGEST_URI);
		sb.append("?term=");
		sb.append(term);
		String path = sb.toString();

		logger.debug("Query to P4WS:\n" + path);

		P4HttpClient client = new P4HttpClient(service.getUserID());

		client.getParams().setParameter("http.protocol.content-charset", "UTF-8");

		HttpRequestBase request = new HttpGet(path);
		HttpResponse response = client.executeRequest(request);
		HttpEntity entity = response.getEntity();

		if (entity != null) {
			InputStream is = entity.getContent();
			if (is != null) {
				char[] buffer = new char[1024];

				Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				int n;
				while ((n = reader.read(buffer)) != -1) {
					writer.write(buffer, 0, n);
				}
				is.close();
			}
		}
		results = writer.toString();
		EntityUtils.consume(entity);
		writer.close();
	} catch (Exception e) {
		logger.error(e.getMessage());
		logger.error("Either the query was invalid or P4WS could not be accessed.");
		results = null;
	}
	return results;
}
 
Example 41
Project: stickypunch   File: TestUtils.java View source code 6 votes vote down vote up
public static String getRandomLogJson() {
    JsonFactory jsonfactory = new JsonFactory();
    Writer writer = new StringWriter();
    String json = null;
    try {
        JsonGenerator jsonGenerator = jsonfactory.createJsonGenerator(writer);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeArrayFieldStart("logs");
        jsonGenerator.writeString("authenticationToken must be at least 16 characters.");
        jsonGenerator.writeString("Downloading push notification package failed.");
        jsonGenerator.writeString("Extracting push notification package failed.");
        jsonGenerator.writeString("Missing file in push notification package.");
        jsonGenerator.writeString("Missing image in push notification package.");
        jsonGenerator.writeEndArray();
        jsonGenerator.writeEndObject();
        jsonGenerator.close();
        json = writer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return json;
}
 
Example 42
Project: StartupNews   File: CrashHandler.java View source code 6 votes vote down vote up
/**
 */
private String saveCrashInfo2File(Throwable ex) {

    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : infos.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        sb.append(key + "=" + value + "\n");
    }

    Writer writer = new StringWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    ex.printStackTrace(printWriter);
    Throwable cause = ex.getCause();
    while (cause != null) {
        cause.printStackTrace(printWriter);
        cause = cause.getCause();
    }
    printWriter.close();
    String result = writer.toString();
    sb.append(result);
    try {
        long timestamp = System.currentTimeMillis();
        String time = formatter.format(new Date());
        String fileName = "crash-" + time + "-" + timestamp + ".txt";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + Constants.CRASH_LOG_DIR;
            File dir = new File(path);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(path + fileName);
            fos.write(sb.toString().getBytes());
            fos.close();
        }
        return fileName;
    } catch (Exception e) {
        Log.e(LOG_TAG, "an error occured while writing file...", e);
    }
    return null;
}
 
Example 43
Project: neba   File: BeanRendererImpl.java View source code 6 votes vote down vote up
public String renderInternal(Object object, String templatePath, Map<String, Object> additionalContextElements) {
    final Writer writer = new FastStringWriter();
    final VelocityBindings bindings = prepareBindings(object);
    merge(additionalContextElements, bindings);
    final VelocityContext context = new VelocityContext(bindings);

    String renderedObject;
    try {
        this.engine.getTemplate(templatePath).merge(context, writer);
    } catch (Exception e) {
        throw new RuntimeException("Unable to render " + object + " with template " + templatePath + ".", e);
    }
    renderedObject = writer.toString();

    return renderedObject;
}
 
Example 44
Project: Katari   File: JsonRepresentationWrapperTest.java View source code 6 votes vote down vote up
@Test
public void testSimpleJSONObject() throws Exception {
  StringReader reader = new StringReader(
      "element1='${result.element1}', element2='${result.element2}'");

  Template template = new Template("wrapper", reader, configuration);
  Map<String, Object> model = new HashMap<String, Object>();

  JSONObject element = new JSONObject();
  element.put("element1", "value-1");
  element.put("element2", "value-2");
  model.put("result", new JsonRepresentation(element));

  Writer out = new StringWriter();
  template.process(model, out);
  String result = out.toString();
  log.debug("Output for testSimpleJSONObject is {}", result);
  assertThat(result, is("element1='value-1', element2='value-2'"));
}
 
Example 45
Project: fedora-client   File: AtomApimMessage.java View source code 6 votes vote down vote up
/**
 * Serialization of the API-M message as an Atom entry. [email protected]}
 */
@Override
public String toString() {
    Writer sWriter = new StringWriter();

    try {
        entry.writeTo("prettyxml", sWriter);
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
    return sWriter.toString();
}
 
Example 46
Project: libreplan   File: PageForErrorOnEvent.java View source code 6 votes vote down vote up
private String getStacktrace() {
    Throwable exception = (Throwable) Executions.getCurrent().getAttribute(
            "javax.servlet.error.exception");
    if (exception != null) {
        Writer stacktrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stacktrace));
        return stacktrace.toString();
    }
    return "";
}
 
Example 47
Project: callback-blackberry   File: JSONWriter.java View source code 6 votes vote down vote up
/**
     * Constructor.
     * @param writer The writer to use to do 'streaming' JSON writing.
     * @throws NullPointerException Thrown if writer is null.
     */
    public JSONWriter(Writer writer) throws NullPointerException {
        //Try to avoid double-buffering or buffering in-memory writers.
        Class writerClass = writer.getClass();
//        if (!StringWriter.class.isAssignableFrom(writerClass) &&
//            !CharArrayWriter.class.isAssignableFrom(writerClass) &&
//            !BufferedWriter.class.isAssignableFrom(writerClass)) {
//            writer = new BufferedWriter(writer);
//        }
        this.writer = writer;
        this.closures = new Stack();
    }
 
Example 48
Project: WebWorks-Packager-deprecated   File: JSONWriter.java View source code 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param writer
 *            The writer to use to do 'streaming' JSON writing.
 * @throws NullPointerException
 *             Thrown if writer is null.
 */
public JSONWriter( Writer writer ) throws NullPointerException {
    // Try to avoid double-buffering or buffering in-memory writers.
    Class writerClass = writer.getClass();
    // if (!StringWriter.class.isAssignableFrom(writerClass) &&
    // !CharArrayWriter.class.isAssignableFrom(writerClass) &&
    // !BufferedWriter.class.isAssignableFrom(writerClass)) {
    // writer = new BufferedWriter(writer);
    // }
    this.writer = writer;
    this.closures = new Stack();
}
 
Example 49
Project: opslogger   File: AbstractFileChannelProviderTest.java View source code 6 votes vote down vote up
protected void ensureAssociated(Writer writer, FileChannel channel) throws Exception {
    Class<? extends Writer> implementationClass = writer.getClass();
    for (Field field : implementationClass.getDeclaredFields()) {
        if (!field.getType().isAssignableFrom(channel.getClass())) {
            continue;
        }
        field.setAccessible(true);
        Object value = field.get(writer);
        if (channel == value) {
            return;
        }
    }
    throw new AssertionError("The provided writer is not associated with the FileChannel");
}
 
Example 50
Project: opslogger   File: AbstractFileChannelProviderTest.java View source code 6 votes vote down vote up
protected void ensureUtf8Charset(Writer writer) throws Exception {
    Class<? extends Writer> implementationClass = writer.getClass();
    for (Field field : implementationClass.getDeclaredFields()) {
        if (!field.getType().isAssignableFrom(Charset.class)) {
            continue;
        }
        field.setAccessible(true);
        assertSame(StandardCharsets.UTF_8, field.get(writer));
        return;
    }
}
 
Example 51
Project: phonegap-simjs   File: JSONArray.java View source code 6 votes vote down vote up
/**
 * Convert this array into a stream of JSON text, specifying verbosity.
 * @param writer The writer which to write the JSON text to.
 * @param indentDepth How many spaces to use for each indent level.  Should be one to eight.  
 *
 * @throws JSONException Thrown on IO errors during serialization.
 */
public Writer write(Writer writer, int indentDepth) throws JSONException {
    Serializer serializer;

    if (indentDepth < 1) {
        indentDepth = 0;
    } else if (indentDepth > 8) {
        indentDepth = 9;
    }

    //Try to avoid double-buffering or buffering in-memory
    //writers.
    Class writerClass = writer.getClass();
    if (!StringWriter.class.isAssignableFrom(writerClass) &&
        !CharArrayWriter.class.isAssignableFrom(writerClass) &&
        !BufferedWriter.class.isAssignableFrom(writerClass)) {
        writer = new BufferedWriter(writer);
    }

    if (indentDepth > 0) {
        serializer = new SerializerVerbose(writer, indentDepth);
    } else {
        serializer = new Serializer(writer);
    }
    try {
        serializer.writeArray(this);
    } catch (IOException iox) {
        JSONException jex = new JSONException("Error occurred during input read.");
        jex.initCause(iox);
        throw jex;
    }
    return writer;
}
 
Example 52
Project: phonegap-simjs   File: JSONWriter.java View source code 6 votes vote down vote up
/**
 * Constructor.
 * @param writer The writer to use to do 'streaming' JSON writing.
 * @throws NullPointerException Thrown if writer is null.
 */
public JSONWriter(Writer writer) throws NullPointerException {
    //Try to avoid double-buffering or buffering in-memory writers.
    Class writerClass = writer.getClass();
    if (!StringWriter.class.isAssignableFrom(writerClass) &&
        !CharArrayWriter.class.isAssignableFrom(writerClass) &&
        !BufferedWriter.class.isAssignableFrom(writerClass)) {
        writer = new BufferedWriter(writer);
    }
    this.writer = writer;
    this.closures = new Stack();
}
 
Example 53
Project: WebWorks   File: JSONWriter.java View source code 6 votes vote down vote up
/**
     * Constructor.
     * @param writer The writer to use to do 'streaming' JSON writing.
     * @throws NullPointerException Thrown if writer is null.
     */
    public JSONWriter(Writer writer) throws NullPointerException {
        //Try to avoid double-buffering or buffering in-memory writers.
        Class writerClass = writer.getClass();
//        if (!StringWriter.class.isAssignableFrom(writerClass) &&
//            !CharArrayWriter.class.isAssignableFrom(writerClass) &&
//            !BufferedWriter.class.isAssignableFrom(writerClass)) {
//            writer = new BufferedWriter(writer);
//        }
        this.writer = writer;
        this.closures = new Stack();
    }
 
Example 54
Project: phonegap-blackberry-webworks   File: JSONWriter.java View source code 6 votes vote down vote up
/**
     * Constructor.
     * @param writer The writer to use to do 'streaming' JSON writing.
     * @throws NullPointerException Thrown if writer is null.
     */
    public JSONWriter(Writer writer) throws NullPointerException {
        //Try to avoid double-buffering or buffering in-memory writers.
        Class writerClass = writer.getClass();
//        if (!StringWriter.class.isAssignableFrom(writerClass) &&
//            !CharArrayWriter.class.isAssignableFrom(writerClass) &&
//            !BufferedWriter.class.isAssignableFrom(writerClass)) {
//            writer = new BufferedWriter(writer);
//        }
        this.writer = writer;
        this.closures = new Stack();
    }
 
Example 55
Project: liferay-apps-content-targeting   File: CTSampleSQLBuilder.java View source code 5 votes vote down vote up
protected void buildPluginSqls(String dbType, String sqlDir, File outputDir)
	throws Exception {

	DB db = DBFactoryUtil.getDB(dbType);

	File dir = new File(sqlDir);

	for (File sqlFile : dir.listFiles()) {
		String sqlFileName = sqlFile.getName();

		if (!sqlFileName.endsWith(_SQL_FILE_SUFFIX)) {
			continue;
		}

		StringBundler sb = new StringBundler(4);

		int index = sqlFileName.indexOf(_SQL_FILE_SUFFIX);

		sb.append(sqlFileName.substring(0, index));
		sb.append(StringPool.MINUS);
		sb.append(dbType);
		sb.append(_SQL_FILE_SUFFIX);

		File newSqlFile = new File(outputDir, sb.toString());

		String line = null;
		Writer writer = null;
		UnsyncBufferedReader unsyncBufferedReader = null;

		try {
			writer = new FileWriter(newSqlFile);

			Reader reader = new FileReader(sqlFile);

			unsyncBufferedReader = new UnsyncBufferedReader(reader);

			while ((line = unsyncBufferedReader.readLine()) != null) {
				line = line.trim();

				if (line.length() == 0) {
					continue;
				}

				line = db.buildSQL(line);

				writer.write(line);
			}
		}
		finally {
			if (unsyncBufferedReader != null) {
				unsyncBufferedReader.close();
			}

			if (writer != null) {
				writer.close();
			}
		}
	}
}
 
Example 56
Project: appstatus   File: RadiatorPage.java View source code 5 votes vote down vote up
public void doGet(StatusWebHandler webHandler, HttpServletRequest req, HttpServletResponse resp)
		throws UnsupportedEncodingException, IOException {

	// Setup response
	resp.setContentType("text/html");
	resp.setCharacterEncoding("UTF-8");

	// Get Health checks
	List<ICheckResult> results = webHandler.getAppStatus().checkAll(req.getLocale());
	int status = STATUS_OK;
	for (ICheckResult r : results) {

		if (r.getCode() != ICheckResult.OK && !r.isFatal() && status == STATUS_OK) {
			status = STATUS_WARN;
		}

		if (r.getCode() != ICheckResult.OK && r.isFatal()) {
			status = STATUS_ERROR;
			break;
		}
	}

	String btnClass = "btn-success";
	if (status == STATUS_WARN) {
		btnClass = "btn-warning";
	}

	if (status == STATUS_ERROR) {
		btnClass = "btn-danger";
	}

	// Get batchs status.
	IBatchManager manager = webHandler.getAppStatus().getBatchManager();

	String batchStatus = " progress-success ";
	String active = StringUtils.EMPTY;
	int width = 0;

	if (manager != null) {
		batchStatus = manager.getErrorBatches().size() > 0 ? " progress-danger " : " progress-success ";
		active = manager.getRunningBatches().size() > 0 ? " progress-striped active " : "";
		width = manager.getRunningBatches().size() + manager.getFinishedBatches().size() > 0 ? 100 : 0;
	}

	Writer w = resp.getWriter();
	w.append("<html>");
	w.append("<head>");
	w.append("<meta http-equiv=\"refresh\" content=\"60;\">");
	w.append("<link href=\"?resource=appstatus.css\" rel=\"stylesheet\">");
	w.append("</head>");
	w.append("<body style=\"background: #000; text-align: center; padding-top: 5%;\">");
	w.append("<p style=\"color: #fff; font-size: 200%;\" >" + webHandler.getApplicationName() + "</p>");
	w.append("<p style=\" padding-top: 10%;\"><a href=\"?p=status\" target=\"_blank\" class=\"btn btn-large "
			+ btnClass + "\" >Status</a></p>");
	w.append("<div class=\"progress "
			+ batchStatus
			+ active
			+ "\" style=\"margin-top: 5%; width: 90%; margin-left: 5%; margin-right: 5%;\">  <div class=\"bar\" style=\"width: "
			+ width + "%;\"></div></div>");
	w.append("</body></html>");
}
 
Example 57
Project: Terminal   File: CrashHandler.java View source code 5 votes vote down vote up
@SuppressLint("SimpleDateFormat")
private String saveCrashInfoToFile(Throwable ex) {
	Writer info = new StringWriter();
	PrintWriter printWriter = new PrintWriter(info);
	ex.printStackTrace(printWriter);
	Throwable cause = ex.getCause();
	while (cause != null) {
		cause.printStackTrace(printWriter);
		cause = cause.getCause();
	}

	String result = info.toString();
	printWriter.close();
	deviceInfo.put("EXEPTION", ex.getLocalizedMessage());
	deviceInfo.put(STACK_TRACE, result);
	try {
		Date date = new Date();
		SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
		String fileName = String.format("Crash_%s%s", fmt.format(date),
				CRASH_REPORTER_EXTENSION);

		FileOutputStream trace = null;
		File dumpFile = null;

		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			dumpFile = new File(Environment.getExternalStorageDirectory(),
					fileName);
		} else {
			dumpFile = new File(appContext.getFilesDir(), fileName);
		}

		trace = new FileOutputStream(dumpFile);

		for (Object key : deviceInfo.keySet()) {
			Object val = deviceInfo.get(key);

			String l = String.format(
					"%s\n========================\n%s\n\n\n",
					key.toString(), val.toString());
			trace.write(l.getBytes());
		}

		trace.flush();
		trace.close();

		return dumpFile.getAbsolutePath();
	} catch (Exception e) {
		Logger.w("Error while writing crush dump: " + e.toString());
	}
	return null;
}