Java Code Examples for java.io.Writer

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 addis, under directory /application/src/main/java/org/drugis/addis/util/.

Source file: CopyrightInfo.java

  20 
vote

public void writeHeader(String fileName) throws IOException {
  Writer out=new OutputStreamWriter(new FileOutputStream(fileName),"UTF-8");
  try {
    out.write(d_headerText);
  }
  finally {
    out.close();
  }
}
 

Example 2

From project agile, under directory /agile-web/src/main/java/org/headsupdev/agile/web/.

Source file: AbstractEvent.java

  18 
vote

public String getBodyHeader(){
  final Writer out=new StringWriter();
  for (  CssReference ref : getBodyCssReferences()) {
    String url=Manager.getStorageInstance().getGlobalConfiguration().getFullUrl("/resources/" + ref.getScope().getName() + "/"+ ref.getName());
    try {
      out.write("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + url + "\" />");
    }
 catch (    IOException e) {
    }
  }
  return out.toString();
}
 

Example 3

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/util/.

Source file: Helpers.java

  18 
vote

public static void writeFile(String fileName,String fileContents) throws IOException {
  Writer writer=new BufferedWriter(new FileWriter(fileName));
  try {
    writer.write(fileContents);
  }
  finally {
    writer.close();
  }
}
 

Example 4

From project ajah, under directory /ajah-html/src/main/java/com/ajah/html/element/.

Source file: AbstractNestableHtmlCoreElement.java

  18 
vote

/** 
 * Returns a rendering of this element (and children) as a string.
 * @see AbstractNestableHtmlCoreElement#render(Writer,int)
 * @return A rendering of this element (and children) as a string.
 */
public String render(){
  try {
    final Writer writer=new StringWriter();
    render(writer,0);
    return writer.toString();
  }
 catch (  final IOException e) {
    log.log(Level.SEVERE,e.getMessage(),e);
    return null;
  }
}
 

Example 5

From project alfredo, under directory /examples/src/main/java/com/cloudera/alfredo/examples/.

Source file: WhoServlet.java

  18 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/plain");
  resp.setStatus(HttpServletResponse.SC_OK);
  String user=req.getRemoteUser();
  String principal=(req.getUserPrincipal() != null) ? req.getUserPrincipal().getName() : null;
  Writer writer=resp.getWriter();
  writer.write(MessageFormat.format("You are: user[{0}] principal[{1}]\n",user,principal));
}
 

Example 6

From project arquillian-rusheye, under directory /rusheye-impl/src/main/java/org/jboss/rusheye/result/statistics/.

Source file: OverallStatistics.java

  18 
vote

@Override public void setProperties(Properties properties){
  Writer writer=(Writer)properties.getProperty("overall-statistics-output");
  if (writer == null) {
    writer=new OutputStreamWriter(System.out);
  }
  this.printerWriter=new PrintWriter(writer);
}
 

Example 7

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/report/.

Source file: ReportHTML.java

  18 
vote

@Override public void save(String path){
  try {
    Writer out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path),"UTF-8"));
    out.write(formatted_header.toString());
    out.flush();
    out.close();
  }
 catch (  IOException e) {
    Logger.getLogger(ReportHTML.class.getName()).log(Level.WARNING,"Could not write out HTML report!",e);
  }
}
 

Example 8

From project Axon-trader, under directory /external-listeners/src/main/java/org/axonframework/samples/trader/listener/.

Source file: OrderbookExternalListener.java

  18 
vote

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 9

From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/beintoosdkutility/.

Source file: ErrorDisplayer.java

  18 
vote

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 10

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

  18 
vote

/** 
 * 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 11

From project bndtools, under directory /bndtools.core/src/bndtools/.

Source file: Logger.java

  18 
vote

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 12

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/util/.

Source file: XMLPrinterTool.java

  18 
vote

public String print(Element e) throws IOException {
  final org.jdom.Element jdomElem=new DOMBuilder().build(e);
  final Writer sw=new StringWriter();
  XMLOutputter xmlOutputter=new XMLOutputter(Format.getPrettyFormat());
  xmlOutputter.output(jdomElem,sw);
  return sw.toString();
}
 

Example 13

From project bundlemaker, under directory /main/org.bundlemaker.core.osgi/src/org/bundlemaker/core/osgi/utils/.

Source file: JarFileManifestWriter.java

  18 
vote

private void writeManifest(JarOutputStream out,BundleManifest manifest) throws IOException {
  out.putNextEntry(new JarEntry("META-INF/"));
  out.write(new byte[0]);
  out.flush();
  out.closeEntry();
  out.putNextEntry(new JarEntry(JarFile.MANIFEST_NAME));
  Writer writer=new NonClosingOuptutStreamWriter(out);
  manifest.write(writer);
  writer.flush();
  out.flush();
  out.closeEntry();
}
 

Example 14

From project c24-spring, under directory /c24-spring-batch/src/main/java/biz/c24/io/spring/batch/writer/.

Source file: C24ItemWriter.java

  18 
vote

/** 
 * 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 15

From project candlepin, under directory /src/test/java/org/candlepin/util/.

Source file: UtilTest.java

  18 
vote

@Test public void readfile() throws IOException {
  File tmpfile=File.createTempFile("utiltest","tmp");
  Writer out=new FileWriter(tmpfile);
  out.write("you're right");
  out.close();
  String line=Util.readFile(new FileInputStream(tmpfile));
  assertEquals("you're right\n",line);
  tmpfile.delete();
}
 

Example 16

From project capedwarf-green, under directory /server-api/src/main/java/org/jboss/capedwarf/server/api/mvc/.

Source file: AbstractAction.java

  18 
vote

/** 
 * Write result.
 * @param resp   the response
 * @param result the result
 * @throws IOException for any IO error
 */
protected void writeResult(HttpServletResponse resp,Object result) throws IOException {
  if (result instanceof Iterable) {
    writeResults(resp,(Iterable)result);
  }
 else {
    prepareResponse(resp);
    Writer writer=resp.getWriter();
    writer.write(String.valueOf(result));
    writer.flush();
  }
}
 

Example 17

From project cascading, under directory /src/core/cascading/util/.

Source file: Util.java

  18 
vote

public static void printGraph(String filename,SimpleDirectedGraph graph){
  try {
    Writer writer=new FileWriter(filename);
    try {
      printGraph(writer,graph);
    }
  finally {
      writer.close();
    }
  }
 catch (  IOException exception) {
    LOG.error("failed printing graph to {}, with exception: {}",filename,exception);
  }
}
 

Example 18

From project cascading-avro, under directory /cascading-avro-maven-plugin/src/test/java/com/maxpoint/cascading/avro/.

Source file: CascadingFieldsGeneratorTest.java

  18 
vote

@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 19

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/generate/java/taghandler/.

Source file: TagHandlerClassGenerator.java

  18 
vote

public boolean process(ModelElementBase model,TagModel tag) throws CdkException {
  try {
    Writer writer=getOutput(tag);
    configuration.writeTemplate(TAGHANDLER_TEMPLATE,new TagWithModel<ModelElementBase>(tag,model),writer);
    writer.close();
  }
 catch (  IOException e) {
    throw new CdkException(e);
  }
catch (  TemplateException e) {
    throw new CdkException(e);
  }
  return false;
}
 

Example 20

From project chililog-server, under directory /src/main/java/org/chililog/server/.

Source file: App.java

  18 
vote

/** 
 * Writes the shutdown file to stop the server
 * @throws Exception
 */
static void writeShutdownFile() throws Exception {
  Writer out=new OutputStreamWriter(new FileOutputStream(new File(".",STOP_ME_FILENAME)));
  try {
    out.write("shutdown");
  }
  finally {
    out.close();
  }
}
 

Example 21

From project CIShell, under directory /core/org.cishell.utilities/src/org/cishell/utilities/.

Source file: StringUtilities.java

  18 
vote

