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:at.tugraz.sss.serv.util.SSFileU.java

public static void writeFileText(final File file, final String text) throws SSErr {

    OutputStreamWriter fileOut = null;

    try {/*from   www.j  a  v a  2s .c om*/
        //    final byte[]        bytes      = text.getBytes();

        fileOut = new OutputStreamWriter(openOrCreateFileWithPathForWrite(file.getAbsolutePath()),
                Charset.forName(SSEncodingU.utf8.toString()));

        fileOut.write(text);
        //      fileOut.write (bytes, 0, bytes.length);

    } catch (Exception error) {
        SSServErrReg.regErrThrow(error);
    } finally {

        if (fileOut != null) {

            try {
                fileOut.close();
            } catch (IOException error) {
                SSLogU.err(error);
            }
        }
    }
}

From source file:de.hybris.platform.marketplaceintegration.utils.impl.MarketplaceintegrationHttpUtilImpl.java

/**
 * Post data/*from w w w. j av  a 2s  .  c om*/
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    try {
        writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:com.commerce4j.storefront.controllers.CatalogController.java

/**
 * @param request/*  w  w  w . j a v  a 2s.  c  o  m*/
 * @param response
 */
public void featuredBrands(HttpServletRequest request, HttpServletResponse response) {
    Map<String, Object> responseModel = new HashMap<String, Object>();
    response.setContentType(HTTP_HEADER_JSON);
    Gson gson = new GsonBuilder().create();

    BrandDAO brandDAO = (BrandDAO) getApplicationContext().getBean("brandDAO");
    List<BrandDTO> brands = brandDAO.findAllFeatured();

    responseModel.put("responseCode", SUCCESS);
    responseModel.put("responseMessage", "Login Completo");
    responseModel.put("brands", brands);

    // serialize output
    try {

        OutputStreamWriter os = new OutputStreamWriter(response.getOutputStream(), "UTF8");
        String data = gson.toJson(responseModel);
        os.write(data);

        os.flush();
        os.close();
    } catch (IOException e) {
        logger.fatal(e);
    }
}

From source file:com.gdevelop.gwt.syncrpc.RemoteServiceSyncProxy.java

public Object doInvoke(RequestCallbackAdapter.ResponseReader responseReader, String requestData)
        throws Throwable {
    HttpURLConnection connection = null;
    InputStream is = null;/*from   ww  w  .j  a v  a2s  .  c om*/
    int statusCode;

    if (DUMP_PAYLOAD) {
        log.debug("Send request to {}", remoteServiceURL);
        log.debug("Request payload: {}", requestData);
    }

    // Send request
    CookieHandler oldCookieHandler = CookieHandler.getDefault();
    try {
        CookieHandler.setDefault(cookieManager);

        URL url = new URL(remoteServiceURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty(RpcRequestBuilder.STRONG_NAME_HEADER, serializationPolicyName);
        connection.setRequestProperty(RpcRequestBuilder.MODULE_BASE_HEADER, moduleBaseURL);
        connection.setRequestProperty("Content-Type", "text/x-gwt-rpc; charset=utf-8");
        connection.setRequestProperty("Content-Length", "" + requestData.getBytes("UTF-8").length);

        CookieStore store = cookieManager.getCookieStore();
        String cookiesStr = "";

        for (HttpCookie cookie : store.getCookies()) {
            if (!"".equals(cookiesStr))
                cookiesStr += "; ";
            cookiesStr += cookie.getName() + "=" + cookie.getValue();
        }

        connection.setRequestProperty("Cookie", cookiesStr);

        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
        writer.write(requestData);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new InvocationException("IOException while sending RPC request", e);
    } finally {
        CookieHandler.setDefault(oldCookieHandler);
    }

    // Receive and process response
    try {

        is = connection.getInputStream();
        statusCode = connection.getResponseCode();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        String encodedResponse = baos.toString("UTF8");
        if (DUMP_PAYLOAD) {
            log.debug("Response code: {}", statusCode);
            log.debug("Response payload: {}", encodedResponse);
        }

        // System.out.println("Response payload (len = " + encodedResponse.length() + "): " + encodedResponse);
        if (statusCode != HttpURLConnection.HTTP_OK) {
            throw new StatusCodeException(statusCode, encodedResponse);
        } else if (encodedResponse == null) {
            // This can happen if the XHR is interrupted by the server dying
            throw new InvocationException("No response payload");
        } else if (isReturnValue(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            return responseReader.read(createStreamReader(encodedResponse));
        } else if (isThrownException(encodedResponse)) {
            encodedResponse = encodedResponse.substring(4);
            Throwable throwable = (Throwable) createStreamReader(encodedResponse).readObject();
            throw throwable;
        } else {
            throw new InvocationException("Unknown response " + encodedResponse);
        }
    } catch (IOException e) {

        log.error("error response: {}", IOUtils.toString(connection.getErrorStream()));
        throw new InvocationException("IOException while receiving RPC response", e);

    } catch (SerializationException e) {
        throw new InvocationException("Error while deserialization response", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignore) {
            }
        }
        if (connection != null) {
            // connection.disconnect();
        }
    }
}

From source file:com.upnext.blekit.util.http.HttpClient.java

public <T> Response<T> fetchResponse(Class<T> clazz, String path, Map<String, String> params, String httpMethod,
        String payload, String payloadContentType) {
    try {/*from   w w w  .  j  a va 2  s  .  co m*/
        String fullUrl = urlWithParams(path != null ? url + path : url, params);
        L.d("[" + httpMethod + "] " + fullUrl);
        final URLConnection connection = new URL(fullUrl).openConnection();
        if (connection instanceof HttpURLConnection) {
            final HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setDoInput(true);
            if (httpMethod != null) {
                httpConnection.setRequestMethod(httpMethod);
                if (httpMethod.equals("POST")) {
                    connection.setDoOutput(true); // Triggers POST.
                    connection.setRequestProperty("Accept-Charset", "UTF-8");
                    connection.setRequestProperty("Content-Type", payloadContentType);
                }
            } else {
                httpConnection.setRequestMethod(params != null ? "POST" : "GET");
            }
            httpConnection.addRequestProperty("Accept", "application/json");
            httpConnection.connect();
            if (payload != null) {
                OutputStream outputStream = httpConnection.getOutputStream();
                try {
                    if (LOG_RESPONSE) {
                        L.d("[payload] " + payload);
                    }
                    OutputStreamWriter writer = new OutputStreamWriter(outputStream, "UTF-8");
                    writer.write(payload);
                    writer.close();
                } finally {
                    outputStream.close();
                }
            }
            InputStream input = null;
            try {
                input = connection.getInputStream();
            } catch (IOException e) {
                // workaround for Android HttpURLConnection ( IOException is thrown for 40x error codes ).
                final int statusCode = httpConnection.getResponseCode();
                if (statusCode == -1)
                    throw e;
                return new Response<T>(Error.httpError(httpConnection.getResponseCode()));
            }
            final int statusCode = httpConnection.getResponseCode();
            L.d("statusCode " + statusCode);
            if (statusCode == HttpURLConnection.HTTP_OK || statusCode == HttpURLConnection.HTTP_CREATED) {
                try {
                    T value = null;
                    if (clazz != Void.class) {
                        if (LOG_RESPONSE || clazz == String.class) {
                            StringBuilder sb = new StringBuilder();
                            BufferedReader br = new BufferedReader(new InputStreamReader(input));
                            String read = br.readLine();
                            while (read != null) {
                                sb.append(read);
                                read = br.readLine();
                            }
                            String response = sb.toString();
                            if (LOG_RESPONSE) {
                                L.d("response " + response);
                            }
                            if (clazz == String.class) {
                                value = (T) response;
                            } else {
                                value = (T) objectMapper.readValue(response, clazz);
                            }
                        } else {
                            value = (T) objectMapper.readValue(input, clazz);
                        }
                    }
                    return new Response<T>(value);
                } catch (JsonMappingException e) {
                    return new Response<T>(Error.serlizerError(e));
                } catch (JsonParseException e) {
                    return new Response<T>(Error.serlizerError(e));
                }
            } else if (statusCode == HttpURLConnection.HTTP_NO_CONTENT) {
                try {
                    T def = clazz.newInstance();
                    if (LOG_RESPONSE) {
                        L.d("statusCode  == HttpURLConnection.HTTP_NO_CONTENT");
                    }
                    return new Response<T>(def);
                } catch (InstantiationException e) {
                    return new Response<T>(Error.ioError(e));
                } catch (IllegalAccessException e) {
                    return new Response<T>(Error.ioError(e));
                }
            } else {
                if (LOG_RESPONSE) {
                    L.d("error, statusCode " + statusCode);
                }
                return new Response<T>(Error.httpError(statusCode));
            }
        }
        return new Response<T>(Error.ioError(new Exception("Url is not a http link")));
    } catch (IOException e) {
        if (LOG_RESPONSE) {
            L.d("error, ioError " + e);
        }
        return new Response<T>(Error.ioError(e));
    }
}

From source file:hudson.model.UsageStatistics.java

/**
 * Gets the encrypted usage stat data to be sent to the Hudson server.
 *//*from   ww  w  . ja v  a 2 s  . co m*/
public String getStatData() throws IOException {
    Hudson h = Hudson.getInstance();

    JSONObject o = new JSONObject();
    o.put("stat", 1);
    o.put("install", Util.getDigestOf(h.getSecretKey()));
    o.put("version", Hudson.VERSION);

    List<JSONObject> nodes = new ArrayList<JSONObject>();
    for (Computer c : h.getComputers()) {
        JSONObject n = new JSONObject();
        if (c.getNode() == h) {
            n.put("master", true);
            n.put("jvm-vendor", System.getProperty("java.vm.vendor"));
            n.put("jvm-version", System.getProperty("java.version"));
        }
        n.put("executors", c.getNumExecutors());
        DescriptorImpl descriptor = h.getDescriptorByType(DescriptorImpl.class);
        n.put("os", descriptor.get(c));
        nodes.add(n);
    }
    o.put("nodes", nodes);

    List<JSONObject> plugins = new ArrayList<JSONObject>();
    for (PluginWrapper pw : h.getPluginManager().getPlugins()) {
        if (!pw.isActive())
            continue; // treat disabled plugins as if they are uninstalled
        JSONObject p = new JSONObject();
        p.put("name", pw.getShortName());
        p.put("version", pw.getVersion());
        plugins.add(p);
    }
    o.put("plugins", plugins);

    JSONObject jobs = new JSONObject();
    List<TopLevelItem> items = h.getItems();
    for (TopLevelItemDescriptor d : Items.all()) {
        int cnt = 0;
        for (TopLevelItem item : items) {
            if (item.getDescriptor() == d)
                cnt++;
        }
        jobs.put(d.getJsonSafeClassName(), cnt);
    }
    o.put("jobs", jobs);

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // json -> UTF-8 encode -> gzip -> encrypt -> base64 -> string
        OutputStreamWriter w = new OutputStreamWriter(
                new GZIPOutputStream(new CombinedCipherOutputStream(baos, getCipher(), "AES")), "UTF-8");
        o.write(w);
        w.close();

        return new String(Base64.encode(baos.toByteArray()));
    } catch (GeneralSecurityException e) {
        throw new Error(e); // impossible
    }
}

From source file:github.nisrulz.optimushttp.HttpReq.java

@Override
protected String doInBackground(HttpReqPkg... params) {

    URL url;/* ww  w  .ja  v a 2 s.  c  o m*/
    BufferedReader reader = null;

    String username = params[0].getUsername();
    String password = params[0].getPassword();
    String authStringEnc = null;

    if (username != null && password != null) {
        String authString = username + ":" + password;

        byte[] authEncBytes;
        authEncBytes = Base64.encode(authString.getBytes(), Base64.DEFAULT);
        authStringEnc = new String(authEncBytes);
    }

    String uri = params[0].getUri();

    if (params[0].getMethod().equals("GET")) {
        uri += "?" + params[0].getEncodedParams();
    }

    try {
        StringBuilder sb;
        // create the HttpURLConnection
        url = new URL(uri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        if (authStringEnc != null) {
            connection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        }

        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")
                || params[0].getMethod().equals("DELETE")) {
            // enable writing output to this url
            connection.setDoOutput(true);
        }

        if (params[0].getMethod().equals("POST")) {
            connection.setRequestMethod("POST");
        } else if (params[0].getMethod().equals("GET")) {
            connection.setRequestMethod("GET");
        } else if (params[0].getMethod().equals("PUT")) {
            connection.setRequestMethod("PUT");
        } else if (params[0].getMethod().equals("DELETE")) {
            connection.setRequestMethod("DELETE");
        }

        // give it x seconds to respond
        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);
        connection.setRequestProperty("Content-Type", contentType);

        for (int i = 0; i < headerMap.size(); i++) {
            connection.setRequestProperty(headerMap.keyAt(i), headerMap.valueAt(i));
        }

        connection.setRequestProperty("Content-Length", "" + params[0].getEncodedParams().getBytes().length);

        connection.connect();
        if (params[0].getMethod().equals("POST") || params[0].getMethod().equals("PUT")) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
            writer.write(params[0].getEncodedParams());
            writer.flush();
            writer.close();
        }

        // read the output from the server
        InputStream in;
        resCode = connection.getResponseCode();
        resMsg = connection.getResponseMessage();
        if (resCode != HttpURLConnection.HTTP_OK) {
            in = connection.getErrorStream();
        } else {
            in = connection.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(in));
        sb = new StringBuilder();

        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        sb.append(resCode).append(" : ").append(resMsg);
        return sb.toString();
    } catch (Exception e) {
        listener.onFailure(Integer.toString(resCode) + " : " + resMsg);
        e.printStackTrace();
    } finally {
        // close the reader; this can throw an exception too, so
        // wrap it in another try/catch block.
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }

    return null;
}

