Example usage for java.io PrintWriter PrintWriter

List of usage examples for java.io PrintWriter PrintWriter

Introduction

In this page you can find the example usage for java.io PrintWriter PrintWriter.

Prototype

public PrintWriter(File file) throws FileNotFoundException 

Source Link

Document

Creates a new PrintWriter, without automatic line flushing, with the specified file.

Usage

From source file:com.dongli.model.MyJSONData.java

public static String createObject(MyJSONObject mjo) throws MyRESTException {

    // generate uid for this object
    String uid = UIDGenerator.getUID();
    mjo.setUID(uid);/*ww w.  java 2  s  .  c o  m*/

    // tmp path of data file to store this object. The file will to sent to S3 later.
    String path = "/tmp/" + uid;

    try {
        FileWriter fw = new FileWriter(path, false);
        PrintWriter pw = new PrintWriter(fw);
        pw.println(mjo.toString());
        pw.close();
        fw.close();
    } catch (IOException e) {
        // e.printStackTrace();
        // failed to create the new object
        File nf = new File(path);
        nf.delete();
        throw new MyRESTException("Failed to create the object " + uid + ".");
    }

    // create the new object on AWS S3 
    try {
        File uploadFile = new File(path);
        MyAWSStorage.getInstance().s3client
                .putObject(new PutObjectRequest(MyConfiguration.getInstance().bucket, uid, uploadFile));
    } catch (AmazonServiceException ase) {
        throw new MyRESTException("Failed to create the object " + uid + ".");
    } catch (AmazonClientException ace) {
        throw new MyRESTException("Failed to create the object " + uid + ".");
    }

    return uid;
}

From source file:com.memetix.gun4j.GunshortenAPI.java

protected static JSONObject post(final String serviceUrl, final String paramsString) throws Exception {
    final URL url = new URL(serviceUrl);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);

    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);//from  w  w w.j a va  2 s .co  m

    final PrintWriter pw = new PrintWriter(uc.getOutputStream());
    pw.write(paramsString);
    pw.close();
    uc.getOutputStream().close();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Gunshorten API: " + result);
        }
        return parseJSON(result);
    } finally {
        uc.getInputStream().close();
        if (uc.getErrorStream() != null) {
            uc.getErrorStream().close();
        }
    }
}

From source file:DateServer.java

