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.android.W3T.app.network.NetworkUtil.java

public static String attemptGetReceipt(String op, String id) {
    // Here we may want to check the network status.
    checkNetwork();/*w ww  .j a  v  a2  s.  c o  m*/

    try {
        JSONObject jsonstr = new JSONObject();
        JSONObject param = new JSONObject();
        try {
            param.put("opcode", op);
            param.put("acc", UserProfile.getUsername());
            if (op.equals(METHOD_RECEIVE_ALL)) {
                // Add your data
                param.put("limitStart", "0");
                param.put("limitOffset", "7");
            } else if (op.equals(METHOD_RECEIVE_RECEIPT_DETAIL)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);

            } else if (op.equals(METHOD_RECEIVE_RECEIPT_ITEMS)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);
            }
            jsonstr.put("json", param);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();

        System.out.println("get " + s);

        return s;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.yahoo.glimmer.util.MergeSortTool.java

public static int mergeSort(FileSystem fs, List<Path> sourcePaths, Path outputPath,
        CompressionCodecFactory compressionCodecFactory) throws IOException {
    assert sourcePaths.size() > 0 : "No source paths given.";

    LOG.info("Sorted merge into " + outputPath.toString());
    OutputStream outputStream = fs.create(outputPath);

    CompressionCodec inputCompressionCodec = compressionCodecFactory.getCodec(sourcePaths.get(0));
    if (inputCompressionCodec != null) {
        LOG.info("Input compression codec " + inputCompressionCodec.getClass().getName());
    }//  w ww.j  a v a  2  s. com

    CompressionCodec outputCompressionCodec = compressionCodecFactory.getCodec(outputPath);
    if (outputCompressionCodec != null) {
        LOG.info("Output compression codec " + outputCompressionCodec.getClass().getName());
        outputStream = outputCompressionCodec.createOutputStream(outputStream);
    }

    List<BufferedReader> readers = new ArrayList<BufferedReader>();
    OutputStreamWriter writer = new OutputStreamWriter(outputStream);

    for (Path partPath : sourcePaths) {
        LOG.info("\tAdding source " + partPath.toString());
        InputStream inputStream = fs.open(partPath);
        if (inputCompressionCodec != null) {
            inputStream = inputCompressionCodec.createInputStream(inputStream);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        readers.add(reader);
    }

    int count = ReadersWriterMergeSort.mergeSort(readers, writer);

    writer.close();
    for (BufferedReader reader : readers) {
        reader.close();
    }
    readers.clear();
    LOG.info("Processed " + count + " lines into " + outputPath.toString());
    return count;
}

From source file:Main.java

public static Uri getAllCallLogs(ContentResolver cr, Uri internal, Context context, String timeStamp) {
    SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm");
    String[] callLogArray = new String[3];
    String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
    Uri callUri = Uri.parse("content://call_log/calls");
    Cursor cur = cr.query(callUri, null, null, null, strOrder);

    FileOutputStream fOut = null;
    try {//  www . jav  a 2s  . c om
        fOut = context.openFileOutput("call_logs_" + timeStamp + ".txt", Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    OutputStreamWriter osw = new OutputStreamWriter(fOut);

    while (cur.moveToNext()) {
        callLogArray[0] = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
        callLogArray[1] = cur.getString(cur.getColumnIndex(android.provider.CallLog.Calls.CACHED_NAME));

        int thirdIndex = cur.getColumnIndex(android.provider.CallLog.Calls.DATE);
        long seconds = cur.getLong(thirdIndex);
        String dateString = formatter.format(new Date(seconds));
        callLogArray[2] = dateString;

        writeToOutputStreamArray(callLogArray, osw);
    }

    try {
        osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return internal;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String post(URL url, String payload, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }/*from w  w  w .  j a  v  a 2 s .  c  om*/
    }

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    osr.close();
    rd.close();

    return resp;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

protected static String post(URL url, Map props) throws IOException {
    String propstr = new String();

    for (Iterator i = props.keySet().iterator(); i.hasNext();) {
        String key = (String) i.next();
        propstr = propstr + URLEncoder.encode(key, "UTF-8") + "="
                + URLEncoder.encode((String) props.get(key), "UTF-8");
        if (i.hasNext()) {
            propstr = propstr + "&";
        }//from  www.  j  a  v  a 2 s. com
    }

    SSLUtils.verifyHost();

    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(propstr);
    osr.flush();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    osr.close();
    rd.close();

    return resp;
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*from  w ww .j a v  a2s  . c o m*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptSearch(String op, int range, String[] terms) {
    // Here we may want to check the network status.
    checkNetwork();// w w w  .  java2s  .  c  o m

    try {
        JSONObject param = new JSONObject();
        param.put("acc", UserProfile.getUsername());
        param.put("opcode", "search");
        param.put("mobile", true);
        JSONObject jsonstr = new JSONObject();
        if (op == METHOD_KEY_SEARCH) {
            // Add your data
            // Add keys if there is any.
            if (terms != null) {
                JSONArray keys = new JSONArray();
                int numTerm = terms.length;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            }
            // Calculate the Search Range by last N days
            Calendar c = Calendar.getInstance();
            if (range == -SEVEN_DAYS || range == -FOURTEEN_DAYS) {
                // 7 days or 14 days
                c.add(Calendar.DAY_OF_MONTH, range);
            } else if (range == -ONE_MONTH || range == -THREE_MONTHS) {
                // 1 month or 6 month
                c.add(Calendar.MONTH, range);
            }

            String timeStart = String.valueOf(c.get(Calendar.YEAR));
            timeStart += ("-" + String.valueOf(c.get(Calendar.MONTH) + 1));
            timeStart += ("-" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)));
            Calendar current = Calendar.getInstance();
            current.add(Calendar.DAY_OF_MONTH, 1);
            String timeEnd = String.valueOf(current.get(Calendar.YEAR));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.MONTH) + 1));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.DAY_OF_MONTH)));

            JSONObject timeRange = new JSONObject();
            timeRange.put("start", timeStart);
            timeRange.put("end", timeEnd);
            param.put("timeRange", timeRange);

            jsonstr.put("json", param);
        } else if (op == METHOD_TAG_SEARCH) {

        } else if (op == METHOD_KEY_DATE_SEARCH) {
            if (terms.length > 2) {
                // Add keys if there is any.
                JSONArray keys = new JSONArray();
                int numTerm = terms.length - 2;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            } else if (terms.length < 2) {
                System.out.println("Wrong terms: no start or end date.");
                return null;
            }
            JSONObject timeRange = new JSONObject();
            timeRange.put("start", terms[terms.length - 2]);
            timeRange.put("end", terms[terms.length - 1]);
            param.put("timeRange", timeRange);
            jsonstr.put("json", param);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        return in.readLine();
        //           String s = in.readLine();
        //           System.out.println(s);
        //           return s;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:gate.util.Files.java

/**
 * This method updates an XML element in an XML file
 * with a new set of attributes. If the element is not found the XML
 * file is unchanged. The attributes keys and values must all be Strings.
 * We first try to read the file using UTF-8 encoding.  If an error occurs we
 * fall back to the platform default encoding (for backwards-compatibility
 * reasons) and try again.  The file is written back in UTF-8, with an
 * updated encoding declaration./*from  w w w  .j  a  v a  2s.  com*/
 *
 * @param xmlFile An XML file.
 * @param elementName The name of the element to update.
 * @param newAttrs The new attributes to place on the element.
 * @return A string of the whole XML file, with the element updated (the
 *   file is also overwritten).
 */
public static String updateXmlElement(File xmlFile, String elementName, Map<String, String> newAttrs)
        throws IOException {
    String newXml = null;
    BufferedReader utfFileReader = null;
    BufferedReader platformFileReader = null;
    Charset utfCharset = Charset.forName("UTF-8");
    try {
        FileInputStream fis = new FileInputStream(xmlFile);
        // try reading with UTF-8, make sure any errors throw an exception
        CharsetDecoder decoder = utfCharset.newDecoder().onUnmappableCharacter(CodingErrorAction.REPORT)
                .onMalformedInput(CodingErrorAction.REPORT);
        utfFileReader = new BomStrippingInputStreamReader(fis, decoder);
        newXml = updateXmlElement(utfFileReader, elementName, newAttrs);
    } catch (CharacterCodingException cce) {
        // File not readable as UTF-8, so try the platform default encoding
        if (utfFileReader != null) {
            utfFileReader.close();
            utfFileReader = null;
        }
        if (DEBUG) {
            Err.prln("updateXmlElement: could not read " + xmlFile + " as UTF-8, " + "trying platform default");
        }
        platformFileReader = new BufferedReader(new FileReader(xmlFile));
        newXml = updateXmlElement(platformFileReader, elementName, newAttrs);
    } finally {
        if (utfFileReader != null) {
            utfFileReader.close();
        }
        if (platformFileReader != null) {
            platformFileReader.close();
        }
    }

    // write the updated file in UTF-8, fixing the encoding declaration
    newXml = newXml.replaceFirst("\\A<\\?xml (.*)encoding=(?:\"[^\"]*\"|'[^']*')",
            "<?xml $1encoding=\"UTF-8\"");
    FileOutputStream fos = new FileOutputStream(xmlFile);
    OutputStreamWriter fileWriter = new OutputStreamWriter(fos, utfCharset);
    fileWriter.write(newXml);
    fileWriter.close();

    return newXml;
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

/**
 *
 * @param httpParam/*from  w  ww . j  a  v  a2  s. c om*/
 * @return
 */
public static SimpleHttpResult httpRequest(SimpleHttpParam httpParam) {
    String url = httpParam.getUrl();
    Map<String, Object> parameters = httpParam.getParameters();
    String sMethod = httpParam.getMethod();
    String charSet = httpParam.getCharSet();
    boolean sslVerify = httpParam.isSslVerify();
    int maxResultSize = httpParam.getMaxResultSize();
    Map<String, Object> headers = httpParam.getHeaders();
    int readTimeout = httpParam.getReadTimeout();
    int connectTimeout = httpParam.getConnectTimeout();
    boolean ignoreContentIfUnsuccess = httpParam.isIgnoreContentIfUnsuccess();
    boolean hostnameVerify = httpParam.isHostnameVerify();
    TrustKeyStore trustKeyStore = httpParam.getTrustKeyStore();
    ClientKeyStore clientKeyStore = httpParam.getClientKeyStore();

    if (url == null || url.trim().length() == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }
    if (maxResultSize <= 0) {
        throw new IllegalArgumentException("maxResultSize must be positive : " + maxResultSize);
    }
    Charset.forName(charSet);
    HttpURLConnection urlConn = null;
    URL destURL = null;

    String baseUrl = url.trim();
    if (!baseUrl.toLowerCase().startsWith(HTTPS_PREFIX) && !baseUrl.toLowerCase().startsWith(HTTP_PREFIX)) {
        baseUrl = HTTP_PREFIX + baseUrl;
    }

    String method = null;
    if (sMethod != null) {
        method = sMethod.toUpperCase();
    }
    if (method == null || !(method.equals(HTTP_METHOD_POST) || method.equals(HTTP_METHOD_GET))) {
        throw new IllegalArgumentException("invalid http method : " + method);
    }

    int index = baseUrl.indexOf("?");
    if (index > 0) {
        baseUrl = urlEncode(baseUrl, charSet);
    } else if (index == 0) {
        throw new IllegalArgumentException("invalid url : " + url);
    }

    String queryString = mapToQueryString(parameters, charSet);
    String targetUrl = "";
    if (method.equals(HTTP_METHOD_POST)) {
        targetUrl = baseUrl;
    } else {
        if (index > 0) {
            targetUrl = baseUrl + "&" + queryString;
        } else {
            targetUrl = baseUrl + "?" + queryString;
        }
    }
    try {
        destURL = new URL(targetUrl);
        urlConn = (HttpURLConnection) destURL.openConnection();

        setSSLSocketFactory(urlConn, sslVerify, hostnameVerify, trustKeyStore, clientKeyStore);

        boolean hasContentType = false;
        boolean hasUserAgent = false;
        for (String key : headers.keySet()) {
            if ("Content-Type".equalsIgnoreCase(key)) {
                hasContentType = true;
            }
            if ("user-agent".equalsIgnoreCase(key)) {
                hasUserAgent = true;
            }
        }
        if (!hasContentType) {
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=" + charSet);
        }
        if (!hasUserAgent) {
            headers.put("user-agent", "PlatSystem");
        }

        if (headers != null && !headers.isEmpty()) {
            for (Entry<String, Object> entry : headers.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                List<String> values = makeStringList(value);
                for (String v : values) {
                    urlConn.addRequestProperty(key, v);
                }
            }
        }
        urlConn.setDoOutput(true);
        urlConn.setDoInput(true);
        urlConn.setAllowUserInteraction(false);
        urlConn.setUseCaches(false);
        urlConn.setRequestMethod(method);
        urlConn.setConnectTimeout(connectTimeout);
        urlConn.setReadTimeout(readTimeout);

        if (method.equals(HTTP_METHOD_POST)) {
            String postData = queryString.length() == 0 ? httpParam.getPostData() : queryString;
            if (postData != null && postData.trim().length() > 0) {
                OutputStream os = urlConn.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, charSet);
                osw.write(postData);
                osw.flush();
                osw.close();
            }
        }

        int responseCode = urlConn.getResponseCode();
        Map<String, List<String>> responseHeaders = urlConn.getHeaderFields();
        String contentType = urlConn.getContentType();

        SimpleHttpResult result = new SimpleHttpResult(responseCode);
        result.setHeaders(responseHeaders);
        result.setContentType(contentType);

        if (responseCode != 200 && ignoreContentIfUnsuccess) {
            return result;
        }

        InputStream is = urlConn.getInputStream();
        byte[] temp = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readBytes = is.read(temp);
        while (readBytes > 0) {
            baos.write(temp, 0, readBytes);
            readBytes = is.read(temp);
        }
        String resultString = new String(baos.toByteArray(), charSet); //new String(buffer.array(), charSet);
        baos.close();
        result.setContent(resultString);
        return result;
    } catch (Exception e) {
        logger.warn("connection error : " + e.getMessage());
        return new SimpleHttpResult(e);
    } finally {
        if (urlConn != null) {
            urlConn.disconnect();
        }
    }
}

From source file:com.mingsoft.weixin.http.HttpClientConnectionManager.java

/**
 * ?//from   ww w .  j ava2 s. c  om
 * @param postUrl ?
 * @param param ?
 * @param method 
 * @return null
 */
public static String request(String postUrl, String param, String method) {
    URL url;
    try {
        url = new URL(postUrl);

        HttpURLConnection conn;
        conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(30000); // ??)
        conn.setReadTimeout(30000); // ????)
        conn.setDoOutput(true); // post??http?truefalse
        conn.setDoInput(true); // ?httpUrlConnectiontrue
        conn.setUseCaches(false); // Post ?
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestMethod(method);// "POST"GET
        conn.setRequestProperty("Content-Length", param.length() + "");
        String encode = "utf-8";
        OutputStreamWriter out = null;
        out = new OutputStreamWriter(conn.getOutputStream(), encode);
        out.write(param);
        out.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        // ??
        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line = "";
        StringBuffer strBuf = new StringBuffer();
        while ((line = in.readLine()) != null) {
            strBuf.append(line).append("\n");
        }
        in.close();
        out.close();
        return strBuf.toString();
    } catch (MalformedURLException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}