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:ca.ualberta.cmput301f13t13.storyhoard.serverClasses.ESUpdates.java

/**
 * Deletes an entry (in this case a story object) specified by the id from
 * the server. You must specify the id as a string (but in the format of
 * a UUID), and the server as a string as well. In addition, output from
 * the server (the response's content) will also be printed out to
 * System.err. </br></br>/*from w  w w.j  a v  a2  s  .com*/
 * 
 * Example call: </br>
 * Let's say the following story is on the server. </br>
 * </br> String id = f1bda3a9-4560-4530-befc-2d58db9419b7; 
 *       Story myStory = new Story(id, "The Cow", "John Wayne", 
 *                            "A story about a Cow", phoneId). 
 * </br> To delete myStory from the server, call </br>
 * String server = "http://cmput301.softwareprocess.es:8080/cmput301f13t13/stories/" </br>
 * String id = f1bda3a9-4560-4530-befc-2d58db9419b7; </br>
 * deleteStory(id, server); </br></br>
 * 
 * @param id
 *          Must be a String in the valid format of a UUID. See example
 *          above for the formatting of a UUID.
 * @param server
 *          The location on elastic search to search for the responses.
 *          It expects this information as a String.</br>
 *          See the above example for an example of a valid server string
 *          format.
 */
protected void deleteStory(String id, String server) throws IOException {
    HttpDelete httpDelete = new HttpDelete(server + id);
    httpDelete.addHeader("Accept", "application/json");

    HttpResponse response = httpclient.execute(httpDelete);

    String status = response.getStatusLine().toString();
    System.out.println(status);

    HttpEntity entity = response.getEntity();
    InputStreamReader is = new InputStreamReader(entity.getContent());
    BufferedReader br = new BufferedReader(is);
    String output;
    System.err.println("Output from ESUpdates -> ");

    while ((output = br.readLine()) != null) {
        System.err.println(output);
    }

    entity.consumeContent();
    is.close();
}

From source file:com.baifendian.swordfish.execserver.utils.OsUtil.java

/**
 * ?/* w  w w .j av  a2  s.  co m*/
 *
 * @return
 */
public static double memoryUsage() {
    Map<String, Object> map = new HashMap<>();
    InputStreamReader inputs = null;
    BufferedReader buffer = null;

    try {
        inputs = new InputStreamReader(new FileInputStream("/proc/meminfo"));
        buffer = new BufferedReader(inputs);
        String line = "";
        while (true) {
            line = buffer.readLine();
            if (line == null) {
                break;
            }

            if (line.contains(":")) {
                String[] memInfo = line.split(":");
                String value = memInfo[1].replace("kB", "").trim();
                map.put(memInfo[0], value);
            }
        }

        long memTotal = Long.parseLong(map.get("MemTotal").toString());
        long memFree = Long.parseLong(map.get("MemFree").toString());
        long buffers = Long.parseLong(map.get("Buffers").toString());
        long cached = Long.parseLong(map.get("Cached").toString());

        double usage = (float) (memTotal - memFree - buffers - cached) / memTotal;
        return usage;
    } catch (Exception e) {
        logger.error("get memory usage error", e);
    } finally {
        try {
            buffer.close();
            inputs.close();
        } catch (IOException e) {
            logger.error("close stream", e);
        }
    }

    return 0;
}

From source file:de.dfki.km.perspecting.obie.corpus.TextCorpus.java

@SuppressWarnings("unchecked")
public List<?> forEach(DocumentProcedure<?> p) throws Exception {
    @SuppressWarnings("rawtypes")
    List l = new ArrayList();
    for (Entry<URI, InputStream> in : getEntries().entrySet()) {
        InputStreamReader reader = new InputStreamReader(in.getValue());
        log.info("processing entry: " + in.getKey().toString());
        l.add(p.process(reader, in.getKey()));
        reader.close();
    }//from   ww  w. j a  v  a2 s .co m
    return l;
}

From source file:com.github.joshelser.accumulo.DelimitedIngest.java

private void processSinglePathWithByteBuffer(BatchWriter writer, FileMapping mapping, Path p, CsvParser parser)
        throws IOException, MutationsRejectedException {
    final FileSystem fs = p.getFileSystem(conf);
    FSDataInputStream dis = fs.open(p, INPUT_BUFFER_SIZE);
    InputStreamReader reader = new InputStreamReader(dis, UTF_8);
    try {/*w  w  w. jav a2  s . c o m*/
        parser.beginParsing(reader);
        String[] line = null;
        while ((line = parser.parseNext()) != null) {
            writer.addMutation(parseLine(mapping, line));
        }
    } finally {
        if (null != reader) {
            reader.close();
        }
    }
}

From source file:org.apache.velocity.io.UnicodeInputStreamTestCase.java