public static String getStackTraceAsString(Throwable e){
  Writer writer=new StringWriter();
  PrintWriter printWriter=new PrintWriter(writer);
  e.printStackTrace(printWriter);
  return writer.toString();
}
 

Example 22

From project clj-ds, under directory /src/main/java/com/trifork/clj_ds/.

Source file: RT.java

  18 
vote

static public Object format(Object o,String s,Object... args) throws Exception {
  Writer w;
  if (o == null)   w=new StringWriter();
 else   if (Util.equals(o,T))   w=(Writer)new OutputStreamWriter(System.out);
 else   w=(Writer)o;
  doFormat(w,s,ArraySeq.create(args));
  if (o == null)   return w.toString();
  return null;
}
 

Example 23

From project Clotho-Core, under directory /ClothoApps/SeqAnalyzer/src/org/clothocad/algorithm/seqanalyzer/sequencing/.

Source file: seqAnalysis.java

  18 
vote

private void file(String datafile,String filename){
  try {
    Writer output=null;
    File file=new File(filename);
    output=new BufferedWriter(new FileWriter(file));
    output.write(datafile);
    output.close();
  }
 catch (  IOException ex) {
    Logger.getLogger(seqAnalysis.class.getName()).log(Level.SEVERE,null,ex);
    System.out.println("*****IOException in file writer");
  }
}
 

Example 24

From project Cloud9, under directory /src/test/edu/umd/cloud9/io/map/.

Source file: JpEncodingTest.java

  18 
vote

private void writeOutput(String str,String file){
  try {
    FileOutputStream fos=new FileOutputStream(file);
    Writer out=new OutputStreamWriter(fos,"UTF8");
    out.write(str);
    out.close();
  }
 catch (  IOException e) {
    e.printStackTrace();
  }
}
 

Example 25

From project CMM-data-grabber, under directory /benny/src/main/java/au/edu/uq/cmm/benny/.

Source file: Benny.java

  18 
vote

private void respond(HttpServletResponse resp,int status,String msg) throws IOException {
  resp.setContentType("text/plain");
  resp.setStatus(status);
  Writer w=resp.getWriter();
  try {
    w.write(msg + "\r\n");
  }
  finally {
    w.close();
  }
}
 

Example 26

From project Aardvark, under directory /aardvark-core/src/test/java/gw/vark/enums/.

Source file: EnumGenerator.java

  17 
vote

private static void writeEnumTypeToFile(IType iType,File file) throws IOException {
  EnumeratedAttribute ea=(EnumeratedAttribute)iType.getTypeInfo().getConstructor().getConstructor().newInstance();
  StringBuilder sb=new StringBuilder();
  sb.append("package gw.vark.enums\n").append("\n").append("enum ").append(makeName(iType)).append("{\n\n");
  String[] Vals=ea.getValues();
  for (int i=0, ValsLength=Vals.length; i < ValsLength; i++) {
    String string=Vals[i];
    if (string.equals("")) {
      string="NoVal";
    }
    sb.append("  ").append(escape(GosuStringUtil.capitalize(string))).append("(\"").append(GosuEscapeUtil.escapeForGosuStringLiteral(string)).append("\")");
    sb.append(",\n");
  }
  sb.append("\n");
  sb.append("  property get Instance() : " + iType.getName() + " {\n");
  sb.append("    return " + EnumeratedAttribute.class.getName() + ".getInstance("+ iType.getName()+ ", Val) as "+ iType.getName()+ "\n");
  sb.append("  }\n\n");
  sb.append("  var _val : String as Val\n\n");
  sb.append("  private construct( s : String ) { Val = s }\n\n");
  sb.append("}\n");
  String fileName=makeName(iType) + ".gs";
  File actualFile=new File(file,fileName);
  Writer writer=StreamUtil.getOutputStreamWriter(new FileOutputStream(actualFile,false));
  try {
    writer.write(sb.toString());
  }
  finally {
    writer.close();
  }
  _filesInEnums.remove(fileName);
}
 

Example 27

From project AirCastingAndroidClient, under directory /src/main/java/pl/llp/aircasting/helper/.

Source file: CSVHelper.java

  17 
vote

public Uri prepareCSV(Session session) throws IOException {
  OutputStream outputStream=null;
  try {
    File storage=Environment.getExternalStorageDirectory();
    File dir=new File(storage,"aircasting_sessions");
    dir.mkdirs();
    File file=new File(dir,fileName(session.getTitle()));
    outputStream=new FileOutputStream(file);
    Writer writer=new OutputStreamWriter(outputStream);
    CsvWriter csvWriter=new CsvWriter(writer,',');
    csvWriter.write("sensor:model");
    csvWriter.write("sensor:package");
    csvWriter.write("sensor:capability");
    csvWriter.write("Date");
    csvWriter.write("Time");
    csvWriter.write("Timestamp");
    csvWriter.write("geo:lat");
    csvWriter.write("geo:long");
    csvWriter.write("sensor:units");
    csvWriter.write("Value");
    csvWriter.endRecord();
    write(session).toWriter(csvWriter);
    csvWriter.flush();
    csvWriter.close();
    Uri uri=Uri.fromFile(file);
    if (Constants.isDevMode()) {
      Log.i(Constants.TAG,"File path [" + uri + "]");
    }
    return uri;
  }
  finally {
    closeQuietly(outputStream);
  }
}
 

Example 28

From project anadix, under directory /anadix-api/src/main/java/org/anadix/.

Source file: Anadix.java

  17 
vote

/** 
 * Tries to format given report and store it in the report directory under specified name. The name is appended with _{counter} so if the file with given name already exists it is not replaced. ReportFormatter class used is the one set before or the default one (SimpleReportFormatter). Reports are stored either to directory set before via setReportDirectory method or to the default one (./reports).
 * @param report - instance of Report received upon successful analysis
 * @param fileName - name of the file to store results to
 * @return true if the Report was formatted and saved, false otherwise
 */
public static boolean formatReport(Report report,String fileName){
  ReportFormatter formatter;
  try {
    formatter=INSTANCE.createFormatter();
  }
 catch (  InstantiationException ex) {
    return false;
  }
  File output=createFile(INSTANCE.getReportDir(),fileName,formatter.getReportFileExtension());
  Writer writer;
  try {
    writer=new FileWriter(output);
  }
 catch (  IOException ex) {
    logger.error("Unable to create FileWriter",ex);
    return false;
  }
  formatter.formatAndStore(report,writer);
  try {
    writer.close();
  }
 catch (  IOException ex) {
    logger.error("Unable to close FileWriter",ex);
    return false;
  }
  return true;
}
 

Example 29

From project and-bible, under directory /jsword-tweaks/src/main/java/jsword/org/crosswire/jsword/book/sword/.

Source file: ConfigEntryTable.java

  17 
vote

public void save() throws IOException {
  if (configFile != null) {
    String encoding=ENCODING_LATIN1;
    if (getValue(ConfigEntryType.ENCODING).equals(ENCODING_UTF8)) {
      encoding=ENCODING_UTF8;
    }
    Writer writer=null;
    try {
      writer=new OutputStreamWriter(new FileOutputStream(configFile),encoding);
      writer.write(toConf());
    }
  finally {
      if (writer != null) {
        writer.close();
      }
    }
  }
}
 

Example 30

From project android-context, under directory /src/edu/fsu/cs/contextprovider/.

Source file: ContextExpandableListActivity.java

  17 
vote

