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.rapidminer.tools.Tools.java

/**
 * Reads a text file into a single string. Process files created with RapidMiner 5.2.008 or
 * earlier will be read with the system encoding (for compatibility reasons); all other files
 * will be read with UTF-8 encoding./*from   w w w.  j a  va  2 s  .  co  m*/
 * */
public static String readTextFile(File file) throws IOException {
    FileInputStream inStream = new FileInputStream(file);

    // due to a bug in pre-5.2.009, process files were stored in System encoding instead of
    // UTF-8. So we have to check the process version, and if it's less than 5.2.009 we have
    // to retrieve the file again with System encoding.
    // If anything goes wrong while parsing the version number, we continue with the old
    // method. If something goes wrong, the file is either not utf-8 encoded (so the old
    // method will probably work), or it is not a valid process file (which will also be
    // detected by the old method).
    boolean useFallback = false;
    try {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document processXmlDocument = documentBuilder.parse(inStream);
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
        String versionString = xPath.evaluate("/process/@version", processXmlDocument);
        VersionNumber version = new VersionNumber(versionString);
        if (version.isAtMost(5, 2, 8)) {
            useFallback = true;
        }
    } catch (XPathExpressionException e) {
        useFallback = true;
    } catch (SAXException e) {
        useFallback = true;
    } catch (ParserConfigurationException e) {
        useFallback = true;
    } catch (IOException e) {
        useFallback = true;
    } catch (NumberFormatException e) {
        useFallback = true;
    }

    InputStreamReader reader = null;

    try {
        inStream = new FileInputStream(file);
        if (useFallback) {
            // default reader (as in old versions)
            reader = new InputStreamReader(inStream);
        } else {
            // utf8 reader
            reader = new InputStreamReader(inStream, XMLImporter.PROCESS_FILE_CHARSET);
        }

        return readTextFile(reader);
    } finally {
        try {
            inStream.close();
        } catch (IOException e) {
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:cn.leancloud.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

/**
 * ?Response??//  w w w  .  jav  a 2 s  . c o  m
 * 
 * @param httpMethod
 * @return
 */
String getContent(HttpMethod httpMethod) throws UnsupportedEncodingException {
    StringBuilder contentBuilder = new StringBuilder();
    if (isZipContent(httpMethod)) {
        // ???
        InputStream is = null;
        GZIPInputStream gzin = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            is = httpMethod.getResponseBodyAsStream();
            gzin = new GZIPInputStream(is);
            isr = new InputStreamReader(gzin, ((HttpMethodBase) httpMethod).getResponseCharSet()); // ?????
            br = new BufferedReader(isr);
            char[] buffer = new char[4096];
            int readlen = -1;
            while ((readlen = br.read(buffer, 0, 4096)) != -1) {
                contentBuilder.append(buffer, 0, readlen);
            }
        } catch (Exception e) {
            log.error("", e);
        } finally {
            try {
                br.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                isr.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                gzin.close();
            } catch (Exception e1) {
                // ignore
            }
            try {
                is.close();
            } catch (Exception e1) {
                // ignore
            }
        }
    } else {
        // ???
        String content = null;
        try {
            content = httpMethod.getResponseBodyAsString();
        } catch (Exception e) {
            log.error("???", e);
        }
        if (null == content) {
            return null;
        }
        contentBuilder.append(content);
    }
    return StringEscapeUtils.unescapeHtml(contentBuilder.toString());
}

From source file:com.kdmanalytics.toif.ui.common.AdaptorConfiguration.java

/**
 * Load configuration data from the specified stream.
 * /*from  w  w w. j ava 2s.c  o  m*/
 * @param is
 * @throws IOException
 */
private synchronized void load(InputStream is) throws IOException {
    if (!isEmpty()) {
        // If there is already data loaded, we want to merge the new data
        merge(is);
    } else {
        InputStreamReader in = null;
        CSVParser parser = null;
        try {
            in = new InputStreamReader(is);
            CSVFormat format = CSVFormat.EXCEL.withDelimiter(',').withIgnoreEmptyLines();

            parser = new CSVParser(in, format);

            // Set to false once the header is read
            boolean header = true;
            // Number of rows we have loaded so far
            int rcount = data.size();
            // Import all new rows
            for (CSVRecord record : parser) {
                if (header) {
                    parseHeader(record);
                    header = false;
                } else {
                    rcount = parseData(record, rcount);
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (parser != null) {
                parser.close();
            }
        }
    }
}

From source file:it.infn.ct.corsika_portlet.java

public String uncompress(String source, String destination) {
    String folderName = null;/*from   w  ww.j a va2 s .co m*/
    try {
        _log.info("Uncompressing file with command " + "tar " + " -xzvf " + source + "-C " + destination);
        Process process = new ProcessBuilder("tar", "-xzvf", source, "-C", destination).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String fullFileName = br.readLine();
        String relativeFolderName = fullFileName.split("/")[0];

        try {
            Thread.sleep(10 * 1000);
        } catch (InterruptedException ie) {
            //Handle exception
        }

        is.close();
        isr.close();
        br.close();

        folderName = destination + "/" + relativeFolderName;

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("File could not be extracted");
    } finally {
        return folderName;
    }

}

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

/**
 * Opens the http connection to http://www.google.com/, and enables the
 * network data packet.//from  w  w  w .j a va  2 s . c o  m
 * 
 * @throws java.io.IOException
 * @throws ClientProtocolException
 */
public void OpenHttpConnection() throws ClientProtocolException, IOException {

    final String strUrl = "http://www.google.com";
    final int timeoutConnection = 15000;
    final int timeoutSocket = 15000;
    InputStream in = null;
    BufferedReader reader = null;
    InputStreamReader inputstreamReader = null;
    HttpClient client = null;
    HttpResponse response = null;
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    client = new DefaultHttpClient(httpParameters);
    HttpPost post = new HttpPost(strUrl);
    try {
        // add headers
        post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        post.addHeader("Cache-Control", "no-cache");
        post.addHeader("Pragma", "no-cache");
        response = client.execute(post);
        in = response.getEntity().getContent();
        inputstreamReader = new InputStreamReader(in);
        reader = new BufferedReader(inputstreamReader);
        final StringBuilder builder = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            builder.append(line + "\n");
        }

    } finally {
        if (inputstreamReader != null) {
            inputstreamReader.close();
        }
        if (in != null) {
            in.close();
        }
        if (reader != null) {
            reader.close();
        }
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        httpParameters = null;
        post = null;
        client = null;
        response = null;

    }
}

From source file:com.janoz.usenet.searchers.impl.NzbsOrgConnectorImpl.java

public void validate() throws SearchException {
    THROTTLER.throttle();//from  w ww  .  jav  a2  s.c  o  m
    InputStreamReader isr = null;
    try {
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("action", "getnzb"));
        params.add(new BasicNameValuePair("nzbid", "" + 0));
        URI uri = getUri("index.php", params);
        isr = new InputStreamReader((InputStream) uri.toURL().getContent());

        char[] buffer = new char[BUFFSIZE];
        int numRead;
        int trueCount = 0;
        int falseCount = 0;
        while ((numRead = isr.read(buffer)) > 0) {
            for (int c = 0; c < numRead; c++) {
                if (buffer[c] == VALID_STRING.charAt(trueCount)) {
                    trueCount++;
                } else {
                    trueCount = 0;
                }
                if (trueCount == VALID_STRING.length())
                    return;
                if (buffer[c] == INVALID_STRING.charAt(falseCount)) {
                    falseCount++;
                } else {
                    falseCount = 0;
                }
                if (falseCount == INVALID_STRING.length()) {
                    throw new SearchException("Invalid credentials.");
                }
            }
        }
        throw new SearchException("Unable to determine validity.");
    } catch (IOException ioe) {
        throw new SearchException("Error connecting to Nzbs.org.", ioe);
    } catch (URISyntaxException e) {
        throw new SearchException("Error parsing URI.", e);
    } finally {
        THROTTLER.setThrottleForNextAction();
        if (isr != null) {
            try {
                isr.close();
            } catch (IOException e) {
                /* dan niet */
            }
        }
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java

/**
 * Returns the resource uri or <code>null</code> if no resource id and/or path
 * could be found on the specified document. This method is intended to serve
 * as a utility method when importing resources.
 * /* w ww. j a v  a2  s  .co  m*/
 * @param site
 *          the resource uri
 * @param contentUrl
 *          location of the resource file
 * @return the resource uri
 */
protected ResourceURI loadResourceURI(Site site, URL contentUrl) throws IOException {

    InputStream is = null;
    InputStreamReader reader = null;
    try {
        is = new BufferedInputStream(contentUrl.openStream());
        reader = new InputStreamReader(is);
        CharBuffer buf = CharBuffer.allocate(1024);
        reader.read(buf);
        String s = new String(buf.array());
        s = s.replace('\n', ' ');
        Matcher m = resourceHeaderRegex.matcher(s);
        if (m.matches()) {
            long version = ResourceUtils.getVersion(m.group(4));
            return new ResourceURIImpl(m.group(1), site, m.group(3), m.group(2), version);
        }
        return null;
    } finally {
        if (reader != null)
            reader.close();
        IOUtils.closeQuietly(is);
    }
}

From source file:com.moviejukebox.tools.WebBrowser.java

@SuppressWarnings("resource")
public String request(URL url, Charset charset) throws IOException {
    LOG.debug("Requesting {}", url.toString());

    // get the download limit for the host
    ThreadExecutor.enterIO(url);/*from   www.  j  av  a2 s .c  om*/
    StringWriter content = new StringWriter(10 * 1024);
    try {

        URLConnection cnx = null;

        try {
            cnx = openProxiedConnection(url);

            sendHeader(cnx);
            readHeader(cnx);

            InputStreamReader inputStreamReader = null;
            BufferedReader bufferedReader = null;

            try (InputStream inputStream = cnx.getInputStream()) {

                // If we fail to get the URL information we need to exit gracefully
                if (charset == null) {
                    inputStreamReader = new InputStreamReader(inputStream, getCharset(cnx));
                } else {
                    inputStreamReader = new InputStreamReader(inputStream, charset);
                }
                bufferedReader = new BufferedReader(inputStreamReader);

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    content.write(line);
                }

                // Attempt to force close connection
                // We have HTTP connections, so these are always valid
                content.flush();

            } catch (FileNotFoundException ex) {
                LOG.error("URL not found: {}", url.toString());
            } catch (IOException ex) {
                LOG.error("Error getting URL {}, {}", url.toString(), ex.getMessage());
            } finally {
                // Close resources
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (Exception ex) {
                        /* ignore */ }
                }
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (Exception ex) {
                        /* ignore */ }
                }
            }
        } catch (SocketTimeoutException ex) {
            LOG.error("Timeout Error with {}", url.toString());
        } finally {
            if (cnx != null) {
                if (cnx instanceof HttpURLConnection) {
                    ((HttpURLConnection) cnx).disconnect();
                }
            }
        }
        return content.toString();
    } finally {
        content.close();
        ThreadExecutor.leaveIO();
    }
}

From source file:com.util.httpHistorial.java

public List<Llamadas> getHistorial(String idAccount, String page, String max, String startDate, String endDate,
        String destination) {/* ww w .java 2s. c om*/

    // String idAccount = "2";
    // String page = "1";
    // String max = "10";
    //String startDate = "2016-09-20 00:00:00";
    // String endDate = "2016-10-30 23:59:59";
    // String destination = "";
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    String myURL = "http://192.168.5.44/app_dev.php/cus/cdrs/history/" + idAccount + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            urlConn.setDoOutput(true);
            String data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(page, "UTF-8");
            data += "&" + URLEncoder.encode("max", "UTF-8") + "=" + URLEncoder.encode(max, "UTF-8");
            data += "&" + URLEncoder.encode("startDate", "UTF-8") + "=" + URLEncoder.encode(startDate, "UTF-8");
            data += "&" + URLEncoder.encode("endDate", "UTF-8") + "=" + URLEncoder.encode(endDate, "UTF-8");
            data += "&" + URLEncoder.encode("destination", "UTF-8") + "="
                    + URLEncoder.encode(destination, "UTF-8");
            System.out.println("los Datos a enviar por POST son " + data);

            try ( //obtenemos el flujo de escritura
                    OutputStreamWriter wr = new OutputStreamWriter(urlConn.getOutputStream())) {
                //escribimos
                wr.write(data);
                wr.flush();
                //cerramos la conexin
            }
        }
        if (urlConn != null && urlConn.getInputStream() != null) {
            in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

            BufferedReader bufferedReader = new BufferedReader(in);
            if (bufferedReader != null) {
                int cp;
                while ((cp = bufferedReader.read()) != -1) {
                    sb.append((char) cp);
                }
                bufferedReader.close();
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }
    String jsonResult = sb.toString();
    System.out.println("DATOS ENVIADOS DEL SERVIDOR " + sb.toString());

    System.out.println(
            "\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
    JSONObject objJason = new JSONObject(jsonResult);
    // JSONArray dataJson = new JSONArray();
    //  dataJson = objJason.getJSONArray("data");
    String jdata = objJason.optString("data");
    String mensaje = objJason.optString("message");
    System.out.println("\n\n MENSAJE DEL SERVIDOR " + mensaje);
    //System.out.println(" el objeto jdata es "+jdata);
    objJason = new JSONObject(jdata);
    //  System.out.println("objeto normal 1 " + objJason.toString());
    //
    jdata = objJason.optString("items");
    // System.out.println("\n\n el objeto jdata es " + jdata);
    JSONArray jsonArray = new JSONArray();
    Gson gson = new Gson();
    //objJason = gson.t
    jsonArray = objJason.getJSONArray("items");
    // System.out.println("\n\nEL ARRAY FINAL ES " + jsonArray.toString());

    List<Llamadas> llamadas = new ArrayList<Llamadas>();

    for (int i = 0; i < jsonArray.length(); i++) {
        Llamadas llamada = new Llamadas();
        llamada.setNo(i + 1);
        llamada.setInicioLLamada(jsonArray.getJSONObject(i).getString("callstart"));
        llamada.setNumero(jsonArray.getJSONObject(i).getString("callednum"));
        llamada.setPais_operador(jsonArray.getJSONObject(i).getString("notes"));
        llamada.setDuracionSegundos(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
        llamada.setCostoTotal(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
        llamada.setCostoMinuto(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));

        long minutos = Long.parseLong(llamada.getDuracionSegundos()) / 60;
        llamada.setDuracionMinutos(minutos);

        llamadas.add(llamada);

    }

    for (int i = 0; i < llamadas.size(); i++) {
        System.out.print("\n\nNo" + llamadas.get(i).getNo());
        System.out.print("  Fecna " + llamadas.get(i).getInicioLLamada());
        System.out.print("  Numero " + llamadas.get(i).getNumero());
        System.out.print("  Pais-Operador " + llamadas.get(i).getPais_operador());
        System.out.print("  Cantidad de segundos " + llamadas.get(i).getDuracionSegundos());
        System.out.print("  Costo total " + llamadas.get(i).getCostoTotal());
        System.out.print("  costo por minuto " + llamadas.get(i).getCostoMinuto());
        System.out.print("  costo por minuto " + llamadas.get(i).getDuracionMinutos());

    }

    /**
     * List<String> list = new ArrayList<String>(); for (int i = 0; i <
     * jsonArray.length(); i++) { list.add(String.valueOf(i));
     * list.add(jsonArray.getJSONObject(i).getString("callstart"));
     * list.add(jsonArray.getJSONObject(i).getString("callednum"));
     * list.add(jsonArray.getJSONObject(i).getString("notes"));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("cost")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("billseconds")));
     * list.add(String.valueOf(jsonArray.getJSONObject(i).getBigDecimal("rate_cost")));
     * } System.out.println("\n\nel array java contiene " +
     * list.toString());
     *
     */
    return llamadas;
}

From source file:org.ala.spatial.web.services.GDMWSController.java

private int runGDM(int level, String params) {
    Runtime runtime = Runtime.getRuntime();
    Process proc;/*from ww w.  j  ava  2s  . co  m*/
    InputStreamReader isre = null, isr = null;
    BufferedReader bre = null, br = null;
    int exitValue = -1;

    try {
        String command = AlaspatialProperties.getAnalysisGdmCmd() + " -g" + level + " " + params;
        System.out.println("Running gdm: " + command);

        //            return 111;

        proc = runtime.exec(command);

        isre = new InputStreamReader(proc.getErrorStream());
        bre = new BufferedReader(isre);
        isr = new InputStreamReader(proc.getInputStream());
        br = new BufferedReader(isr);
        String line;

        while ((line = bre.readLine()) != null) {
            System.out.println(line);
        }

        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }

        int exitVal = proc.waitFor();

        // any error???
        exitValue = exitVal;

    } catch (Exception e) {
        System.out.println("Error executing GDM: ");
        e.printStackTrace(System.out);
    } finally {
        try {
            isre.close();
            bre.close();
            isr.close();
            br.close();
        } catch (IOException ioe) {
            System.out.println("Error closing output and error streams");
        }
    }

    return exitValue;
}