protected byte[] readAllBytes(final InputStream inputStream, final String enc) throws Exception {
    InputStreamReader isr = null;

    byte[] res = new byte[0];

    try {/*from   w  ww. j  av a  2s  .c o m*/
        byte[] buf = new byte[1024];
        int read = 0;

        while ((read = inputStream.read(buf)) >= 0) {
            res = ArrayUtils.addAll(res, ArrayUtils.subarray(buf, 0, read));
        }
    } finally {

        if (isr != null) {
            isr.close();
        }
    }

    return res;
}

From source file:info.sugoiapps.xoserver.XOverServer.java

/**
 * The main background task.//from   w  ww  .j ava  2s  .c om
 * Accept connection from the server socket and read incoming messages.
 * Pass messages to mouse event handler.
 */
private void listen() {
    Socket socket = null;
    InputStream in = null;
    publish(CONNECTED_MESSAGE + PORT);
    System.out.println("about to enter server loop");
    while (!Thread.interrupted()) { //!Thread.interrupted()
        try {
            socket = server.accept(); // stop is clicked, this is still waiting for incoming connections, 
                                      // therefore once the server is closed, it will produce an error
                                      //socket.setKeepAlive(false);
            System.out.println("started accepting from socket");
        } catch (IOException ex) {
            serverClosedMessage(ex);
            break;
        }

        try {
            in = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(in);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (isCancelled()) {
                    in.close();
                    isr.close();
                    br.close();
                    socket.close();
                    break;
                }
                if (!addressReceived && isValidAddress(line)) {
                    System.out.println("address check entered");
                    addressReceived = true;
                    hostAddress = line;
                    startFileClient();
                } else {
                    imitateMouse(line);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            serverClosedMessage(ex);
        }
    }
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;//from  ww  w . j  a v  a2s. co  m
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java

/**
 * find the process info//from  w w w  .ja v  a 2  s.  co  m
 * @param processName
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
public static String executePS(String processName) throws IOException, InterruptedException {
    AROLogger.d(TAG, "entered ps...");

    final Process process = Runtime.getRuntime().exec("ps " + processName);
    final InputStreamReader inputStream = new InputStreamReader(process.getInputStream());
    final BufferedReader reader = new BufferedReader(inputStream);
    try {
        String line = null;

        int read;
        final char[] buffer = new char[4096];
        final StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        // Waits for the command to finish.
        process.waitFor();
        //no need to destroy the process since waitFor() will wait until all subprocesses exit

        line = output.toString();
        return line;
    } finally {
        try {
            reader.close();
            inputStream.close();
            reader.close();

        } catch (Exception e) {
            AROLogger.e(TAG,
                    "Exception caught while closing resources in executePS. Error msg=" + e.getMessage());
            AROLogger.e(TAG, "execution will be allowed to continue");
        }

        AROLogger.d(TAG, "exiting ps...");
    }
}

From source file:org.apache.solr.common.util.ContentStreamTest.java

public void testURLStream() throws IOException {
    InputStream is = new SolrResourceLoader().openResource("solrj/README");
    assertNotNull(is);/*from  w ww .ja va 2s  . c  o  m*/
    File file = new File(createTempDir().toFile(), "README");
    FileOutputStream os = new FileOutputStream(file);
    IOUtils.copy(is, os);
    os.close();
    is.close();

    ContentStreamBase stream = new ContentStreamBase.URLStream(new URL(file.toURI().toASCIIString()));
    InputStream s = stream.getStream();
    FileInputStream fis = new FileInputStream(file);
    FileInputStream fis2 = new FileInputStream(file);
    InputStreamReader isr = new InputStreamReader(fis, StandardCharsets.UTF_8);
    Reader r = stream.getReader();
    try {
        assertTrue(IOUtils.contentEquals(fis2, s));
        assertEquals(file.length(), stream.getSize().intValue());
        assertTrue(IOUtils.contentEquals(isr, r));
        assertEquals(file.length(), stream.getSize().intValue());
    } finally {
        r.close();
        s.close();
        isr.close();
        fis.close();
        fis2.close();
    }
}

From source file:eu.eexcess.opensearch.opensearchDescriptionDocument.parse.OpenSearchDocumentParserTest.java

License:asdf

/**
 * Parse XML from relativeFilepath and build an
 * {@link OpensearchDescription}//from  w  w w. j  a  v  a 2 s  .  c  o  m
 * 
 * @param relativeFilepath
 * @return
 */
private OpensearchDescription readFromXMLFile(String relativeFilepath) {
    InputStream inputFile = OpenSearchDocumentParserTest.class.getResourceAsStream(relativeFilepath);

    OpensearchDescription document = null;

    InputStreamReader fileReader = new InputStreamReader(inputFile);

    try {
        StringBuilder xmlDocumentDescription = new StringBuilder();
        int character = fileReader.read();
        while (character != -1) {
            xmlDocumentDescription.append((char) character);
            character = fileReader.read();
        }
        fileReader.close();

        OpenSearchDocumentParser parser = new OpenSearchDocumentParser();
        document = parser.toDescriptionDocument(xmlDocumentDescription.toString());

    } catch (IOException e) {
        logger.log(Level.ERROR, e);
    }
    return document;
}