Example usage for java.io Writer close

List of usage examples for java.io Writer close

Introduction

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

Prototype

public abstract void close() throws IOException;

Source Link

Document

Closes the stream, flushing it first.

Usage

From source file:juicebox.tools.utils.common.MatrixTools.java

/**
 * Write data from matrix out to specified file with each row on a separate line
 *
 * @param filename//from  w w  w.ja va  2s .  c  o m
 * @param realMatrix
 */
public static void saveMatrixText(String filename, RealMatrix realMatrix) {
    Writer writer = null;
    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
        double[][] matrix = realMatrix.getData();
        for (double[] row : matrix) {
            writer.write(Arrays.toString(row) + "\n");
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:dk.clarin.tools.workflow.java

/**
* Sends an HTTP GET request to a url/*w w  w .  j  a v  a  2  s. c  om*/
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestString - all the request parameters (Example: "param1=val1&param2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/

public static int sendRequest(String result, String endpoint, String requestString, bracmat BracMat,
        String filename, String jobID, boolean postmethod) {
    int code = 0;
    String message = "";
    //String filelist;
    if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
        // Send a GET or POST request to the servlet
        try {
            // Construct data
            String requestResult = "";
            String urlStr = endpoint;
            if (postmethod) // HTTP POST
            {
                logger.debug("HTTP POST");
                StringReader input = new StringReader(requestString);
                StringWriter output = new StringWriter();
                URL endp = new URL(endpoint);

                HttpURLConnection urlc = null;
                try {
                    urlc = (HttpURLConnection) endp.openConnection();
                    try {
                        urlc.setRequestMethod("POST");
                    } catch (ProtocolException e) {
                        throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
                    }
                    urlc.setDoOutput(true);
                    urlc.setDoInput(true);
                    urlc.setUseCaches(false);
                    urlc.setAllowUserInteraction(false);
                    urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");

                    OutputStream out = urlc.getOutputStream();

                    try {
                        Writer writer = new OutputStreamWriter(out, "UTF-8");
                        pipe(input, writer);
                        writer.close();
                    } catch (IOException e) {
                        throw new Exception("IOException while posting data", e);
                    } finally {
                        if (out != null)
                            out.close();
                    }
                } catch (IOException e) {
                    throw new Exception("Connection error (is server running at " + endp + " ?): " + e);
                } finally {
                    if (urlc != null) {
                        code = urlc.getResponseCode();

                        if (code == 200) {
                            got200(result, BracMat, filename, jobID, urlc.getInputStream());
                        } else {
                            InputStream in = urlc.getInputStream();
                            try {
                                Reader reader = new InputStreamReader(in);
                                pipe(reader, output);
                                reader.close();
                                requestResult = output.toString();
                            } catch (IOException e) {
                                throw new Exception("IOException while reading response", e);
                            } finally {
                                if (in != null)
                                    in.close();
                            }
                            logger.debug("urlc.getResponseCode() == {}", code);
                            message = urlc.getResponseMessage();
                            didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                    postmethod, urlStr, message, requestResult);
                        }
                        urlc.disconnect();
                    } else {
                        code = 0;
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                }
                //requestResult = output.toString();
                logger.debug("postData returns " + requestResult);
            } else // HTTP GET
            {
                logger.debug("HTTP GET");
                // Send data

                if (requestString != null && requestString.length() > 0) {
                    urlStr += "?" + requestString;
                }
                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                conn.connect();

                // Cast to a HttpURLConnection
                if (conn instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) conn;
                    code = httpConnection.getResponseCode();
                    logger.debug("httpConnection.getResponseCode() == {}", code);
                    message = httpConnection.getResponseMessage();
                    BufferedReader rd;
                    StringBuilder sb = new StringBuilder();
                    ;
                    //String line;
                    if (code == 200) {
                        got200(result, BracMat, filename, jobID, httpConnection.getInputStream());
                    } else {
                        // Get the error response
                        rd = new BufferedReader(new InputStreamReader(httpConnection.getErrorStream()));
                        int nextChar;
                        while ((nextChar = rd.read()) != -1) {
                            sb.append((char) nextChar);
                        }
                        rd.close();
                        requestResult = sb.toString();
                        didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID,
                                postmethod, urlStr, message, requestResult);
                    }
                } else {
                    code = 0;
                    didnotget200(code, result, endpoint, requestString, BracMat, filename, jobID, postmethod,
                            urlStr, message, requestResult);
                }
            }
            logger.debug("Job " + jobID + " receives status code [" + code + "] from tool.");
        } catch (Exception e) {
            //jobs = 0; // No more jobs to process now, probably the tool is not reachable
            logger.warn("Job " + jobID + " aborted. Reason:" + e.getMessage());
            /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
        }
    } else {
        //jobs = 0; // No more jobs to process now, probably the tool is not integrated at all
        logger.warn("Job " + jobID + " aborted. Endpoint must start with 'http://' or 'https://'. (" + endpoint
                + ")");
        /*filelist =*/ BracMat.Eval("abortJob$(" + result + "." + jobID + ")");
    }
    return code;
}

