Java Code Examples for java.io.PrintWriter.close()

The following are Jave code examples for showing how to use close() of the java.io.PrintWriter class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: lams   File: MonitoringAction.java   View Source Code Vote up 6 votes
private ActionForward fixFaultySession(ActionMapping mapping, ActionForm form, HttpServletRequest request,
    HttpServletResponse response) throws DokumaranConfigurationException, ServletException, IOException {
IDokumaranService service = getDokumaranService();
Long toolSessionId = WebUtil.readLongParam(request, AttributeNames.PARAM_TOOL_SESSION_ID);
DokumaranSession session = service.getDokumaranSessionBySessionId(toolSessionId);

try {
    log.debug("Fixing faulty session (sessionId=" + toolSessionId + ").");
    service.createPad(session.getDokumaran(), session);

} catch (Exception e) {
    // printing out error cause
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.write("Failed! " + e.getMessage());
    out.flush();
    out.close();
    log.error("Failed! " + e.getMessage());
    return null;
}

return null;
   }
 
Example 2
Project: incubator-netbeans   File: NbArtifactFixer.java   View Source Code Vote up 6 votes
private static synchronized File createFallbackPOM(String groupId, String artifactId, String version) throws IOException {
    String k = groupId + ':' + artifactId + ':' + version;
    File fallbackPOM = fallbackPOMs.get(k);
    if (fallbackPOM == null) {
        fallbackPOM = File.createTempFile("fallback", ".netbeans.pom");
        fallbackPOM.deleteOnExit();
        PrintWriter w = new PrintWriter(fallbackPOM);
        try {
            w.println("<project>");
            w.println("<modelVersion>4.0.0</modelVersion>");
            w.println("<groupId>" + groupId + "</groupId>");
            w.println("<artifactId>" + artifactId + "</artifactId>");
            w.println("<packaging>pom</packaging>");
            w.println("<version>" + version + "</version>");
            w.println("<name>" + FALLBACK_NAME + "</name>");
            w.println("</project>");
            w.flush();
        } finally {
            w.close();
        }
        fallbackPOMs.put(k, fallbackPOM);
    }
    return fallbackPOM;
}
 
Example 3
Project: Voxel_Game   File: UserSettings.java   View Source Code Vote up 6 votes
public static final void save() throws IOException {

		Console.print("Saving settings...", null);

		final Properties properties = new Properties();

		final File file = new File(Content.PREFERENCES_FILE);
		if (!file.exists()) file.createNewFile();

		final PrintWriter writer = new PrintWriter(file);

		properties.setProperty("render_distance", RENDER_DISTANCE + "");
		properties.setProperty("render_hand", RENDER_HAND + "");
		properties.setProperty("render_clouds", RENDER_CLOUDS + "");
		properties.setProperty("screen_width", SCREEN_WIDTH + "");
		properties.setProperty("screen_height", SCREEN_HEIGHT + "");
		properties.setProperty("minimap_size", MINIMAP_SIZE + "");
		properties.setProperty("render_light_rays", RENDER_LIGHT_RAYS + "");
		properties.setProperty("vsync", VSYNC + "");

		properties.store(writer, "");
		writer.close();

	}
 
Example 4
Project: GitHub   File: LogUtils.java   View Source Code Vote up 6 votes
/**
 * To stack trace string string.
 * <p>
 * 此方法参见:https://github.com/Ereza/CustomActivityOnCrash
 *
 * @param throwable the throwable
 * @return the string
 */
public static String toStackTraceString(Throwable throwable) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    throwable.printStackTrace(pw);
    String stackTraceString = sw.toString();
    //Reduce data to 128KB so we don't get a TransactionTooLargeException when sending the intent.
    //The limit is 1MB on Android but some devices seem to have it lower.
    //See: http://developer.android.com/reference/android/os/TransactionTooLargeException.html
    //And: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception#comment46697371_12809171
    if (stackTraceString.length() > MAX_STACK_TRACE_SIZE) {
        String disclaimer = " [stack trace too large]";
        stackTraceString = stackTraceString.substring(0, MAX_STACK_TRACE_SIZE - disclaimer.length()) + disclaimer;
    }
    pw.close();
    return stackTraceString;
}
 