public void exportToFile() throws IOException {
  String path=Environment.getExternalStorageDirectory() + "/" + CSV_FILENAME;
  File file=new File(path);
  file.createNewFile();
  if (!file.isFile()) {
    throw new IllegalArgumentException("Should not be a directory: " + file);
  }
  if (!file.canWrite()) {
    throw new IllegalArgumentException("File cannot be written: " + file);
  }
  Writer output=new BufferedWriter(new FileWriter(file));
  HashMap<String,String> cntx=null;
  String line;
  cntx=ContextProvider.getAllUnordered();
  for (  LinkedHashMap.Entry<String,String> entry : cntx.entrySet()) {
    ContextListItem item=new ContextListItem();
    item.setName(entry.getKey());
    item.setValue(entry.getValue());
    line=item.toString();
    output.write(line + "\n");
  }
  output.close();
  Toast.makeText(this,String.format("Saved",path),Toast.LENGTH_LONG).show();
  Intent shareIntent=new Intent(Intent.ACTION_SEND);
  shareIntent.putExtra(Intent.EXTRA_STREAM,Uri.parse("file://" + path));
  shareIntent.setType("text/plain");
  startActivity(Intent.createChooser(shareIntent,"Share Context Using..."));
}
 

Example 31

From project android_packages_apps_Gallery, under directory /tests/src/com/android/camera/stress/.

Source file: ImageCapture.java

  17 
vote

@LargeTest public void testVideoCapture(){
  boolean memoryResult=false;
  Instrumentation inst=getInstrumentation();
  File imageCaptureMemFile=new File(CAMERA_MEM_OUTPUTFILE);
  mStartPid=getMediaserverPid();
  mStartMemory=getMediaserverVsize();
  Log.v(TAG,"start memory : " + mStartMemory);
  try {
    Writer output=new BufferedWriter(new FileWriter(imageCaptureMemFile,true));
    output.write("Camera Image capture\n");
    output.write("No of loops : " + TOTAL_NUMBER_OF_VIDEOCAPTURE + "\n");
    getMemoryWriteToLog(output);
    mOut.write("Video Camera Capture\n");
    mOut.write("No of loops :" + TOTAL_NUMBER_OF_VIDEOCAPTURE + "\n");
    mOut.write("loop: ");
    Intent intent=new Intent();
    intent.setClassName("com.android.camera","com.android.camera.VideoCamera");
    getActivity().startActivity(intent);
    for (int i=0; i < TOTAL_NUMBER_OF_VIDEOCAPTURE; i++) {
      Thread.sleep(WAIT_FOR_PREVIEW);
      inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
      Thread.sleep(WAIT_FOR_VIDEO_CAPTURE_TO_BE_TAKEN);
      inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
      Thread.sleep(WAIT_FOR_PREVIEW);
      mOut.write(" ," + i);
      mOut.flush();
    }
    Thread.sleep(WAIT_FOR_STABLE_STATE);
    memoryResult=validateMemoryResult(mStartPid,mStartMemory,output);
    Log.v(TAG,"End memory : " + getMediaserverVsize());
    output.close();
    assertTrue("Camera video capture memory test",memoryResult);
  }
 catch (  Exception e) {
    Log.v(TAG,e.toString());
    fail("Fails to capture video");
  }
}
 

Example 32

From project Anki-Android, under directory /src/com/ichi2/anki/.

Source file: CustomExceptionHandler.java

  17 
vote

@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 33

From project ant4eclipse, under directory /org.ant4eclipse.lib.core/src/org/ant4eclipse/lib/core/util/.

Source file: Utilities.java

  17 
vote

/** 
 * This function stores a file under a specified location using a chosen encoding.
 * @param destination The destination where the file has to be written to. Not <code>null</code>.
 * @param content The content that has to be written. Not <code>null</code>.
 * @param encoding The encoding that will be used to write the content. Neither <code>null</code> nor empty.
 */
public static final void writeFile(File destination,String content,String encoding){
  Assure.notNull("destination",destination);
  Assure.notNull("content",content);
  Assure.nonEmpty("encoding",encoding);
  OutputStream output=null;
  Writer writer=null;
  try {
    output=new FileOutputStream(destination);
    writer=new OutputStreamWriter(output,encoding);
    writer.write(content);
  }
 catch (  IOException ex) {
    throw new Ant4EclipseException(ex,CoreExceptionCode.IO_FAILURE);
  }
 finally {
    close(writer);
    close(output);
  }
}
 

Example 34

From project arquillian-extension-persistence, under directory /impl/src/main/java/org/jboss/arquillian/persistence/core/client/.

Source file: DatabaseStateDumper.java

  17 
vote

public void dump(@Observes DumpDataCommand dumpDataCommand){
  final DataDump dataDump=dumpDataCommand.getDumpData();
  Writer writer=null;
  try {
    writer=new BufferedWriter(new FileWriter(dataDump.getPath()));
    writer.write(dataDump.getDataSet());
  }
 catch (  Exception e) {
    throw new DatabaseDumpException("Unable to dump database state to " + dataDump.getPath(),e);
  }
 finally {
    dumpDataCommand.setResult(true);
    if (writer != null) {
      try {
        writer.close();
      }
 catch (      IOException e) {
        throw new DatabaseDumpException("Unable to close writer.",e);
      }
    }
  }
}
 

Example 35

From project azkaban, under directory /azkaban/src/java/azkaban/web/.

Source file: LogServlet.java

  17 
vote

@Override protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
  resp.setContentType("text/plain");
  String file=getParam(req,"file");
  String fileName=_logDir + File.separator + file;
  if (!new File(fileName).canRead()) {
    resp.getWriter().write("No log available at '" + file + "'");
    return;
  }
  long size=new File(fileName).length();
  FileInputStream f=new FileInputStream(fileName);
  long skipped=0;
  if (req.getParameter("full") == null) {
    skipped=Math.max(0,size - 200 * 1024);
    f.skip(skipped);
  }
  BufferedReader reader=new BufferedReader(new InputStreamReader(f));
  try {
    Writer writer=resp.getWriter();
    String line=reader.readLine();
    if (skipped > 0) {
      writer.write("Skipping " + skipped + " bytes. Use the optional parameter ?full to see the entire log.\n\n");
      line=reader.readLine();
    }
    for (; line != null; line=reader.readLine()) {
      writer.write(line);
      writer.write("\n");
    }
  }
  finally {
    reader.close();
  }
}
 

Example 36

From project b3log-latke, under directory /maven-min-plugin/src/main/java/org/b3log/maven/plugin/min/.

Source file: CSSProcessor.java

  17 
vote

/** 
 * Minimizes CSS sources.
 */
@Override protected void minimize(){
  if (null == getSrcDir()) {
    getLogger().error("The source directory is null!");
    return;
  }
  try {
    final File srcDir=getSrcDir();
    final File[] srcFiles=srcDir.listFiles(new FileFilter(){
      @Override public boolean accept(      final File file){
        return !file.isDirectory() && !file.getName().endsWith(getSuffix() + ".css");
      }
    }
);
    for (int i=0; i < srcFiles.length; i++) {
      final File src=srcFiles[i];
      final String targetPath=getTargetDir() + File.separator + src.getName().substring(0,src.getName().length() - ".css".length())+ getSuffix()+ ".css";
      final File target=new File(targetPath);
      getLogger().info("Minimizing [srcPath=" + src.getPath() + ", targetPath="+ targetPath+ "]");
      final Reader reader=new InputStreamReader(new FileInputStream(src),"UTF-8");
      final FileOutputStream writerStream=new FileOutputStream(target);
      final Writer writer=new OutputStreamWriter(writerStream,"UTF-8");
      final CssCompressor compressor=new CssCompressor(reader);
      compressor.compress(writer,-1);
      reader.close();
      writer.close();
    }
  }
 catch (  final IOException e) {
    getLogger().error("Minimization error!",e);
  }
}
 

Example 37

From project Bitcoin-Wallet-for-Android, under directory /wallet/src/de/schildbach/wallet/ui/.

Source file: WalletActivity.java

  17 
vote

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 38

From project Cafe, under directory /webapp/src/org/openqa/selenium/browserlaunchers/.

Source file: Proxies.java

  17 
vote