public void run() {
    while (true) {
        try {/*from   ww  w  .  j  a  v a2s  .com*/
            Socket s = ss.accept();

            ObjectInputStream ois;
            ois = new ObjectInputStream(s.getInputStream());
            Locale l = (Locale) ois.readObject();

            PrintWriter pw;
            pw = new PrintWriter(s.getOutputStream());

            MessageFormat mf;
            mf = new MessageFormat("The date is {0, date, long}", l);

            Object[] args = { new Date() };

            pw.println(mf.format(args));

            pw.close();
        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

From source file:com.asual.summer.core.ErrorController.java

@ResponseViews({ AbstractResponseView.class, StringView.class })
public ModelAndView error(Exception ex) {

    Writer stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    ex.printStackTrace(printWriter);//w  w w  .ja v a2 s  .com

    ModelMap model = new ModelMap();
    model.addAttribute("error", ex);
    model.addAttribute("stackTrace", stringWriter.toString());
    return new ModelAndView("/error", model);
}

From source file:com.edmunds.etm.tools.urltoken.util.OutputWriter.java

@Autowired
public OutputWriter(CommandLocator commandLocator) {
    // Using the default charset is correct in this case, since we are writing to standard out.
    this.writer = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()));
    this.commandLocator = commandLocator;
}

From source file:FileTableHTML.java

public static String makeHTMLTable(String dirname) {
    // Look up the contents of the directory
    File dir = new File(dirname);
    String[] entries = dir.list();

    // Set up an output stream we can print the table to.
    // This is easier than concatenating strings all the time.
    StringWriter sout = new StringWriter();
    PrintWriter out = new PrintWriter(sout);

    // Print the directory name as the page title
    out.println("<H1>" + dirname + "</H1>");

    // Print an "up" link, unless we're already at the root
    String parent = dir.getParent();
    if ((parent != null) && (parent.length() > 0))
        out.println("<A HREF=\"" + parent + "\">Up to parent directory</A><P>");

    // Print out the table
    out.print("<TABLE BORDER=2 WIDTH=600><TR>");
    out.print("<TH>Name</TH><TH>Size</TH><TH>Modified</TH>");
    out.println("<TH>Readable?</TH><TH>Writable?</TH></TR>");
    for (int i = 0; i < entries.length; i++) {
        File f = new File(dir, entries[i]);
        out.println("<TR><TD>" + (f.isDirectory() ? "<a href=\"" + f + "\">" + entries[i] + "</a>" : entries[i])
                + "</TD><TD>" + f.length() + "</TD><TD>" + new Date(f.lastModified()) + "</TD><TD align=center>"
                + (f.canRead() ? "x" : " ") + "</TD><TD align=center>" + (f.canWrite() ? "x" : " ")
                + "</TD></TR>");
    }//w w w. j  av a  2  s .c  o  m
    out.println("</TABLE>");
    out.close();

    // Get the string of HTML from the StringWriter and return it.
    return sout.toString();
}

From source file:com.mobius.software.mqtt.performance.runner.util.FileUtil.java

public static void logErrors(UUID scenarioID, List<ClientReport> reports) {
    if (reports.isEmpty())
        return;/*from   www  .  j a v  a2  s.c  o m*/

    String filename = DIRECTORY_NAME + File.separator + scenarioID.toString() + LOG_EXTENSION;
    File log = new File(filename);
    if (!log.getParentFile().exists())
        log.getParentFile().mkdir();
    try (PrintWriter pw = new PrintWriter(log)) {
        for (ClientReport clientReport : reports) {
            List<ErrorReport> errorReports = clientReport.getErrors();
            if (!errorReports.isEmpty()) {
                String errorContent = ReportBuilder.buildError(clientReport.getIdentifier(), errorReports);
                pw.println(errorContent);
            }
        }
    } catch (IOException e) {
        logger.error("An error occured while writing error reports to file:" + e.getMessage());
    }

    if (log.length() == 0)
        log.delete();
}

From source file:org.esigate.HttpErrorPage.java

private static HttpEntity toMemoryEntity(Exception exception) {
    StringBuilderWriter out = new StringBuilderWriter(Parameters.DEFAULT_BUFFER_SIZE);
    PrintWriter pw = new PrintWriter(out);
    exception.printStackTrace(pw);/*  w ww.  ja  v  a 2s. c  om*/
    String content = out.toString();
    try {
        return toMemoryEntity(content);
    } finally {
        pw.close();
    }
}

From source file:org.bigloupe.web.monitor.util.JSONUtil.java

public static void writeJson(String fileName, Object object) throws IOException {
    JSONUtil.writeJson(new PrintWriter(fileName), object);
}

From source file:net.sf.sripathi.ws.mock.util.WebServiceutil.java

/**
 * Invokes the web service using SAAJ API.
 * //from w w  w  .ja va  2 s.c om
 * @param request soap request string.
 * @param url end point URL.
 * @param user user name for authentication.
 * @param password password for authentication.
 * 
 * @return response soap string.
 */
public static String callWebService(String request, String url, String user, String password) {

    if (request == null)
        request = "";
    try {
        SOAPConnection conn = SOAPConnectionFactory.newInstance().createConnection();

        MimeHeaders hd = new MimeHeaders();
        hd.addHeader("Content-Type", "text/xml");
        if (StringUtil.isValid(user) && StringUtil.isValid(password)) {
            String authorization = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            hd.addHeader("Authorization", "Basic " + authorization);
        }

        SOAPMessage msg = MessageFactory.newInstance().createMessage(hd,
                new ByteArrayInputStream(request.getBytes()));
        SOAPMessage resp = conn.call(msg, url);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        resp.writeTo(baos);
        return new String(baos.toByteArray());
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }
}