Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:org.envirocar.aggregation.AggregatedTracksServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(), Charset.forName("UTF-8"));

    resp.setContentType("application/json");

    String uri = req.getRequestURI();
    String subPath = uri.substring(uri.indexOf(PATH) + PATH.length());

    String trackId = null;//from  w ww . ja  va  2s  .  co m
    if (!subPath.isEmpty() && !(subPath.length() == 1 && subPath.equals("/"))) {
        trackId = subPath.startsWith("/") ? subPath.substring(1) : subPath;
    }

    String json;
    try {
        if (trackId != null) {
            json = createTrackExists(trackId);
        } else {
            json = createAggregatedTracksList();
        }
    } catch (SQLException e) {
        throw new IOException(e);
    }

    writer.append(json);

    writer.flush();
    writer.close();

    resp.setStatus(200);
}

From source file:org.tellervo.desktop.wsi.JaxbResponseHandler.java

public T toDocument(final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }/*www.  jav  a 2 s.  co m*/

    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }

    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    /**
     * Methodology
     * 1) Save XML to disk temporarily (it can be big, 
     *       we might want to look at it as a raw file)
     * 2) If we can't write to disk, throw IOException
     * 3) Try to parse
     * 4) Throw error with the raw document (it's malformed XML)
     */

    File tempFile = null;
    OutputStreamWriter fileOut = null;
    boolean usefulFile = false; // preserve this file outside this local context?

    try {
        tempFile = File.createTempFile("tellervo", ".xml");
        fileOut = new OutputStreamWriter(new FileOutputStream(tempFile, false), charset);

        // ok, dump the webservice xml to a file
        BufferedReader webIn = new BufferedReader(new InputStreamReader(instream, charset));

        char indata[] = new char[8192];
        int inlen;

        // write the file out
        while ((inlen = webIn.read(indata)) >= 0)
            fileOut.write(indata, 0, inlen);

        fileOut.close();
    } catch (IOException ioe) {
        // File I/O failed (?!) Clean up and re-throw the IOE.
        if (fileOut != null)
            fileOut.close();
        if (tempFile != null)
            tempFile.delete();

        throw ioe;
    }

    try {
        Unmarshaller um = context.createUnmarshaller();
        ValidationEventCollector vec = new ValidationEventCollector();

        // validate against this schema
        um.setSchema(validateSchema);

        // collect events instead of throwing exceptions
        um.setEventHandler(vec);

        // do the magic!
        Object ret = um.unmarshal(tempFile);

        // typesafe way of checking if this is the right type!
        return returnClass.cast(ret);
    } catch (UnmarshalException ume) {
        usefulFile = true;
        throw new ResponseProcessingException(ume, tempFile);

    } catch (JAXBException jaxbe) {
        usefulFile = true;
        throw new ResponseProcessingException(jaxbe, tempFile);

    } catch (ClassCastException cce) {
        usefulFile = true;
        throw new ResponseProcessingException(cce, tempFile);

    } finally {
        // clean up and delete
        if (tempFile != null) {
            if (!usefulFile)
                tempFile.delete();
            else
                tempFile.deleteOnExit();
        }
    }

    /*
    try {
       um.un
    } catch (JDOMException jdome) {
    // this document must be malformed
    usefulFile = true;
    throw new XMLParsingException(jdome, tempFile);
       } 
    } catch (IOException ioe) {
       // well, something there failed and it was lower level than just bad XML...
       if(tempFile != null) {
    usefulFile = true;
    throw new XMLParsingException(ioe, tempFile);
       }
               
       throw new XMLParsingException(ioe);
               
    } finally {
       // make sure we closed our file
       if(fileOut != null)
    fileOut.close();
               
       // make sure we delete it, too
       if(tempFile != null)
       {
    if (!usefulFile)
       tempFile.delete();
    else
       tempFile.deleteOnExit();
       }
    }
    */
}

From source file:gate.creole.gazetteer.GazetteerList.java

/**
 * Stores the list to the specified url/*from w w  w  .  j  av  a 2  s.  co m*/
 * 
 * @throws ResourceInstantiationException
 */