From source file:gate.util.Files.java

/**
  * Writes aString into a temporary file located inside
  * the default temporary directory defined by JVM, using the specific
  * anEncoding./*from  www  .j  a va 2s .c  o  m*/
  * An unique ID is generated and associated automaticaly with the file name.
  * @param aString the String to be written. If is null then the file will be
  * empty.
  * @param anEncoding the encoding to be used. If is null then the default
  * encoding will be used.
  * @return the tmp file containing the string.
  */
public static File writeTempFile(String aString, String anEncoding)
        throws UnsupportedEncodingException, IOException {
    File resourceFile = null;
    OutputStreamWriter writer = null;

    // Create a temporary file name
    resourceFile = File.createTempFile("gateResource", ".tmp");
    resourceFile.deleteOnExit();

    if (aString == null)
        return resourceFile;
    // Prepare the writer
    if (anEncoding == null) {
        // Use default encoding
        writer = new OutputStreamWriter(new FileOutputStream(resourceFile));

    } else {
        // Use the specified encoding
        writer = new OutputStreamWriter(new FileOutputStream(resourceFile), anEncoding);
    } // End if

    // This Action is added only when a gate.Document is created.
    // So, is for sure that the resource is a gate.Document
    writer.write(aString);
    writer.flush();
    writer.close();
    return resourceFile;
}