Example 5
Project: FizeauExperimentSimulation   File: SaveButtonListener.java   View Source Code Vote up 5 votes
@Override
public void actionPerformed(ActionEvent e) {
	try {

		frame.chooser.setDialogTitle("Wybierz miejsce gdzie zapisać plik.");

		int result = frame.chooser.showSaveDialog(null);
		if (result != JFileChooser.APPROVE_OPTION){
			return;
		}
		frame.to = frame.chooser.getSelectedFile();
		
		PrintWriter pr = new PrintWriter(frame.to); 

		pr.println("n: "+ this.frame.bottom.settings.nTeeth.getSelectedItem());
		pr.println("d[m]: "+ this.frame.bottom.settings.distance.getSelectedItem());
		pr.println("w[rad/s] \t Q/Qmax");
		for (int i=0; i<frame.bottom.graph.data.length ; i++)
		{
			if(frame.bottom.graph.data[i]>-1){
				pr.println(i*5 + " \t " + frame.bottom.graph.data[i]/255.0);
			}
		}
		pr.close();
	}

	catch (IOException ee) {

		ee.printStackTrace();
	}		
}
 
Example 6
Project: hadoop   File: MiniDFSCluster.java   View Source Code Vote up 5 votes
private void addToFile(String p, String address) throws IOException {
  File f = new File(p);
  f.createNewFile();
  PrintWriter writer = new PrintWriter(new FileWriter(f, true));
  try {
    writer.println(address);
  } finally {
    writer.close();
  }
}
 
Example 7
Project: Android-Code-Demos   File: CrashHandler.java   View Source Code Vote up 5 votes
private void dumpExceptionToSDCard(Throwable ex) throws IOException {
    /* 如果 SD 卡不存在或无法使用,则无法把异常信息写入 SD 卡 */
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        if (DEBUG) {
            Log.w(TAG, "sdcard unmounted, skip dump exception");
            return;
        }
    }

    File dir = new File(PATH);
    if (!dir.exists()) {
        dir.mkdirs();
    }
    long current = System.currentTimeMillis();
    String time = new SimpleDateFormat("yyy-MM-dd HH:mm:ss", Locale.CHINA).format(new Date(current));
    File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);

    try {
        PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        pw.println(time);
        dumpPhoneInfo(pw);
        pw.println();
        ex.printStackTrace(pw);
        pw.close();
    } catch (Exception e) {
        Log.e(TAG, "dump crash info failed");
    }
}
 