public static File makeProxyPAC(File parentDir,int port,String configuredProxy,String proxyPort,String nonProxyHosts,Capabilities capabilities){
  DoNotUseProxyPac pac=newProxyPac(port,configuredProxy,proxyPort,nonProxyHosts,capabilities);
  Proxy proxy=extractProxy(capabilities);
  if (proxy != null && proxy.getHttpProxy() != null) {
    pac.defaults().toProxy(proxy.getHttpProxy());
  }
  try {
    File pacFile=new File(parentDir,"proxy.pac");
    Writer out=new FileWriter(pacFile);
    pac.outputTo(out);
    out.close();
    return pacFile;
  }
 catch (  IOException e) {
    throw new SeleniumException("Unable to configure proxy. Selenium will not work.",e);
  }
}
 

Example 39

From project Carolina-Digital-Repository, under directory /fcrepo-clients/src/main/java/edu/unc/lib/dl/fedora/.

Source file: ClientUtils.java

  17 
vote

/** 
 * Serializes a non-FOXML root XML element.  Does not attempt to attach local namespaces to sub-elements.
 * @param element 
 * @return
 */
public static byte[] serializeXML(Element element){
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Writer pw;
  try {
    pw=new OutputStreamWriter(baos,"UTF-8");
  }
 catch (  UnsupportedEncodingException e) {
    throw new ServiceException("UTF-8 character encoding support is required",e);
  }
  Format format=Format.getPrettyFormat();
  XMLOutputter outputter=new XMLOutputter(format);
  try {
    outputter.output(element,pw);
    pw.flush();
    byte[] result=baos.toByteArray();
    return result;
  }
 catch (  IOException e) {
    log.error("Failed to serialize element",e);
  }
 finally {
    try {
      pw.close();
      baos.close();
    }
 catch (    IOException e) {
      log.error("Could not close streams",e);
    }
  }
  return null;
}
 

Example 40

From project chromattic, under directory /testgenerator/src/main/java/org/chromattic/testgenerator/.

Source file: CheckTestProcessor.java

  17 
vote

@Override public boolean process(Set<? extends TypeElement> annotations,RoundEnvironment roundEnvironment){
  Set<? extends Element> elements=roundEnvironment.getElementsAnnotatedWith(TestId.class);
  if (elements.size() != 0) {
    testId=elements.iterator().next().getAnnotation(TestId.class);
  }
  for (  Element element : roundEnvironment.getElementsAnnotatedWith(GroovyTestGeneration.class)) {
    TypeElement typeElt=(TypeElement)element;
    TestRef ref=new TestRef(typeElt.getQualifiedName().toString());
    List<String> chromatticClassNames=SourceUtil.getChromatticClassName(typeElt);
    for (    String chromatticQualifiedClassName : chromatticClassNames) {
      String chromatticName=GroovyOutputFormat.CHROMATTIC.getPackageName(chromatticQualifiedClassName) + "." + GroovyOutputFormat.CHROMATTIC.getClassName(chromatticQualifiedClassName).toString();
      ref.getChromatticObject().add(chromatticName);
    }
    generatedTests.add(ref);
  }
  if (roundEnvironment.processingOver()) {
    try {
      String name="testsRef-" + testId.value() + ".xml";
      FileObject xmlFile=processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,"load",name);
      Writer xmlWriter=xmlFile.openWriter();
      TestSerializer xmlSerializer=new TestSerializer();
      xmlSerializer.writeTo(xmlWriter,generatedTests);
      xmlWriter.close();
    }
 catch (    IOException e) {
      throw new RuntimeException(e);
    }
  }
  return false;
}
 

Example 41

From project clearcase-plugin, under directory /src/main/java/hudson/plugins/clearcase/ucm/.

Source file: UcmMakeBaselineComposite.java

  17 
vote

/** 
 * Extract Composite baseline information in an external file
 * @param compositeComponnentName
 * @param pvob
 * @param compositeBaselineName
 * @param fileName
 * @param clearToolLauncher
 * @param filePath
 * @throws Exception
 */
private void processExtractInfoFile(ClearTool clearTool,String compositeComponnentName,String pvob,String compositeBaselineName,String fileName) throws Exception {
  String output=clearTool.lsbl(compositeBaselineName + "@" + pvob,"\"%[depends_on]p\"");
  if (output.contains("cleartool: Error")) {
    throw new Exception("Failed to make baseline, reason: " + output);
  }
  String baselinesComp[]=output.split(" ");
  List<String> baselineList=Arrays.asList(baselinesComp);
  Collections.sort(baselineList);
  Writer writer=null;
  try {
    FilePath fp=new FilePath(clearTool.getLauncher().getLauncher().getChannel(),fileName);
    OutputStream outputStream=fp.write();
    writer=new OutputStreamWriter(outputStream);
    writer.write("The composite baseline is '" + compositeBaselineName + "'");
    for (    String baseLine : baselineList) {
      writer.write("\nThe  baseline of component '" + getComponent(clearTool,baseLine) + "' is :"+ baseLine);
    }
  }
  finally {
    if (writer != null) {
      writer.close();
    }
  }
}
 

Example 42

From project clirr-maven-plugin, under directory /src/main/java/org/codehaus/mojo/clirr/.

Source file: ClirrReport.java

  17 
vote