From source file:com.cprassoc.solr.auth.SolrHttpHandler.java

private String cURLRequest(String url, String data, Method method) {
    String result = "";

    if (method == null) {
        method = Method.GET;//from   w ww  .j  av  a  2  s . c  om
    }
    try {

        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();

        // conn.setRequestProperty("Content-Type", "application/json");
        conn.setDoOutput(true);

        conn.setRequestMethod(method.name());

        String userpass = "solr" + ":" + "SolrRocks";
        String basicAuth = "Basic "
                + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes("UTF-8"));
        conn.setRequestProperty("Authorization", basicAuth);

        //String data =  "{\"format\":\"json\",\"pattern\":\"#\"}";
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        if (data != null && !data.equals("")) {
            out.write(data);
        }
        out.close();

        // new InputStreamReader(conn.getInputStream());   
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }

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

    return result;
}

From source file:com.contrastsecurity.ide.eclipse.core.extended.ExtendedContrastSDK.java

private HttpURLConnection makeConnection(String url, String method, Object body) throws IOException {

    HttpURLConnection connection = makeConnection(url, method);

    connection.setDoOutput(true);/*  w w  w  . j ava 2 s . c  om*/
    connection.setRequestProperty("Content-Type", "application/json");
    OutputStream os = connection.getOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");

    osw.write(gson.toJson(body));
    osw.flush();
    osw.close();
    os.close();

    return connection;
}