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:com.example.appengine.UrlFetchServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    String id = req.getParameter("id");
    String text = req.getParameter("text");

    if (id == null || text == null || id == "" || text == "") {
        req.setAttribute("error", "invalid input");
        req.getRequestDispatcher("/main.jsp").forward(req, resp);
        return;/*from  ww  w.  j a  va2  s. c o m*/
    }

    JSONObject jsonObj = new JSONObject().put("userId", 33).put("id", id).put("title", text).put("body", text);

    // [START complex]
    URL url = new URL("http://jsonplaceholder.typicode.com/posts/" + id);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("PUT");

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(URLEncoder.encode(jsonObj.toString(), "UTF-8"));
    writer.close();

    int respCode = conn.getResponseCode(); // New items get NOT_FOUND on PUT
    if (respCode == HttpURLConnection.HTTP_OK || respCode == HttpURLConnection.HTTP_NOT_FOUND) {
        req.setAttribute("error", "");
        StringBuffer response = new StringBuffer();
        String line;

        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
        reader.close();
        req.setAttribute("response", response.toString());
    } else {
        req.setAttribute("error", conn.getResponseCode() + " " + conn.getResponseMessage());
    }
    // [END complex]
    req.getRequestDispatcher("/main.jsp").forward(req, resp);
}

From source file:com.vmware.identity.HealthStatusController.java

/**
 * Handle GET request for the health status
 *//*from  ww w  .  jav a  2 s .  c om*/