protected void doExecute() throws MojoExecutionException, MojoFailureException {
  if (!canGenerateReport()) {
    return;
  }
  try {
    DecorationModel model=new DecorationModel();
    model.setBody(new Body());
    Map attributes=new HashMap();
    attributes.put("outputEncoding","UTF-8");
    Locale locale=Locale.getDefault();
    SiteRenderingContext siteContext=siteRenderer.createContextForSkin(getSkinArtifactFile(),attributes,model,getName(locale),locale);
    RenderingContext context=new RenderingContext(outputDirectory,getOutputName() + ".html");
    SiteRendererSink sink=new SiteRendererSink(context);
    generate(sink,locale);
    outputDirectory.mkdirs();
    Writer writer=new FileWriter(new File(outputDirectory,getOutputName() + ".html"));
    siteRenderer.generateDocument(writer,sink,siteContext);
    siteRenderer.copyResources(siteContext,new File(project.getBasedir(),"src/site/resources"),outputDirectory);
  }
 catch (  RendererException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
catch (  IOException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
catch (  MavenReportException e) {
    throw new MojoExecutionException("An error has occurred in " + getName(Locale.ENGLISH) + " report generation.",e);
  }
}
 

Example 43

From project closure-templates, under directory /java/src/com/google/template/soy/jssrc/internal/.

Source file: JsSrcMain.java

  17 
vote

/** 
 * Generates JS source files given a Soy parse tree, an options object, an optional bundle of translated messages, and information on where to put the output files.
 * @param soyTree The Soy parse tree to generate JS source code for.
 * @param jsSrcOptions The compilation options relevant to this backend.
 * @param locale The current locale that we're generating JS for, or null if not applicable.
 * @param msgBundle The bundle of translated messages, or null to use the messages from the Soysource.
 * @param outputPathFormat The format string defining how to build the output file pathcorresponding to an input file path.
 * @param inputPathsPrefix The input path prefix, or empty string if none.
 * @throws SoySyntaxException If a syntax error is found.
 * @throws IOException If there is an error in opening/writing an output JS file.
 */
public void genJsFiles(SoyFileSetNode soyTree,SoyJsSrcOptions jsSrcOptions,@Nullable String locale,@Nullable SoyMsgBundle msgBundle,String outputPathFormat,String inputPathsPrefix) throws SoySyntaxException, IOException {
  List<String> jsFileContents=genJsSrc(soyTree,jsSrcOptions,msgBundle);
  int numFiles=soyTree.numChildren();
  if (numFiles != jsFileContents.size()) {
    throw new AssertionError();
  }
  Multimap<String,Integer> outputs=Multimaps.newListMultimap(Maps.<String,Collection<Integer>>newLinkedHashMap(),new Supplier<List<Integer>>(){
    @Override public List<Integer> get(){
      return Lists.newArrayList();
    }
  }
);
  for (int i=0; i < numFiles; ++i) {
    SoyFileNode inputFile=soyTree.getChild(i);
    String inputFilePath=inputFile.getFilePath();
    String outputFilePath=JsSrcUtils.buildFilePath(outputPathFormat,locale,inputFilePath,inputPathsPrefix);
    BaseUtils.ensureDirsExistInPath(outputFilePath);
    outputs.put(outputFilePath,i);
  }
  for (  String outputFilePath : outputs.keySet()) {
    Writer out=Files.newWriter(new File(outputFilePath),Charsets.UTF_8);
    try {
      boolean isFirst=true;
      for (      int inputFileIndex : outputs.get(outputFilePath)) {
        if (isFirst) {
          isFirst=false;
        }
 else {
          out.write("\n;\n");
        }
        out.write(jsFileContents.get(inputFileIndex));
      }
    }
  finally {
      out.close();
    }
  }
}
 

Example 44

From project cloudify, under directory /tools/src/main/java/org/cloudifysource/restDoclet/generation/.

Source file: Generator.java

  17 
vote

/** 
 * Creates the REST API documentation in HTML form, using the controllers' data and the velocity template.
 * @param controllers
 * @return string that contains the documentation in HTML form.
 * @throws Exception
 */
public String generateHtmlDocumentation(List<DocController> controllers) throws Exception {
  logger.log(Level.INFO,"Generate velocity using template: " + velocityTemplatePath + " ("+ (isUserDefineTemplatePath ? "got template path from user" : "default template path")+ ")");
  Properties p=new Properties();
  if (isUserDefineTemplatePath) {
    p.setProperty("file.resource.loader.path",velocityTemplatePath);
  }
 else {
    p.setProperty(RuntimeConstants.RESOURCE_LOADER,"classpath");
    p.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());
  }
  Velocity.init(p);
  VelocityContext ctx=new VelocityContext();
  ctx.put("controllers",controllers);
  ctx.put("version",version);
  Writer writer=new StringWriter();
  Template template=Velocity.getTemplate(velocityTemplateFileName);
  template.merge(ctx,writer);
  return writer.toString();
}
 

Example 45

From project cocos2d, under directory /cocos2d-android/src/org/cocos2d/opengl/.

Source file: GLSurfaceView.java

  17 
vote

public GL createSurface(SurfaceHolder holder){
  if (mEglSurface != null && mEglSurface != EGL10.EGL_NO_SURFACE) {
    mEgl.eglMakeCurrent(mEglDisplay,EGL10.EGL_NO_SURFACE,EGL10.EGL_NO_SURFACE,EGL10.EGL_NO_CONTEXT);
    mEGLWindowSurfaceFactory.destroySurface(mEgl,mEglDisplay,mEglSurface);
  }
  mEglSurface=mEGLWindowSurfaceFactory.createWindowSurface(mEgl,mEglDisplay,mEglConfig,holder);
  if (mEglSurface == null || mEglSurface == EGL10.EGL_NO_SURFACE) {
    throwEglException("createWindowSurface");
  }
  if (!mEgl.eglMakeCurrent(mEglDisplay,mEglSurface,mEglSurface,mEglContext)) {
    throwEglException("eglMakeCurrent");
  }
  GL gl=mEglContext.getGL();
  if (mGLWrapper != null) {
    gl=mGLWrapper.wrap(gl);
  }
  if ((mDebugFlags & (DEBUG_CHECK_GL_ERROR | DEBUG_LOG_GL_CALLS)) != 0) {
    int configFlags=0;
    Writer log=null;
    if ((mDebugFlags & DEBUG_CHECK_GL_ERROR) != 0) {
      configFlags|=GLDebugHelper.CONFIG_CHECK_GL_ERROR;
    }
    if ((mDebugFlags & DEBUG_LOG_GL_CALLS) != 0) {
      log=new LogWriter();
    }
    gl=GLDebugHelper.wrap(gl,configFlags,log);
  }
  return gl;
}
 

Example 46

From project coffeescript-netbeans, under directory /src/coffeescript/nb/.

Source file: CoffeeScriptNodeJSCompiler.java

  17 
vote

protected String getInputStreamAsString(InputStream is){
  char[] buffer=new char[1024];
  Writer writer=new StringWriter();
  try {
    Reader reader=new BufferedReader(new InputStreamReader(is,"UTF-8"));
    int n;
    while ((n=reader.read(buffer)) != -1) {
      writer.write(buffer,0,n);
    }
  }
 catch (  IOException e) {
    Exceptions.printStackTrace(e);
  }
 finally {
    try {
      is.close();
    }
 catch (    IOException e) {
    }
  }
  return writer.toString();
}
 

Example 47

From project CommitCoin, under directory /src/com/google/bitcoin/utils/.

Source file: BriefLogFormatter.java

  17 
vote

@Override public String format(LogRecord logRecord){
  Object[] arguments=new Object[6];
  arguments[0]=logRecord.getThreadID();
  String fullClassName=logRecord.getSourceClassName();
  int lastDot=fullClassName.lastIndexOf('.');
  String className=fullClassName.substring(lastDot + 1);
  arguments[1]=className;
  arguments[2]=logRecord.getSourceMethodName();
  arguments[3]=new Date(logRecord.getMillis());
  arguments[4]=logRecord.getMessage();
  if (logRecord.getThrown() != null) {
    Writer result=new StringWriter();
    logRecord.getThrown().printStackTrace(new PrintWriter(result));
    arguments[5]=result.toString();
  }
 else {
    arguments[5]="";
  }
  return messageFormat.format(arguments);
}
 

Example 48

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source file: Webserver.java

  15 
vote

void save(Writer w) throws IOException {
  if (expired)   return;
  w.write(id);
  w.write(':');
  w.write(Integer.toString(inactiveInterval));
  w.write(':');
  w.write(servletContext == null || servletContext.getServletContextName() == null ? "" : servletContext.getServletContextName());
  w.write(':');
  w.write(Long.toString(lastAccessTime));
  w.write("\r\n");
  Enumeration<String> e=getAttributeNames();
  ByteArrayOutputStream os=new ByteArrayOutputStream(1024 * 16);
  while (e.hasMoreElements()) {
    String aname=(String)e.nextElement();
    Object so=get(aname);
    if (so instanceof Serializable) {
      os.reset();
      ObjectOutputStream oos=new ObjectOutputStream(os);
      try {
        oos.writeObject(so);
        w.write(aname);
        w.write(":");
        w.write(Utils.base64Encode(os.toByteArray()));
        w.write("\r\n");
      }
 catch (      IOException ioe) {
        servletContext.log("Can't replicate/store a session value of '" + aname + "' class:"+ so.getClass().getName(),ioe);
      }
    }
 else     servletContext.log("Non serializable session object has been " + so.getClass().getName() + " skiped in storing of "+ aname,null);
    if (so instanceof HttpSessionActivationListener)     ((HttpSessionActivationListener)so).sessionWillPassivate(new HttpSessionEvent((HttpSession)this));
  }
  w.write("$$\r\n");
}
 

Example 49

From project accesointeligente, under directory /src/org/accesointeligente/server/servlets/.

Source file: BackendServlet.java

  15 
vote

private static void checkResponses(Writer writer) throws IOException {
  Thread thread=new Thread(){
    @Override public void run(){
      ResponseChecker responseChecker=new ResponseChecker();
      responseChecker.connectAndCheck();
    }
  }
;
  thread.start();
  writer.write(Command.check_responses.name() + " started");
}
 

Example 50

From project activejdbc, under directory /javalite-common/src/main/java/org/javalite/common/.

Source file: Convert.java

  15 
vote

private static void copyStream(Reader r,Writer w) throws IOException {
  char buffer[]=new char[4096];
  for (int n=0; -1 != (n=r.read(buffer)); ) {
    w.write(buffer,0,n);
  }
}
 

Example 51

From project activiti-webapp-rest-generic, under directory /activiti-webapp-rest/src/main/java/org/activiti/rest/builder/.

Source file: JSONTemplateProcessor.java

  15 
vote

public void process(String template,Object model,Writer out){
  JSONObjectBuilder builder=objectBuilders.get(getTemplateKey(template));
  if (builder == null) {
    throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,"Template " + template + " is registered on this this processor.");
  }
  try {
    JSONObject resultObject=builder.createJsonObject(model);
    writeJSON(resultObject,out);
  }
 catch (  JSONException jsone) {
    throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR,"Error while creating JSONObject from model",jsone);
  }
}
 