public void store() throws ResourceInstantiationException {
    try {
        if (null == url) {
            throw new ResourceInstantiationException("URL not specified (null)");
        }

        File fileo = Files.fileFromURL(url);

        fileo.delete();
        OutputStreamWriter listWriter = new OutputStreamWriter(new FileOutputStream(fileo), encoding);
        // BufferedWriter listWriter = new BufferedWriter(new
        // FileWriter(fileo));
        Iterator<GazetteerNode> iter = entries.iterator();
        while (iter.hasNext()) {
            listWriter.write(iter.next().toString());
            listWriter.write(13);
            listWriter.write(10);
        }
        listWriter.close();
    } catch (Exception x) {
        throw new ResourceInstantiationException(x.getClass() + ":" + x.getMessage());
    }
    isModified = false;
}

From source file:com.networknt.light.server.LoadPageMojo.java

private void writeSqlToOutputFile() {
    OutputStreamWriter out = null;
    try {//w  w  w.j  a v  a2s. c o  m
        final StringBuffer path = new StringBuffer();
        path.append(outputDirectory);
        path.append(System.getProperty("file.separator"));
        path.append("server.sql");

        final FileOutputStream fos = new FileOutputStream(path.toString());
        out = new OutputStreamWriter(fos, encoding);
        out.write(sqlString);

    } catch (final IOException e) {
        getLog().error(e.getMessage());
    } finally {
        if (null != out) {
            try {
                out.close();
            } catch (final IOException e) {
                getLog().error(e.getMessage());
            }
        }
    }
}

From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**//from w  ww .  ja  v  a 2  s. co  m
 * Run the AuthGetTokeb Web API Method
 */
public Long execute() {

    //Build url Parameter String
    String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password;

    //Try to execute the API Method
    try {

        URL url = new URL(userAuthentication.getBaseURL());
        URLConnection conn = url.openConnection();

        //add user agent to the request header
        conn.setRequestProperty("User-Agent", USER_AGENT);

        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //Read the response JSON
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line).append("\n");
        }

        JSONObject json = (JSONObject) new JSONParser().parse(text.toString());

        this.status = (Long) json.get("status");
        if (this.status != -1L) {
            this.authToken = (String) json.get("result");

            //Save the AuthToken
            userAuthentication.setAuthToken((String) json.get("result"));
        }

        writer.close();
        reader.close();

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

    }

    return this.status;
}

From source file:com.hqme.cm.cache.StreamingServer.java

public void run() {
    if (UntenCacheService.sIsDebugMode) {
        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
        Thread.currentThread().setName(getClass().getName());
    }//from   w  w  w.  j a va  2s.c  o m

    isStopping = false;
    serverSocket = null;
    serverPortPrefs = new File(UntenCacheService.sPluginContext.getFilesDir(), tag_PlaybackPortNumber);
    try {
        String text = new BufferedReader(new InputStreamReader(new FileInputStream(serverPortPrefs), "UTF16"),
                1 << 10).readLine();
        serverPortNumber = Integer.valueOf(text.trim());
    } catch (Throwable ignore) {
        serverPortNumber = 0;
    }

    int retries = 2;
    while (retries-- > 0) {
        try {
            serverSocket = new ServerSocket(serverPortNumber);
            if (serverPortNumber == 0) {
                serverPortNumber = serverSocket.getLocalPort();
                try {
                    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(serverPortPrefs),
                            "UTF16");
                    writer.write(serverPortNumber + "\r\n");
                    writer.flush();
                    writer.close();
                } catch (Throwable ignore) {
                }
            }
            clientBox = new ClientBox[MAX_CLIENTS];
            retries = 0;

            UntenCacheService.debugLog(sTag, "run: Streaming Media Server is now active on TCP port # %d",
                    serverPortNumber);
            handleRequests();
        } catch (IOException fault) {
            fault.printStackTrace();
            try {
                serverPortPrefs.delete();
            } catch (Throwable ignore) {
            }
        }
    }
}