From source file:juicebox.tools.utils.juicer.apa.APAUtils.java

/**
 * @param filename//  www .  j a  v  a  2  s  .  com
 * @param matrix
 */
public static void saveMeasures(String filename, RealMatrix matrix) {

    Writer writer = null;

    APARegionStatistics apaStats = new APARegionStatistics(matrix);

    try {
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "utf-8"));
        writer.write("P2M" + '\t' + apaStats.getPeak2mean() + '\n');
        writer.write("P2UL" + '\t' + apaStats.getPeak2UL() + '\n');
        writer.write("P2UR" + '\t' + apaStats.getPeak2UR() + '\n');
        writer.write("P2LL" + '\t' + apaStats.getPeak2LL() + '\n');
        writer.write("P2LR" + '\t' + apaStats.getPeak2LR() + '\n');
        writer.write("ZscoreLL" + '\t' + apaStats.getZscoreLL());
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:com.nary.io.FileUtils.java

public static void writeFile(File outFile, String content) throws IOException {
    Writer outWriter = null;
    try {/* w ww  . j  a  v a2s  .c om*/
        outWriter = cfEngine.thisPlatform.getFileIO().getFileWriter(outFile);
        outWriter.write(content);
        outWriter.flush();
    } finally {
        try {
            if (outWriter != null)
                outWriter.close();
        } catch (Exception ignoreCloseException) {
        }
    }
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;

    try {//w w w.  jav a 2s  .c o  m
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:dataGen.DataGen.java

/**
 * Creates normal or uniform distributed Test-Data, without correlation.
 * The resulting Data is stored in the resources Folder.
 * @param dimensions//from   w  w w . j a v a2  s.com
 *       The dimension count of the resulting Data
 * @param rowCount
 *       How many data tuples should be created?
 * @throws IOException
 *       If Stream to a File couldn't be written/closed 
 */
public static void genData(int dimensions, int rowCount) throws IOException {
    logger.info("Generating uniform random Data with " + rowCount + " Tuples in " + dimensions + " dimensions");
    Writer fw = new FileWriter("src/main/resources/random-" + rowCount + "-" + dimensions + ".dat");
    Random gen = new Random();

    for (int i = 1; i <= rowCount; i++) {
        // Each Row should start with the Row count
        String row = i + " ";
        // Files should be created OS/Language independent
        DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();
        dfs.setDecimalSeparator('.');
        NumberFormat nf = new DecimalFormat("0.000000000", dfs);

        for (int j = 0; j < dimensions; j++) {
            Float n = gen.nextFloat();
            row = row + nf.format(n) + " ";
        }
        fw.write(row);
        fw.append(System.getProperty("line.separator"));
    }
    fw.close();
    logger.info(rowCount + " entries generated");
}

From source file:com.zimbra.common.util.ByteUtil.java

/**
 * Closes the given writer and ignores any exceptions.
 * @param w the <tt>Writer</tt>, may be <tt>null</tt>
 *//*from   w w w  .  j  av a 2 s.com*/
public static void closeWriter(Writer w) {
    if (w == null) {
        return;
    }
    try {
        w.close();
    } catch (IOException e) {
        ZimbraLog.misc.debug("ignoring exception while closing writer", e);
    }
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

protected static void generateActorHelpTOC(final RootDoc root, final Collection<ClassDoc> classes)
        throws IOException, ClassNotFoundException {
    String template = FileUtils.readFileToString(new File(
            "C:\\data\\development\\workspaces\\isencia-workspaces\\passerelle-V7\\com.isencia.passerelle.doc.generator\\src\\main\\java\\tocTemplate.vm"));
    Map<String, String> actorClassNameMap = new TreeMap<String, String>();
    for (ClassDoc classDoc : classes) {
        actorClassNameMap.put(_generateShortClassName(classDoc), _generateClassName(classDoc));
    }//from w  w  w . j  a v a  2s.c  o m
    Writer resultWriter = new StringWriter();
    try {
        Context velocityContext = new VelocityContext();
        velocityContext.put("allActorClasses", actorClassNameMap);

        velocity.evaluate(velocityContext, resultWriter, "TOC template", template);
        String res = resultWriter.toString();
        _writeTOC(res);
    } finally {
        try {
            resultWriter.close();
        } catch (Exception e) {
        }
    }
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

protected static void generateActorHelpIndex(final RootDoc root, final Collection<ClassDoc> classes)
        throws IOException, ClassNotFoundException {
    String template = FileUtils.readFileToString(new File(
            "C:\\data\\development\\workspaces\\isencia-workspaces\\passerelle-V7\\com.isencia.passerelle.doc.generator\\src\\main\\java\\indexTemplate.vm"));
    Map<String, String> actorClassNameMap = new TreeMap<String, String>();
    for (ClassDoc classDoc : classes) {
        actorClassNameMap.put(_generateShortClassName(classDoc), _generateClassName(classDoc));
    }//  w w  w . ja  v  a2  s  .  c  om
    Writer resultWriter = new StringWriter();
    try {
        Context velocityContext = new VelocityContext();
        velocityContext.put("allActorClasses", actorClassNameMap);

        velocity.evaluate(velocityContext, resultWriter, "index template", template);
        String res = resultWriter.toString();
        _writeIndex(res);
    } finally {
        try {
            resultWriter.close();
        } catch (Exception e) {
        }
    }
}

From source file:doc.doclets.WorkbenchHelpDoclet.java

protected static void generateActorHelpHtmlTOC(final RootDoc root, final Collection<ClassDoc> classes)
        throws IOException, ClassNotFoundException {
    String template = FileUtils.readFileToString(new File(
            "C:\\data\\development\\workspaces\\isencia-workspaces\\passerelle-V7\\com.isencia.passerelle.doc.generator\\src\\main\\java\\htmlTocTemplate.vm"));
    Map<String, String> actorClassNameMap = new TreeMap<String, String>();
    for (ClassDoc classDoc : classes) {
        actorClassNameMap.put(_generateShortClassName(classDoc), _generateClassName(classDoc));
    }/*from   w w  w . ja v a 2  s  .c  o m*/
    Writer resultWriter = new StringWriter();
    try {
        Context velocityContext = new VelocityContext();
        velocityContext.put("allActorClasses", actorClassNameMap);

        velocity.evaluate(velocityContext, resultWriter, "TOC template", template);
        String res = resultWriter.toString();
        _writeHtmlTOC(res);
    } finally {
        try {
            resultWriter.close();
        } catch (Exception e) {
        }
    }
}