Example 52

From project ambrose, under directory /common/src/main/java/com/twitter/ambrose/util/.

Source file: JSONUtil.java

  15 
vote

/** 
 * Writes object to the writer as JSON using Jackson and adds a new-line before flushing.
 * @param writer the writer to write the JSON to
 * @param object the object to write as JSON
 * @throws IOException if the object can't be serialized as JSON or written to the writer
 */
public static void writeJson(Writer writer,Object object) throws IOException {
  ObjectMapper om=new ObjectMapper();
  om.configure(SerializationConfig.Feature.INDENT_OUTPUT,true);
  om.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS,false);
  writer.write(om.writeValueAsString(object));
  writer.write("\n");
  writer.flush();
}
 

Example 53

From project amplafi-sworddance, under directory /src/main/java/com/sworddance/util/perf/.

Source file: LapTimerCollection.java

  15 
vote

/** 
 * Write out the collection of LapTimers to output. In CSV (Excel) format.
 * @param output Writer to use to output CSV information
 * @param firstLine if true a header line for column names is displayed
 * @throws IOException
 */
public void writeCSV(Writer output,boolean firstLine) throws IOException {
  if (firstLine) {
    LapTimer top=this.lapTimers.get(0);
    String[] names=top.getLapNames();
    output.write("LapTimerName,Start Time,Hop Count,Total Time,");
    for (    String element : names) {
      if (element != null) {
        output.write(element);
        output.write(',');
      }
    }
    output.write("\n");
  }
  for (  LapTimer lt : this.lapTimers) {
    output.write(lt.toCSV());
    output.write('\n');
  }
}
 

Example 54

From project Android-Simple-Social-Sharing, under directory /SimpleSocialSharing/src/com/nostra13/socialsharing/twitter/extpack/winterwell/json/.

Source file: JSONArray.java

  15 
vote

/** 
 * 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 55

From project android-thaiime, under directory /makedict/src/com/android/inputmethod/latin/.

Source file: XmlDictInputOutput.java

  15 
vote

/** 
 * Writes a dictionary to an XML file. The output format is the "second" format, which supports bigrams and shortcuts.
 * @param destination a destination stream to write to.
 * @param dict the dictionary to write.
 */
public static void writeDictionaryXml(Writer destination,FusionDictionary dict) throws IOException {
  final TreeSet<Word> set=new TreeSet<Word>();
  for (  Word word : dict) {
    set.add(word);
  }
  destination.write("<wordlist format=\"2\">\n");
  for (  Word word : set) {
    destination.write("  <" + WORD_TAG + " "+ WORD_ATTR+ "=\""+ word.mWord+ "\" "+ FREQUENCY_ATTR+ "=\""+ word.mFrequency+ "\">");
    if (null != word.mBigrams) {
      destination.write("\n");
      for (      WeightedString bigram : word.mBigrams) {
        destination.write("    <" + BIGRAM_TAG + " "+ FREQUENCY_ATTR+ "=\""+ bigram.mFrequency+ "\">"+ bigram.mWord+ "</"+ BIGRAM_TAG+ ">\n");
      }
      destination.write("  ");
    }
    destination.write("</" + WORD_TAG + ">\n");
  }
  destination.write("</wordlist>\n");
  destination.close();
}
 

Example 56

From project AndroidSensorLogger, under directory /libraries/opencsv-2.3-src-with-libs/opencsv-2.3/src/au/com/bytecode/opencsv/.

Source file: CSVWriter.java

  15 
vote

/** 
 * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 * @param writer the writer to an underlying CSV source.
 * @param separator the delimiter to use for separating entries
 * @param quotechar the character to use for quoted elements
 * @param escapechar the character to use for escaping quotechars or escapechars
 * @param lineEnd the line feed terminator to use
 */
public CSVWriter(Writer writer,char separator,char quotechar,char escapechar,String lineEnd){
  this.rawWriter=writer;
  this.pw=new PrintWriter(writer);
  this.separator=separator;
  this.quotechar=quotechar;
  this.escapechar=escapechar;
  this.lineEnd=lineEnd;
}
 

Example 57

From project android_8, under directory /src/com/google/gson/stream/.

Source file: JsonWriter.java

  15 
vote

/** 
 * Creates a new instance that writes a JSON-encoded stream to  {@code out}. For best performance, ensure  {@link Writer} is buffered; wrapping in{@link java.io.BufferedWriter BufferedWriter} if necessary.
 */
public JsonWriter(Writer out){
  if (out == null) {
    throw new NullPointerException("out == null");
  }
  this.out=out;
}
 

Example 58

From project android_external_guava, under directory /src/com/google/common/io/.

Source file: CharStreams.java

  15 
vote

/** 
 * Returns a Writer that sends all output to the given  {@link Appendable}target. Closing the writer will close the target if it is  {@link Closeable}, and flushing the writer will flush the target if it is  {@link java.io.Flushable}.
 * @param target the object to which output will be sent
 * @return a new Writer object, unless target is a Writer, in which case thetarget is returned
 */
public static Writer asWriter(Appendable target){
  if (target instanceof Writer) {
    return (Writer)target;
  }
  return new AppendableWriter(target);
}
 

Example 59

From project android_external_tagsoup, under directory /src/org/ccil/cowan/tagsoup/.

Source file: XMLWriter.java

  15 
vote

/** 
 * Internal initialization method. <p>All of the public constructors invoke this method.
 * @param writer The output destination, or null to usestandard output.
 */
private void init(Writer writer){
  setOutput(writer);
  nsSupport=new NamespaceSupport();
  prefixTable=new Hashtable();
  forcedDeclTable=new Hashtable();
  doneDeclTable=new Hashtable();
  outputProperties=new Properties();
}
 

Example 60

From project android_packages_inputmethods_LatinIME, under directory /tools/makedict/src/com/android/inputmethod/latin/.

Source file: XmlDictInputOutput.java

  15 
vote

/** 
 * Writes a dictionary to an XML file. The output format is the "second" format, which supports bigrams and shortcuts.
 * @param destination a destination stream to write to.
 * @param dict the dictionary to write.
 */
public static void writeDictionaryXml(Writer destination,FusionDictionary dict) throws IOException {
  final TreeSet<Word> set=new TreeSet<Word>();
  for (  Word word : dict) {
    set.add(word);
  }
  destination.write("<wordlist format=\"2\">\n");
  for (  Word word : set) {
    destination.write("  <" + WORD_TAG + " "+ WORD_ATTR+ "=\""+ word.mWord+ "\" "+ FREQUENCY_ATTR+ "=\""+ word.mFrequency+ "\">");
    if (null != word.mBigrams) {
      destination.write("\n");
      for (      WeightedString bigram : word.mBigrams) {
        destination.write("    <" + BIGRAM_TAG + " "+ FREQUENCY_ATTR+ "=\""+ bigram.mFrequency+ "\">"+ bigram.mWord+ "</"+ BIGRAM_TAG+ ">\n");
      }
      destination.write("  ");
    }
    destination.write("</" + WORD_TAG + ">\n");
  }
  destination.write("</wordlist>\n");
  destination.close();
}
 

Example 61

From project ANNIS, under directory /annis-gui/src/main/java/annis/gui/exporter/.

Source file: GeneralTextExporter.java

  15 
vote