Example 8
Project: uavstack   File: TestStruts2Action.java   View Source Code Vote up 5 votes
public void hello() throws IOException {

        ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        try {
            out.print("TestStruts2Action hello()");
            out.flush();
            out.close();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
 
Example 9
Project: solo-spring   File: TextXMLRenderer.java   View Source Code Vote up 5 votes
@Override
public void render(final HttpServletRequest request, final HttpServletResponse response) {
	try {
		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");

		final PrintWriter writer = response.getWriter();

		writer.write(content);
		writer.close();
	} catch (final IOException e) {
		logger.error("Render failed", e);
	}
}
 
Example 10
Project: dubbocloud   File: ClassUtils.java   View Source Code Vote up 5 votes
public static String toString(Throwable e) {
    StringWriter w = new StringWriter();
    PrintWriter p = new PrintWriter(w);
    p.print(e.getClass().getName() + ": ");
    if (e.getMessage() != null) {
        p.print(e.getMessage() + "\n");
    }
    p.println();
    try {
        e.printStackTrace(p);
        return w.toString();
    } finally {
        p.close();
    }
}
 
Example 11
Project: fc-java-sdk   File: FunctionComputeClientTest.java   View Source Code Vote up 5 votes
@Test
public void testCreateFunctionSetDir() throws IOException {
    createService(SERVICE_NAME);

    // Create a function
    CreateFunctionRequest createFuncReq = new CreateFunctionRequest(SERVICE_NAME);
    createFuncReq.setFunctionName(FUNCTION_NAME);
    createFuncReq.setDescription("Function for test");
    createFuncReq.setMemorySize(128);
    createFuncReq.setHandler("hello_world.handler");
    createFuncReq.setRuntime("nodejs4.4");

    // Setup code directory
    String tmpDir = "/tmp/fc_test_" + UUID.randomUUID();
    String funcFilePath = tmpDir + "/" + "hello_world.js";
    new File(tmpDir).mkdir();

    PrintWriter out = new PrintWriter(funcFilePath);
    out.println(
        "'use strict'; module.exports.handler = function(event, context, callback) {console.log('hello world'); callback(null, 'hello world');};");
    out.close();

    Code code = new Code().setDir(tmpDir);
    createFuncReq.setCode(code);
    createFuncReq.setTimeout(10);
    client.createFunction(createFuncReq);

    // Invoke the function
    InvokeFunctionRequest request = new InvokeFunctionRequest(SERVICE_NAME, FUNCTION_NAME);
    InvokeFunctionResponse response = client.invokeFunction(request);

    assertEquals("hello world", new String(response.getPayload()));

    // Cleanups
    client.deleteFunction(new DeleteFunctionRequest(SERVICE_NAME, FUNCTION_NAME));
    client.deleteService(new DeleteServiceRequest(SERVICE_NAME));

    new File(funcFilePath).delete();
    new File(tmpDir).delete();
}
 
Example 12
Project: ureport   File: HtmlPreviewServletAction.java   View Source Code Vote up 5 votes
private String buildExceptionMessage(Throwable throwable){
	Throwable root=buildRootException(throwable);
	StringWriter sw=new StringWriter();
	PrintWriter pw=new PrintWriter(sw);
	root.printStackTrace(pw);
	String trace=sw.getBuffer().toString();
	trace=trace.replaceAll("\n", "<br>");
	pw.close();
	return trace;
}
 
Example 13
Project: vertx-sfdc-platformevents   File: SoapApi.java   View Source Code Vote up 5 votes
private Buffer getAuthBody(final String user, final String password) {
	final Map<String, String> values = new HashMap<String, String>();
	values.put("username", user);
	values.put("password", password);
	// TODO: switch to File Callback?
	final InputStream in = this.getClass().getResourceAsStream(Constants.AUTH_SOAP_TEMPLATE);
	if (in == null) {
		this.logger.error("Could not retrieve resource " + Constants.AUTH_SOAP_TEMPLATE);
		return Buffer.buffer();
	}

	final Scanner scanner = new Scanner(in);
	scanner.useDelimiter("\\Z");
	final String authTemplate = scanner.next();
	scanner.close();
	final MustacheFactory mf = new DefaultMustacheFactory();
	final Mustache mustache = mf.compile(new StringReader(authTemplate), "Login");
	final ByteArrayOutputStream out = new ByteArrayOutputStream();
	final PrintWriter pw = new PrintWriter(out);
	try {
		mustache.execute(pw, values).flush();
		pw.close();
	} catch (final IOException e) {
		this.logger.error(e);
		return Buffer.buffer();
	}

	return Buffer.buffer(out.toByteArray());
}
 
Example 14
Project: Star-Ride--RiverRaid   File: SaveScore.java   View Source Code Vote up 5 votes
public SaveScore(String nombreNuevo, int scoreNuevo){
    
    try {
        escribir = new PrintWriter(new BufferedWriter(new FileWriter("top10.txt", true)));           
        escribir.println(nombreNuevo+"-"+scoreNuevo);
        escribir.close();
        
        leer();
        
    } catch (IOException ex) {
        System.out.println("No se pudo registrar en el archivo");
    }
    
}
 
Example 15
Project: ureport   File: DesignerServletAction.java   View Source Code Vote up 5 votes
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("ureport-html/designer.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 16
Project: SlidingWindowFilter-evaluator   File: App.java   View Source Code Vote up 4 votes
/**
 * Starts the App.
 */
public static void main(String[] args) {
  List<TimeSeries<Accel>> records = getRecords();
  System.out.println("\nSlidingWindow:\n");
  List<SlidingWindow> swEvaList = getSlidingWindowEvaluator(records);
  String outputFilename = "build/resources/main/swf-result.csv";
  try {
    String output = "distance;scb;filter;window;threshold;precision_μ;recall_μ;f1score_μ;"
        + "#(nnc);";
    int recordCount = records.size();
    for (int i = 0; i < recordCount; i++) {
      output += "rec" + (i + 1) + "-precision_μ;rec" + (i + 1) + "-recall_μ;rec" + (i + 1)
          + "-f1score_μ;rec" + (i + 1) + "-#(nnc);";
    }
    String[] gestureChars = {"A", "B", "C", "D", "E", "F", "G", "H"};
    for (int i = 0; i < 8; i++) {
      output += "Ges" + gestureChars[i] + "-precision;" + "Ges" + gestureChars[i] + "-recall;"
          + "Ges" + gestureChars[i] + "-f1score;";
    }
    output = output.substring(0, output.length() - 1) + "\n";
    PrintWriter writer = new PrintWriter(outputFilename, "UTF-8");
    writer.print(output);
    for (SlidingWindow swEva : swEvaList) {
      output = swEva.getDistName() + ";" + swEva.getFilterName() + ";"
          + swEva.getWindowSizeName() + ";" + swEva.getThesholdName() + ";"
          + renderDouble(swEva.getMicroPrecision(0, recordCount, 0, 8)) + ";"
          + renderDouble(swEva.getMicroRecall(0, recordCount, 0, 8)) + ";"
          + renderDouble(swEva.getMicroFscore(1, 0, recordCount, 0, 8)) + ";"
          + renderDouble(swEva.getNncCallCount(0, recordCount)) + ";";
      for (int i = 0; i < recordCount; i++) {
        output += renderDouble(swEva.getMicroPrecision(i, i + 1, 0, 8)) + ";"
            + renderDouble(swEva.getMicroRecall(i, i + 1, 0, 8)) + ";"
            + renderDouble(swEva.getMicroFscore(1, i, i + 1, 0, 8)) + ";"
            + renderDouble(swEva.getNncCallCount(i, i + 1)) + ";";
      }
      for (int i = 0; i < 8; i++) {
        output += renderDouble(swEva.getMicroPrecision(0, recordCount, i, i + 1)) + ";"
            + renderDouble(swEva.getMicroRecall(0, recordCount, i, i + 1)) + ";"
            + renderDouble(swEva.getMicroFscore(1, 0, recordCount, i, i + 1)) + ";";
      }
      output = output.substring(0, output.length() - 1) + "\n";
      writer.print(output);
    }
    writer.close();
  } catch (Exception ioEx) {
    System.out.println("Unable to write result into file " + outputFilename);
  }
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: OneLineFormatter.java   View Source Code Vote up 4 votes
@Override
public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    // Timestamp
    addTimestamp(sb, record.getMillis());

    // Severity
    sb.append(' ');
    sb.append(record.getLevel().getLocalizedName());

    // Thread
    sb.append(' ');
    sb.append('[');
    sb.append(Thread.currentThread().getName());
    sb.append(']');

    // Source
    sb.append(' ');
    sb.append(record.getSourceClassName());
    sb.append('.');
    sb.append(record.getSourceMethodName());

    // Message
    sb.append(' ');
    sb.append(formatMessage(record));

    // Stack trace
    if (record.getThrown() != null) {
        sb.append(ST_SEP);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        record.getThrown().printStackTrace(pw);
        pw.close();
        sb.append(sw.getBuffer());
    }

    // New line for next record
    sb.append(LINE_SEP);

    return sb.toString();
}
 
Example 18
Project: hadoop   File: TestDistributedShell.java   View Source Code Vote up 4 votes
@Test(timeout=90000)
public void testDSShellWithShellScript() throws Exception {
  final File basedir =
      new File("target", TestDistributedShell.class.getName());
  final File tmpDir = new File(basedir, "tmpDir");
  tmpDir.mkdirs();
  final File customShellScript = new File(tmpDir, "custom_script.sh");
  if (customShellScript.exists()) {
    customShellScript.delete();
  }
  if (!customShellScript.createNewFile()) {
    Assert.fail("Can not create custom shell script file.");
  }
  PrintWriter fileWriter = new PrintWriter(customShellScript);
  // set the output to DEBUG level
  fileWriter.write("echo testDSShellWithShellScript");
  fileWriter.close();
  System.out.println(customShellScript.getAbsolutePath());
  String[] args = {
      "--jar",
      APPMASTER_JAR,
      "--num_containers",
      "1",
      "--shell_script",
      customShellScript.getAbsolutePath(),
      "--master_memory",
      "512",
      "--master_vcores",
      "2",
      "--master_gcores",
      "0",
      "--container_memory",
      "128",
      "--container_vcores",
      "1",
      "--container_gcores",
      "0"
  };

  LOG.info("Initializing DS Client");
  final Client client =
      new Client(new Configuration(yarnCluster.getConfig()));
  boolean initSuccess = client.init(args);
  Assert.assertTrue(initSuccess);
  LOG.info("Running DS Client");
  boolean result = client.run();
  LOG.info("Client run completed. Result=" + result);
  List<String> expectedContent = new ArrayList<String>();
  expectedContent.add("testDSShellWithShellScript");
  verifyContainerLog(1, expectedContent, false, "");
}
 
Example 19
Project: stockmanagemet-beta-   File: addpro.java   View Source Code Vote up 4 votes
private void addbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addbActionPerformed
    // Add Button

    try {
        if (namei.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Enter item!", "Oops Wait...!", JOptionPane.ERROR_MESSAGE);
        } else {
            BufferedReader rdfile = new BufferedReader(new FileReader("items.txt"));

            String[] itemline = new String[100];
            String prod = "";
            int qty = 0;
            double price = 0.0;
            boolean found = false;

            int x = 0;
            while ((itemline[x] = rdfile.readLine()) != null) {
                x++;
            }
            rdfile.close();

            if (!(x >= 100)) {
                prod = namei.getText();

                for (int j = 0; itemline[j] != null; j++) {      //check whether item is in the list already
                    String[] temp = itemline[j].split("\t");

                    if (prod.equals(temp[0])) {
                        found = true;
                    }
                }

                if (found) {
                    JOptionPane.showMessageDialog(null, "Item already exist!\nSuggestion: Update Item", "", JOptionPane.WARNING_MESSAGE);
                } else {
                    qty = Integer.parseInt(qtyi.getText());
                    price = Double.parseDouble(amti.getText());

                    itemline[x] = prod + "\t" + qty + "\t" + price;

                    PrintWriter wrfile = new PrintWriter(new FileWriter("items.txt"));

                    for (int j = 0; itemline[j] != null; j++) {
                        wrfile.println(itemline[j]);
                    }

                    wrfile.close();

                    JOptionPane.showMessageDialog(null, "Succesfully Added!", " Ok!  :-)", JOptionPane.INFORMATION_MESSAGE);
                }
            } else {
                JOptionPane.showMessageDialog(null, "Inventory Full!", "Warning!", JOptionPane.WARNING_MESSAGE);
            }
        }

        namei.setText("");
        qtyi.setText("");
        amti.setText("");

    } catch (IOException e) {
    }
}
 
Example 20
Project: Logistics-guard   File: CrashHandler.java   View Source Code Vote up 4 votes
/**
 * 保存错误信息到文件中
 *
 * @param ex
 * @return 返回文件名称, 便于将文件传送到服务器
 */
private String saveCrashInfo2File(Throwable ex) {

    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();
        sb.append(key + "=" + value + "\n");
    }
    sb.append("******************Start******************\r\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);
    sb.append("******************End******************\r\n");

    try {
        long timestamp = System.currentTimeMillis();
        String time = format.format(new Date());
        String fileName = "crash-" + time + "-" + timestamp + ".log";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory() + "/AAACrash/";
            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(TAG, "an error occured while writing file...", e);
    }
    return null;
}