Example usage for java.io InputStreamReader close

List of usage examples for java.io InputStreamReader close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

@Override
public Loader<String> onCreateLoader(int id, Bundle args) {
    AsyncTaskLoader<String> loader = new AsyncTaskLoader<String>(activity) {
        @Override//from   w w  w. ja v a  2 s  .c o  m
        public String loadInBackground() {
            StringBuffer instr = new StringBuffer();
            try {
                Socket connection = new Socket(ipAddr, port);
                BufferedOutputStream bos = new BufferedOutputStream(connection.getOutputStream());
                OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
                osw.write(formatJSON(command.toUpperCase()));
                osw.write(13);
                osw.flush();
                BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
                InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
                int c;
                while ((c = isr.read()) != 13)
                    instr.append((char) c);
                isr.close();
                bis.close();
                osw.close();
                bos.close();
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return instr.toString();
        }
    };
    return loader;
}

From source file:com.masse.mvn.plugin.BuildJsonFromPropertiesMojo.java

private void buidJsonTargetFile(File inputFile) throws MojoExecutionException {

    String inputFileString = inputFile.getAbsolutePath()
            .substring(inputFile.getAbsolutePath().lastIndexOf(SystemUtils.IS_OS_LINUX ? "/" : "\\") + 1);
    String outputFileString = jsonTargetPath + new String(SystemUtils.IS_OS_LINUX ? "/" : "\\")
            + inputFileString.substring(0, inputFileString.lastIndexOf(".")) + ".json";

    getLog().info("Process file " + inputFileString);

    if (!inputFile.exists()) {
        throw new MojoExecutionException("Properties file " + inputFile + " not found !");
    }/*from  w  ww  .  ja  va 2 s  .c o m*/

    TreeMap<String, PropertiesToJson> propertiesJson = new TreeMap<String, PropertiesToJson>();
    Properties props = new Properties();

    try {
        FileInputStream inputFileStream = new FileInputStream(inputFile);
        BufferedReader inputFileBufferedReader = new BufferedReader(
                new InputStreamReader(inputFileStream, "UTF-8"));

        File outputTempFile = new File(inputFileString + "-temp");

        FileOutputStream outputTempFileStream = new FileOutputStream(outputTempFile);
        OutputStreamWriter outputTempFileStrWriter = new OutputStreamWriter(outputTempFileStream, "UTF-8");
        BufferedWriter writer = new BufferedWriter(outputTempFileStrWriter);

        String line = "";
        while ((line = inputFileBufferedReader.readLine()) != null) {
            if (!(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n"))) {
                if (line.startsWith("#")) {
                    continue;
                }
                int equalsIndex = line.indexOf("=");
                if (equalsIndex < 0) {
                    continue;
                }
                line = line.replace("\"", "&quot;");
                line = line.replace("\\", "\\\\\\\\");
                line = line.replace("   ", "");
                writer.write(line + "\n");
            }
        }

        writer.close();
        outputTempFileStrWriter.close();
        outputTempFileStream.close();

        inputFileBufferedReader.close();
        inputFileStream.close();

        FileInputStream fis = new FileInputStream(outputTempFile);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        props.load(isr);
        isr.close();
        fis.close();

        outputTempFile.delete();

        @SuppressWarnings("rawtypes")
        Enumeration e = props.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();

            String rootKey = key.split("=")[0];

            propertiesJson.put(rootKey, createMap(propertiesJson, key, props.getProperty(key), 1));

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

    StringBuffer sb = new StringBuffer();
    sb.append(PrintJsonTree(propertiesJson, 0, false));

    File outputFile = new File(outputFileString);

    try {
        FileOutputStream fos = new FileOutputStream(outputFile);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter bwr = new BufferedWriter(osw);

        //write contents of StringBuffer to a file

        bwr.write(sb.toString());

        //flush the stream
        bwr.flush();

        //close the stream
        bwr.close();
        osw.close();
        fos.close();
    } catch (IOException e) {
        getLog().error(e);
        throw new MojoExecutionException("json file creation error", e);
    }
}

From source file:org.opendatakit.common.utils.WebUtils.java

private static String readResponseHelper(InputStream content) {
    StringBuffer response = new StringBuffer();

    if (content != null) {
        // TODO: this section of code is possibly causing 'WARNING: Going to
        // buffer
        // response body of large or unknown size. Using getResponseBodyAsStream
        // instead is recommended.'
        // The WARNING is most likely only happening when running appengine
        // locally,
        // but we should investigate to make sure
        BufferedReader reader = null;
        InputStreamReader isr = null;
        try {/*w w w.  j  a v  a 2s  .  c o m*/
            reader = new BufferedReader(isr = new InputStreamReader(content, HtmlConsts.UTF8_ENCODE));
            String responseLine;
            while ((responseLine = reader.readLine()) != null) {
                response.append(responseLine);
            }
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        } catch (IllegalStateException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException ex) {
                // no-op
            }
            try {
                if (isr != null) {
                    isr.close();
                }
            } catch (IOException ex) {
                // no-op
            }
        }
    }
    return response.toString();
}

From source file:org.cybergarage.round.Node.java

public boolean postMessage(JSONObject reqObj) {
    try {/*  w  w w .jav a  2s  .  c o  m*/
        URL url = new URL("http", host, port, "/rpc");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(reqObj.toString());
        out.close();

        int statusCode = conn.getResponseCode();
        if (statusCode != 200)
            return false;

        InputStream in = conn.getInputStream();

        InputStreamReader reader = new InputStreamReader(in);
        StringBuilder builder = new StringBuilder();
        char[] buf = new char[1024];
        int nRead;
        while (0 <= (nRead = reader.read(buf))) {
            builder.append(buf, 0, nRead);
        }
        reader.close();

        String resStr = builder.toString();
        this.resObj = new JSONObject(resStr);
    } catch (Exception e) {
        return false;
    }

    return true;
}

From source file:org.culturegraph.mf.stream.sink.ObjectFileWriterTest.java

@Override
protected String getOutput() throws IOException {
    final InputStream stream = new FileInputStream(file);
    final InputStreamReader reader;
    try {/*  w  w w.j  a v a2s.co  m*/
        reader = new InputStreamReader(stream, writer.getEncoding());
    } catch (final IOException e) {
        stream.close();
        throw e;
    }

    final String fileContents;
    try {
        fileContents = IOUtils.toString(reader);
    } finally {
        reader.close();
    }

    return fileContents;
}

From source file:org.apache.ranger.plugin.store.file.BaseFileStore.java

protected void close(InputStreamReader reader) {
    if (reader != null) {
        try {// w ww. j a  va  2s .c  o  m
            reader.close();
        } catch (IOException excp) {
            // ignore
        }
    }
}

From source file:com.heliosapm.tsdblite.json.JSON.java

/**
 * Deserializes a JSON formatted byte array to a specific class type
 * <b>Note:</b> If you get mapping exceptions you may need to provide a 
 * TypeReference/*w w w.j  a va  2  s .  co  m*/
 * @param json The buffer to deserialize from
 * @param pojo The class type of the object used for deserialization
 * @param charset The character set of the content type in the buffer
 * @return An object of the {@code pojo} type
 * @throws IllegalArgumentException if the data or class was null or parsing 
 * failed
 * @throws JSONException if the data could not be parsed
 */
public static final <T> T parseToObject(final ByteBuf json, final Class<T> pojo, final Charset charset) {
    if (json == null)
        throw new IllegalArgumentException("Incoming buffer was null");
    if (pojo == null)
        throw new IllegalArgumentException("Missing class type");
    if (charset == null)
        throw new IllegalArgumentException("Missing charset");
    InputStream is = new ByteBufInputStream(json);
    InputStreamReader isr = new InputStreamReader(is, charset);
    try {
        return jsonMapper.readValue(isr, pojo);
    } catch (JsonParseException e) {
        throw new IllegalArgumentException(e);
    } catch (JsonMappingException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        throw new JSONException(e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception x) {
                /* No Op */}
        if (isr != null)
            try {
                isr.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:org.apache.camel.component.flatpack.FlatpackDataFormat.java

public Object unmarshal(Exchange exchange, InputStream stream) throws Exception {
    InputStreamReader reader = new InputStreamReader(stream, IOConverter.getCharsetName(exchange));
    try {/*from ww  w .  j  a  v a  2s  .  c om*/
        Parser parser = createParser(exchange, reader);
        DataSet dataSet = parser.parse();
        return new DataSetList(dataSet);
    } finally {
        reader.close();
    }
}

From source file:com.heliosapm.tsdblite.json.JSON.java

/**
 * Deserializes a JSON formatted ByteBuf to a JsonNode
 * @param json The buffer to deserialize from
 * @param charset The optional character set of the content type in the buffer which defaults to UTF8
 * @return The parsed JsonNode/* www  . j ava  2s.com*/
 * @throws IllegalArgumentException if buffer was null
 * @throws JSONException if the data could not be parsed
 */
public static final JsonNode parseToNode(final ByteBuf json, final Charset charset) {
    if (json == null)
        throw new IllegalArgumentException("Incoming buffer was null");
    InputStream is = new ByteBufInputStream(json);
    InputStreamReader isr = new InputStreamReader(is, charset == null ? UTF8 : charset);
    try {
        return jsonMapper.readTree(is);
    } catch (JsonParseException e) {
        throw new IllegalArgumentException(e);
    } catch (JsonMappingException e) {
        throw new IllegalArgumentException(e);
    } catch (IOException e) {
        throw new JSONException(e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (Exception x) {
                /* No Op */}
        if (isr != null)
            try {
                isr.close();
            } catch (Exception x) {
                /* No Op */}
    }
}