public void convertText(AnnisResultSet queryResult,LinkedList<String> keys,Map<String,String> args,Writer out,int offset) throws IOException {
  int counter=0;
  for (  AnnisResult annisResult : queryResult) {
    Set<Long> matchedNodeIds=annisResult.getGraph().getMatchedNodeIds();
    counter++;
    out.append((counter + offset) + ". ");
    List<AnnisNode> tok=annisResult.getGraph().getTokens();
    for (    AnnisNode annisNode : tok) {
      Long tokID=annisNode.getId();
      if (matchedNodeIds.contains(tokID)) {
        out.append("[");
        out.append(annisNode.getSpannedText());
        out.append("]");
      }
 else {
        out.append(annisNode.getSpannedText());
      }
      out.append(" ");
    }
    out.append("\n");
  }
}
 

Example 62

From project any23, under directory /core/src/main/java/org/apache/any23/extractor/rdfa/.

Source file: XSLTStylesheet.java

  15 
vote

/** 
 * Applies the XSLT transformation
 * @param document where apply the transformation
 * @param output the {@link java.io.Writer} where write on
 * @param parameters the parameters to be passed to {@link Transformer}. Pass an empty  {@link Map} if no parameters are foreseen.
 */
public synchronized void applyTo(Document document,Writer output,Map<String,String> parameters) throws XSLTStylesheetException {
  for (  String parameterKey : parameters.keySet()) {
    transformer.setParameter(parameterKey,parameters.get(parameterKey));
  }
  try {
    transformer.transform(new DOMSource(document,document.getBaseURI()),new StreamResult(output));
  }
 catch (  TransformerException te) {
    log.error("------ BEGIN XSLT Transformer Exception ------");
    log.error("Exception in XSLT Stylesheet transformation.",te);
    log.error("Input DOM node:",document);
    log.error("Input DOM node getBaseURI:",document.getBaseURI());
    log.error("Output writer:",output);
    log.error("------ END XSLT Transformer Exception ------");
    throw new XSLTStylesheetException(" An error occurred during the XSLT transformation",te);
  }
}
 

Example 63

From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/utils/.

Source file: XmlWriter.java

  15 
vote

/** 
 * Create an XmlWriter on top of an existing java.io.Writer.
 * @throws IOException
 */
public XmlWriter(Writer writer,boolean takeOwnership,int indentingOffset,boolean addXmlPrefix) throws IOException {
  thisIsWriterOwner=takeOwnership;
  this.indentingOffset=indentingOffset;
  this.writer=writer;
  this.closed=true;
  this.stack=new Stack<String>();
  this.attrs=new StringBuffer();
  if (addXmlPrefix)   this.writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
}
 

Example 64

From project apps-for-android, under directory /Translate/src/com/beust/android/translate/.

Source file: Entities.java

  15 
vote

/** 
 * <p> Escapes the characters in the <code>String</code> passed and writes the result to the <code>Writer</code> passed. </p>
 * @param writer The <code>Writer</code> to write the results of the escaping to. Assumed to be a non-null value.
 * @param str The <code>String</code> to escape. Assumed to be a non-null value.
 * @throws IOException when <code>Writer</code> passed throws the exception from calls to the  {@link Writer#write(int)}methods.
 * @see #escape(String)
 * @see Writer
 */
public void escape(Writer writer,String str) throws IOException {
  int len=str.length();
  for (int i=0; i < len; i++) {
    char c=str.charAt(i);
    String entityName=this.entityName(c);
    if (entityName == null) {
      if (c > 0x7F) {
        writer.write("&#");
        writer.write(Integer.toString(c,10));
        writer.write(';');
      }
 else {
        writer.write(c);
      }
    }
 else {
      writer.write('&');
      writer.write(entityName);
      writer.write(';');
    }
  }
}
 

Example 65

From project arquillian-container-openshift, under directory /openshift-express/src/main/java/org/jboss/arquillian/container/openshift/express/util/.

Source file: IOUtils.java

  15 
vote

/** 
 * Unconditionally close a Writer. Equivalent to  {@link Writer#close()}, except any exceptions will be ignored. This is typically used in finally blocks.
 * @param output the Writer to close, may be null or already closed
 */
public static void closeQuietly(Writer output){
  try {
    if (output != null) {
      output.close();
    }
  }
 catch (  IOException ioe) {
  }
}
 

Example 66

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/stats/.

Source file: StatsServlet.java

  15 
vote

void writeStats(Writer w) throws IOException {
  VelocityContext context=new VelocityContext();
  context.put("title","Avro RPC Stats");
  ArrayList<String> rpcs=new ArrayList<String>();
  ArrayList<RenderableMessage> messages=new ArrayList<RenderableMessage>();
  for (  Entry<RPCContext,Stopwatch> rpc : this.statsPlugin.activeRpcs.entrySet()) {
    rpcs.add(renderActiveRpc(rpc.getKey(),rpc.getValue()));
  }
  Set<Message> keys=null;
synchronized (this.statsPlugin.methodTimings) {
    keys=this.statsPlugin.methodTimings.keySet();
    for (    Message m : keys) {
      messages.add(renderMethod(m));
    }
  }
  context.put("inFlightRpcs",rpcs);
  context.put("messages",messages);
  context.put("currTime",FORMATTER.format(new Date()));
  context.put("startupTime",FORMATTER.format(statsPlugin.startupTime));
  Template t;
  try {
    t=velocityEngine.getTemplate("org/apache/avro/ipc/stats/templates/statsview.vm");
  }
 catch (  ResourceNotFoundException e) {
    throw new IOException();
  }
catch (  ParseErrorException e) {
    throw new IOException();
  }
catch (  Exception e) {
    throw new IOException();
  }
  t.merge(context,w);
}
 

Example 67

From project babel, under directory /src/org/json/.

Source file: JSONArray.java

  15 
vote

/** 
 * 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 68

From project BeeQueue, under directory /src/org/beequeue/util/.

Source file: Buffers.java

  15 
vote

public static BufferedWriter bufferWriter(Writer writer,int bufferSize){
  if (writer instanceof BufferedWriter) {
    return (BufferedWriter)writer;
  }
 else {
    return new BufferedWriter(writer,adjustBufferSize(bufferSize));
  }
}
 

Example 69

From project Blitz, under directory /src/com/laxser/blitz/web/portal/impl/.

Source file: DefaultPipeRender.java

  15 
vote

@Override public void render(Writer out,Window window) throws IOException {
  JSONObject json=new JSONObject();
  json.put("content",window.getContent());
  json.put("id",window.getName());
  JSONArray js=getAttributeAsArray(window,PipeImpl.WINDIW_JS);
  if (js != null && js.length() > 0) {
    json.put("js",js);
  }
  JSONArray css=getAttributeAsArray(window,PipeImpl.WINDOW_CSS);
  if (css != null && css.length() > 0) {
    json.put("css",css);
  }
  out.append("<script type=\"text/javascript\">");
  out.append("rosepipe.addWindow(");
  out.append(json.toString());
  out.append(");");
  out.append("</script>");
  out.append('\n');
}
 

Example 70

From project book, under directory /src/main/java/com/tamingtext/fuzzy/.

Source file: TypeAheadResponseWriter.java

  15 
vote

@Override public void write(Writer w,SolrQueryRequest req,SolrQueryResponse rsp) throws IOException {
  SolrIndexSearcher searcher=req.getSearcher();
  NamedList nl=rsp.getValues();
  int sz=nl.size();
  for (int li=0; li < sz; li++) {
    Object val=nl.getVal(li);
    if (val instanceof DocList) {
      DocList dl=(DocList)val;
      DocIterator iterator=dl.iterator();
      w.append("<ul>\n");
      while (iterator.hasNext()) {
        int id=iterator.nextDoc();
        Document doc=searcher.doc(id,fields);
        String name=doc.get("word");
        w.append("<li>" + name + "</li>\n");
      }
      w.append("</ul>\n");
    }
  }
}
 

Example 71

From project brightberry, under directory /src/org/json/me/.

Source file: JSONArray.java

  15 
vote

/** 
 * 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.elementAt(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 72

From project brut.apktool.smali, under directory /dexlib/src/main/java/org/jf/dexlib/Code/Analysis/.

Source file: RegisterType.java

  15 
vote

public void writeTo(Writer writer) throws IOException {
  writer.write('(');
  writer.write(category.name());
  if (type != null) {
    writer.write(',');
    writer.write(type.getClassType());
  }
  writer.write(')');
}
 

Example 73

From project Calendar-Application, under directory /au/com/bytecode/opencsv/.

Source file: CSVWriter.java

  15 
vote

/** 
 * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 * @param writer the writer to an underlying CSV source.
 * @param separator the delimiter to use for separating entries
 * @param quotechar the character to use for quoted elements
 * @param escapechar the character to use for escaping quotechars or escapechars
 * @param lineEnd the line feed terminator to use
 */