From source file:com.webarch.common.io.xml.XMLEditor.java

public boolean save(OutputStream os, Document document) {
    boolean flag = true;
    XMLWriter writer = null;/*w w w  .ja  v  a  2 s .c  o m*/
    OutputStreamWriter outputStream = null;
    try {
        outputStream = new OutputStreamWriter(os, DAFAULT_CHARSET);
        writer = new XMLWriter(outputStream);
        writer.write(document);
        writer.flush();
    } catch (Exception ex) {
        log.error("?xml", ex);
        flag = false;
        throw new RuntimeException(ex);

    } finally {
        try {
            if (null != writer) {
                writer.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }

        } catch (IOException e) {
            log.error("?xml:", e);

        }
    }
    return flag;
}

From source file:AIR.Common.Web.HttpWebHelper.java

public String getResponse(String urlString, String postRequestParams, String contentMimeType) throws Exception {
    try {/*w w w  .ja v a 2s  .c  o  m*/
        URL url = new URL(urlString);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setRequestProperty("Content-Type",
                String.format("application/%s; charset=UTF-8", contentMimeType));
        urlConn.setUseCaches(false);

        // the request will return a response
        urlConn.setDoInput(true);

        // set request method to POST
        urlConn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
        writer.write(postRequestParams);
        writer.flush();

        // reads response, store line by line in an array of Strings
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuffer bfr = new StringBuffer();

        String line = "";
        while ((line = reader.readLine()) != null) {
            bfr.append(line + "\n");
        }

        reader.close();
        writer.close();
        urlConn.disconnect();
        return bfr.toString();

    } catch (Exception exp) {
        StringWriter strn = new StringWriter();
        exp.printStackTrace(new PrintWriter(strn));
        _logger.error(strn.toString());
        exp.printStackTrace();
        throw new Exception(exp);
    }
}

From source file:com.networknt.light.rule.LoadRuleMojo.java

private void writeSqlToOutputFile() {
    OutputStreamWriter out = null;
    try {//from  www. j  av a 2 s  .co m
        final StringBuffer path = new StringBuffer();
        path.append(outputDirectory);
        path.append(System.getProperty("file.separator"));
        path.append("rule.sql");

        final FileOutputStream fos = new FileOutputStream(path.toString());
        out = new OutputStreamWriter(fos, encoding);
        out.write(sqlString);

    } catch (final IOException e) {
        getLog().error(e.getMessage());
    } finally {
        if (null != out) {
            try {
                out.close();
            } catch (final IOException e) {
                getLog().error(e.getMessage());
            }
        }
    }
}

From source file:playground.christoph.icem2011.LogLinkTravelTime.java

@Override
public void notifyAfterMobsim(AfterMobsimEvent event) {
    try {/*from  w  w  w .j ava  2s .  co  m*/
        log.info("Writing expected travel time files...");
        Counter counter = new Counter("Writing expected travel time files: ");
        for (Link link : links) {
            String file = event.getControler().getControlerIO().getIterationFilename(event.getIteration(),
                    "expectedLinkTravelTimes_" + link.getId() + ".txt");

            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
            BufferedWriter bw = new BufferedWriter(osw);

            bw.write("time" + delimiter + "expected travel time" + delimiter + "measured travel time" + "\n");
            //            bw.write(data.get(link.getId()).toString());
            List<Double> etts = data.get(link.getId());
            for (int i = 0; i < times.size(); i++) {
                double time = times.get(i);
                double ett = etts.get(i);
                double mtt = measuredTravelTime.getLinkTravelTime(link, time, null, null);
                String string = time + delimiter + ett + delimiter + mtt + "\n";
                bw.write(string);
            }

            bw.close();
            osw.close();
            fos.close();

            String chartFile = event.getControler().getControlerIO().getIterationFilename(event.getIteration(),
                    "expectedLinkTravelTimes_" + link.getId() + ".png");
            createChart(link, chartFile);
            counter.incCounter();
        }
        counter.printCounter();
        log.info("done.");
    } catch (IOException e1) {
        throw new RuntimeException(e1);
    }
}