@RequestMapping(value = "/HealthStatus", method = RequestMethod.GET)
public void getHealthStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException {

    Validate.notNull(request, "HttpServletRequest should not be null.");
    Validate.notNull(response, "HttpServletResponse should not be null.");

    // we are going to be very simple in this request processing for now
    // and just report if we are "reachable"
    // we also do not worry about the sender's identity
    // (in reality CM will include the SAML token in the header,
    // and so generally it means they successfully obtained it through sso ...)
    logger.debug("Handling getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
            request.getRequestURL());

    try {
        response.setHeader("Content-Type", "application/xml; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStreamWriter osw = new OutputStreamWriter(response.getOutputStream(), UTF8);
        try {
            osw.write(healthStatusXml);
        } finally {
            osw.close();
        }

        logger.debug("Handled getHealthStatus HTTP request; method:{} url:{}", request.getMethod(),
                request.getRequestURL());
    } catch (Exception e) {
        logger.error("Failed to return Health Status with [%s]." + e.toString(), e);
        throw new ServletException(e); // let the exception bubble up and show in the response since this is not user-facing
    }
}

From source file:com.cloudbees.mtslaves.client.RemoteReference.java

protected HttpURLConnection postJson(HttpURLConnection con, JSONObject json) throws IOException {
    try {//from   w w w .  j a  va  2  s  . c om
        token.authorizeRequest(con);
        con.setDoOutput(true);
        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        con.connect();

        // send JSON
        OutputStreamWriter w = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
        json.write(w);
        w.close();

        return con;
    } catch (IOException e) {
        throw (IOException) new IOException("Failed to POST to " + url).initCause(e);
    }
}

From source file:com.irahul.worldclock.WorldClockData.java

private void writeToFile(String jsonString) {
    Log.d(TAG, "Writing JSON to file: " + jsonString);
    try {//from  w w  w.ja  v  a 2s .  co m
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        OutputStreamWriter osw = new OutputStreamWriter(fos);

        osw.write(jsonString);
        osw.flush();
        osw.close();
        fos.close();

    } catch (FileNotFoundException e) {
        throw new WorldClockException(e);
    } catch (IOException e) {
        throw new WorldClockException(e);
    }
}

From source file:net.noday.cat.web.admin.DwzManager.java

@RequestMapping(method = RequestMethod.POST)
public Model gen(@RequestParam("url") String url, @RequestParam("alias") String alias, Model m) {
    try {// www .  j  av a 2  s.  c  om
        String urlstr = "http://dwz.cn/create.php";
        URL requrl = new URL(urlstr);
        URLConnection conn = requrl.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        String param = String.format(Locale.CHINA, "url=%s&alias=%s", url, alias);
        out.write(param);
        out.flush();
        out.close();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line = reader.readLine();
        //{"longurl":"http:\/\/www.hao123.com\/","status":0,"tinyurl":"http:\/\/dwz.cn\/1RIKG"}
        ObjectMapper mapper = new ObjectMapper();
        Dwz dwz = mapper.readValue(line, Dwz.class);
        if (dwz.getStatus() == 0) {
            responseData(m, dwz.getTinyurl());
        } else {
            responseMsg(m, false, dwz.getErr_msg());
        }
    } catch (MalformedURLException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        responseMsg(m, false, e.getMessage());
    }
    return m;
}

From source file:org.compose.mobilesdk.android.ServerRequestTask.java

public String doPUTRequest(URL requestUrl) {
    String responseString = null;

    try {// w  w  w  . j  av  a 2  s  .co m
        HttpURLConnection httpCon = (HttpURLConnection) requestUrl.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Authorization", header_parameters);
        httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        httpCon.setRequestProperty("Accept", "*/*");

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("" + this.message);
        out.close();

        if (DEBUG) {
            BufferedReader in = null;
            if (httpCon.getErrorStream() != null)
                in = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
            else
                in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {

                Log.i(DEBUG_INFO, inputLine);
            }
            in.close();

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return responseString;
}

From source file:com.pinterest.deployservice.common.HTTPClient.java

private String internalCall(String url, String method, String payload, Map<String, String> headers, int retries)
        throws Exception {
    HttpURLConnection conn = null;
    Exception lastException = null;

    for (int i = 0; i < retries; i++) {
        try {//from w w  w.  ja v a 2  s .c o m
            URL urlObj = new URL(url);
            conn = (HttpURLConnection) urlObj.openConnection();
            conn.setRequestMethod(method);
            conn.setRequestProperty("Accept-Charset", "UTF-8");

            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            if (StringUtils.isNotEmpty(payload)) {
                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                writer.write(payload);
                writer.flush();
                writer.close();
            }

            String ret = IOUtils.toString(conn.getInputStream(), "UTF-8");
            int responseCode = conn.getResponseCode();
            if (responseCode >= 400) {
                throw new DeployInternalException("HTTP request failed, status = {}, content = {}",
                        responseCode, ret);
            }
            LOG.info("HTTP Request returned with response code {} for URL {}", responseCode, url);
            return ret;
        } catch (Exception e) {
            lastException = e;
            LOG.error("Failed to send HTTP Request to {}, with payload {}, with headers {}", url, payload,
                    headers, e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
    throw lastException;
}

From source file:technology.tikal.accounts.dao.rest.SessionDaoRest.java

private void guardar(UserSession objeto, int intento) {
    //basic auth string
    String basicAuthString = config.getUser() + ":" + config.getPassword();
    basicAuthString = new String(Base64.encodeBase64(basicAuthString.getBytes()));
    basicAuthString = "Basic " + basicAuthString;

    //mensaje remoto
    try {// w w  w. j a  v a 2s  . c o m
        //config
        URL url = new URL(config.getUrl());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(config.getMethod());
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Authorization", basicAuthString);
        connection.setInstanceFollowRedirects(false);
        //write
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(mapper.writeValueAsString(objeto));
        //close
        writer.close();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            return;
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationRefused.SessionDaoRest.guardar" },
                    new String[] { connection.getResponseCode() + "" }, ""));
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        if (intento <= maxRetry) {
            this.guardar(objeto, intento + 1);
        } else {
            throw new MessageSourceResolvableException(new DefaultMessageSourceResolvable(
                    new String[] { "SessionCreationError.SessionDaoRest.guardar" },
                    new String[] { e.getMessage() }, ""));
        }
    }
}

From source file:com.athena.chameleon.engine.utils.FileUtil.java

/**
 * //  w w w .  j a v a  2 s  .com
 * ? ??  .
 *
 * @param zipFilePath ? 
 * @param unzipDirPath ?   
 * @param declaredEncoding ?  
 * @return String  ?  
 * @throws IOException
 */
public static String extract(String zipFilePath, String unzipDirPath, String declaredEncoding)
        throws IOException {
    ZipFile zipFile = null;

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("[ZipUtil] zipFilePath :" + zipFilePath);
        }

        String unZipDir = (unzipDirPath == null)
                ? zipFilePath.substring(0, zipFilePath.lastIndexOf('.')) + File.separator
                : unzipDirPath + File.separator;
        if (logger.isDebugEnabled()) {
            logger.debug("[ZipUtil] unzipDirPath :" + unZipDir);
        }

        zipFile = new ZipFile(zipFilePath, "EUC-KR");

        Enumeration<?> e = zipFile.getEntries();
        for (; e.hasMoreElements();) {
            FileOutputStream output = null;
            InputStream input = null;
            String entryName;

            try {
                byte[] data;
                ZipEntry entry = (ZipEntry) e.nextElement();

                if (logger.isDebugEnabled()) {
                    logger.debug("[ZipUtil] current entry:" + entry.getName());
                }

                entryName = entry.getName().replace('\\', '/');
                if (entry.isDirectory()) {
                    File dir = new File(unZipDir + entry.getName());
                    if (!dir.exists() && !dir.mkdirs()) {
                        throw new IOException("[ZipUtil] make directory fail");
                    }
                } else {
                    File outputFile = null;

                    try {
                        outputFile = new File(unZipDir + entry.getName());

                        if (entry.getSize() == 0 && entry.getName().indexOf('.') == -1) {
                            throw new Exception("[ZipUtil] This file may be a directory");
                        }

                        File parentDir = outputFile.getParentFile();
                        if (!parentDir.exists() && !parentDir.mkdirs()) {
                            throw new IOException("[ZipUtil] make directory fail");
                        }

                        input = zipFile.getInputStream(entry);
                        output = new FileOutputStream(outputFile);

                        String changeTarget = PropertyUtil.getProperty("unzip.change.target");

                        if (changeTarget.indexOf(
                                entryName.substring(entryName.lastIndexOf(".") + 1, entryName.length())) > -1) {

                            OutputStreamWriter osr = new OutputStreamWriter(output, declaredEncoding);

                            CharsetDetector detector = new CharsetDetector();
                            data = IOUtils.toByteArray(input, entry.getSize());
                            IOUtils.closeQuietly(input);
                            detector.setDeclaredEncoding(declaredEncoding);
                            detector.setText(data);
                            Reader reader = detector.detect().getReader();

                            int buffer = 0;
                            while (true) {
                                buffer = reader.read();
                                if (buffer == -1)
                                    break;

                                osr.write(buffer);
                            }
                            osr.close();

                        } else {
                            int len = 0;
                            byte buffer[] = new byte[1024];
                            while ((len = input.read(buffer)) > 0)
                                output.write(buffer, 0, len);
                        }

                    } catch (Exception ex2) {
                        ex2.printStackTrace();
                        if (!outputFile.exists() && !outputFile.mkdirs()) {
                            throw new IOException("[ZipUtil] make directory fail");
                        }
                    }
                }
            }

            catch (IOException ex) {
                throw ex;
            }

            catch (Exception ex) {
                throw new IOException("[ZipUtil] extract fail", ex);
            }

            finally {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }
        }
        return unZipDir;
    }

    catch (IOException e) {
        e.printStackTrace();
        throw e;
    }

    finally {
        if (zipFile != null) {
            zipFile.close();
        }
    }
}

From source file:de.zib.scalaris.examples.wikipedia.plugin.fourcaast.FourCaastAccounting.java

protected void pushSdrToServer(final WikiPageBeanBase page) {
    if (!page.getServiceUser().isEmpty()) {
        final String sdr = createSdr(page);
        //            System.out.println("Sending sdr...\n" + sdr);
        try {//from  w  w w.  j  a  v a 2  s.  c  om
            HttpURLConnection urlConn = (HttpURLConnection) accountingServer.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
            out.write(sdr);
            out.close();

            //read the result from the server (necessary for the request to be send!)
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line + '\n');
            }
            //                System.out.println(sb.toString());
            in.close();
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}