public CSVWriter(Writer writer,char separator,char quotechar,char escapechar,String lineEnd){
  this.rawWriter=writer;
  this.pw=new PrintWriter(writer);
  this.separator=separator;
  this.quotechar=quotechar;
  this.escapechar=escapechar;
  this.lineEnd=lineEnd;
}
 

Example 74

From project caustic, under directory /console/src/au/com/bytecode/opencsv/.

Source file: CSVWriter.java

  15 
vote

/** 
 * Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
 * @param writer the writer to an underlying CSV source.
 * @param separator the delimiter to use for separating entries
 * @param quotechar the character to use for quoted elements
 * @param escapechar the character to use for escaping quotechars or escapechars
 * @param lineEnd the line feed terminator to use
 */
public CSVWriter(Writer writer,char separator,char quotechar,char escapechar,String lineEnd){
  this.rawWriter=writer;
  this.pw=new PrintWriter(writer);
  this.separator=separator;
  this.quotechar=quotechar;
  this.escapechar=escapechar;
  this.lineEnd=lineEnd;
}
 

Example 75

From project ceres, under directory /ceres-core/src/main/java/com/bc/ceres/core/runtime/internal/.

Source file: InstallInfo.java

  15 
vote

public void write(Writer writer) throws IOException {
  try {
    this.date=new Date();
    createXStream().toXML(this,writer);
  }
 catch (  XStreamException e) {
    IOException ioe=new IOException("Failed to write install info.");
    ioe.initCause(e);
    throw ioe;
  }
}
 

Example 76

From project cider, under directory /src/net/yacy/cider/util/.

Source file: FileUtils.java

  15 
vote

public static int copy(final File source,final Charset inputCharset,final Writer dest) throws IOException {
  InputStream fis=null;
  try {
    fis=new FileInputStream(source);
    return copy(fis,dest,inputCharset);
  }
  finally {
    if (fis != null)     try {
      fis.close();
    }
 catch (    final Exception e) {
    }
  }
}
 

Example 77

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/admin/util/.

Source file: JSONArray.java

  15 
vote

/** 
 * 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.
 * @param indentFactor The number of spaces to add to each level of indentation.
 * @param indent The indention of the top level.
 * @return The writer.
 * @throws JSONException
 */
Writer write(Writer writer,int indentFactor,int indent) throws JSONException {
  try {
    boolean commanate=false;
    int length=this.length();
    writer.write('[');
    if (length == 1) {
      JSONObject.writeValue(writer,this.myArrayList.get(0),indentFactor,indent);
    }
 else     if (length != 0) {
      final int newindent=indent + indentFactor;
      for (int i=0; i < length; i+=1) {
        if (commanate) {
          writer.write(',');
        }
        if (indentFactor > 0) {
          writer.write('\n');
        }
        JSONObject.indent(writer,newindent);
        JSONObject.writeValue(writer,this.myArrayList.get(i),indentFactor,newindent);
        commanate=true;
      }
      if (indentFactor > 0) {
        writer.write('\n');
      }
      JSONObject.indent(writer,indent);
    }
    writer.write(']');
    return writer;
  }
 catch (  IOException e) {
    throw new JSONException(e);
  }
}
 

Example 78

From project cloudhopper-commons-util, under directory /src/main/java/com/cloudhopper/commons/util/.

Source file: FastByteArrayOutputStream.java

  15 
vote

public void writeTo(Writer out,String encoding) throws IOException {
  if (buffers != null) {
    writeToViaSmoosh(out,encoding);
  }
 else {
    writeToViaString(out,encoding);
  }
}
 

Example 79

From project clutter, under directory /src/com/thoughtworks/ashcroft/analysis/.

Source file: StaticFactoryDetector.java

  15 
vote

/** 
 * Prints the same way as a stack trace. Most IDEs will turn it into a hyperlink.
 * @param method
 * @param report
 * @throws IOException
 */
public void writeReport(JavaMethod method,Writer report) throws IOException {
  if (method.isStatic() && method.isPublic()) {
    report.write("    at ");
    report.write(method.getParent().toString());
    report.write(".");
    report.write(method.getName());
    report.write("(");
    report.write(method.getParent().getParentSource().getFile().getName());
    report.write(":");
    report.write("" + method.getLineNumber());
    report.write(")\n");
  }
}
 

Example 80

From project codjo-imports, under directory /codjo-imports-common/src/test/java/net/codjo/imports/common/.

Source file: JdbcFixture.java

  15 
vote

public static void dumpResultSet(ResultSet resultSet,Writer outWriter) throws SQLException {
  PrintWriter out=new PrintWriter(outWriter);
  ResultSetMetaData rsmd=resultSet.getMetaData();
  int colmumnCount=rsmd.getColumnCount();
  for (int i=1; i <= colmumnCount; i++) {
    out.print("\"" + rsmd.getColumnName(i) + "\"");
    if (i + 1 <= colmumnCount) {
      out.print(", ");
    }
  }
  out.println();
  while (resultSet.next()) {
    for (int i=1; i <= colmumnCount; i++) {
      out.print("\"" + resultSet.getObject(i) + "\"");
      if (i + 1 <= colmumnCount) {
        out.print(", ");
      }
    }
    out.println();
  }
}
 

Example 81

From project com.cedarsoft.serialization, under directory /serialization/src/main/java/com/cedarsoft/serialization/ui/.

Source file: VersionMappingsVisualizer.java

  15 
vote

public void visualize(@Nonnull Writer out) throws IOException {
  Collection<Column> columns=new ArrayList<Column>();
  SortedSet<Version> keyVersions=mappings.getMappedVersions();
  List<T> keys=new ArrayList<T>(mappings.getMappings().keySet());
  Collections.sort(keys,comparator);
  for (  T key : keys) {
    VersionMapping mapping=mappings.getMapping(key);
    List<Version> versions=new ArrayList<Version>();
    for (    Version keyVersion : keyVersions) {
      versions.add(mapping.resolveVersion(keyVersion));
    }
    columns.add(new Column(toString.convert(key),versions));
  }
  writeHeadline(columns,out);
  writeSeparator(columns.size(),out);
  writeContent(new ArrayList<Version>(keyVersions),columns,out);
  writeSeparator(columns.size(),out);
}
 

Example 82

From project commons-io, under directory /src/main/java/org/apache/commons/io/.

Source file: CopyUtils.java

  15 
vote

/** 
 * Copy chars from a <code>Reader</code> to a <code>Writer</code>.
 * @param input the <code>Reader</code> to read from
 * @param output the <code>Writer</code> to write to
 * @return the number of characters copied
 * @throws IOException In case of an I/O problem
 */
public static int copy(Reader input,Writer output) throws IOException {
  char[] buffer=new char[DEFAULT_BUFFER_SIZE];
  int count=0;
  int n=0;
  while (-1 != (n=input.read(buffer))) {
    output.write(buffer,0,n);
    count+=n;
  }
  return count;
}