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:org.wso2.carbon.appmanager.integration.ui.Util.HttpUtil.java

/**
 * convert org.apache.http.HttpResponse  to org.wso2.carbon.automation.core.utils.HttpResponse
 *
 * @param res org.apache.http.HttpResponse
 * @return org.wso2.carbon.automation.core.utils.HttpResponse
 * @throws Exception/*from   w  w  w  .  j  av  a2s.co m*/
 */
public static HttpResponse convertResponse(org.apache.http.HttpResponse res) throws IOException {
    int responseCode = res.getStatusLine().getStatusCode();
    String data = "";
    InputStreamReader in = null;
    BufferedReader br = null;
    try {
        in = new InputStreamReader((res.getEntity().getContent()));
        br = new BufferedReader(in);
        String line = "";
        while ((line = br.readLine()) != null) {
            data = data.concat(line);
        }
    } finally {
        in.close();
        br.close();
    }
    HttpResponse response = new HttpResponse(data, responseCode);
    return response;
}

From source file:Main.java

public static List<String> getTextToList(InputStream inputStream) {
    InputStreamReader inputStreamReader = null;
    BufferedReader bufferedReader = null;
    List<String> list = new ArrayList<String>();
    try {//from   w  w  w.j  av  a2 s .c om
        inputStreamReader = new InputStreamReader(inputStream);
        bufferedReader = new BufferedReader(inputStreamReader);
        String text;
        while ((text = bufferedReader.readLine()) != null) {
            list.add(text);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (bufferedReader != null) {
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return list;
}

From source file:com.bstek.dorado.data.model.TestDataHolder.java

private static ArrayNode getTestData1() throws IOException {
    InputStreamReader isr = new InputStreamReader(
            TestDataHolder.class.getResourceAsStream("/com/bstek/dorado/data/model/test-data1.js"),
            Constants.DEFAULT_CHARSET);// w  w  w  .  ja v  a  2 s. co m
    try {
        BufferedReader reader = new BufferedReader(isr);
        String l;
        StringBuffer sb = new StringBuffer();
        while ((l = reader.readLine()) != null) {
            sb.append(l).append('\n');
        }
        ArrayNode json = (ArrayNode) JsonUtils.getObjectMapper().readTree(sb.toString());
        return json;
    } finally {
        isr.close();
    }
}

From source file:com.bstek.dorado.data.model.TestDataHolder.java

private static ArrayNode getTestData2() throws IOException {
    InputStreamReader isr = new InputStreamReader(
            TestDataHolder.class.getResourceAsStream("/com/bstek/dorado/data/model/test-data2.js"),
            Constants.DEFAULT_CHARSET);//from   w w  w .  j a  v  a  2s.co m
    try {
        BufferedReader reader = new BufferedReader(isr);
        String l;
        StringBuffer sb = new StringBuffer();
        while ((l = reader.readLine()) != null) {
            sb.append(l).append('\n');
        }
        ArrayNode json = (ArrayNode) JsonUtils.getObjectMapper().readTree(sb.toString());
        return json;
    } finally {
        isr.close();
    }
}

From source file:Main.java

public static String readRawByName(Context context, int id, String encoding) {
    String text = null;// w  w  w.  ja  v  a  2 s  . c om
    InputStreamReader inputReader = null;
    BufferedReader bufReader = null;
    try {
        inputReader = new InputStreamReader(context.getResources().openRawResource(id));
        bufReader = new BufferedReader(inputReader);
        String line = null;
        StringBuffer buffer = new StringBuffer();
        while ((line = bufReader.readLine()) != null) {
            buffer.append(line);
        }
        text = new String(buffer.toString().getBytes(), encoding);
    } catch (Exception e) {
    } finally {
        try {
            if (bufReader != null) {
                bufReader.close();
            }
            if (inputReader != null) {
                inputReader.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return text;
}

From source file:com.depas.utils.FileUtils.java

/**
 * Close input stream reader if not null
 * @param inputStreamReader is given input stream reader
 *//*from   w  w w  .  j av  a2 s .  c o m*/
public static void closeInputStreamReader(InputStreamReader inputStreamReader) {
    if (inputStreamReader != null) {
        try {
            inputStreamReader.close();
        } catch (IOException e) {
            logger.warn("Unable to close the input stream reader: " + e, e);
        }
    }
}

From source file:energy.usef.environment.tool.security.VaultService.java

/**
 * Executes a class's static main method with the current java executable and classpath in a separate process.
 * /*from  w  ww.j  a  va2  s . c  o  m*/
 * @param klass the class to call the static main method for
 * @param params the parameters to provide
 * @return the exit code of the process
 * @throws IOException
 * @throws InterruptedException
 */
public static int exec(@SuppressWarnings("rawtypes") Class klass, List<String> params)
        throws IOException, InterruptedException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = System.getProperty("java.class.path");
    String className = klass.getCanonicalName();

    // construct the command line
    List<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-cp");
    command.add(classpath);
    command.add(className);
    command.addAll(params);
    LOGGER.debug("executing class '{}' with params '{}' in classpath '{}' with java binary '{}'", className,
            params.toString(), classpath, javaBin);

    // build and start the Vault's process
    ProcessBuilder builder = new ProcessBuilder(command);
    Process process = builder.start();
    process.waitFor();

    // get the input and error streams of the process and log them
    InputStream in = process.getInputStream();
    InputStream en = process.getErrorStream();
    InputStreamReader is = new InputStreamReader(in);
    InputStreamReader es = new InputStreamReader(en);
    BufferedReader br = new BufferedReader(is);
    BufferedReader be = new BufferedReader(es);

    String read = br.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = br.readLine();
    }
    read = be.readLine();
    while (read != null) {
        LOGGER.debug(read);
        read = be.readLine();
    }

    br.close();
    is.close();
    in.close();

    return process.exitValue();
}

From source file:de.domjos.schooltools.helper.Helper.java

public static String getStringFromFile(String path, Context context) {
    StringBuilder fileContent = new StringBuilder();
    try {/*w  w w  .jav a2  s. com*/
        File readableFile = new File(path);
        if (readableFile.exists() && readableFile.isFile()) {
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(readableFile),
                    Charset.defaultCharset());
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent.append(line);
                fileContent.append("\n");
            }
            reader.close();
            inputStreamReader.close();
        }
    } catch (Exception ex) {
        Helper.printException(context, ex);
    }
    return fileContent.toString();
}

From source file:org.apache.jmeter.save.SaveService.java

/**
 * /* ww  w  .  j  a v  a2 s .c  om*/
 * @param reader {@link InputStream} 
 * @param file the JMX file used only for debug, can be null
 * @return the loaded tree
 * @throws IOException if there is a problem reading the file or processing it
 */
private static HashTree readTree(InputStream reader, File file) throws IOException {
    if (!reader.markSupported()) {
        reader = new BufferedInputStream(reader);
    }
    reader.mark(Integer.MAX_VALUE);
    ScriptWrapper wrapper = null;
    try {
        // Get the InputReader to use
        InputStreamReader inputStreamReader = getInputStreamReader(reader);
        wrapper = (ScriptWrapper) JMXSAVER.fromXML(inputStreamReader);
        inputStreamReader.close();
        if (wrapper == null) {
            log.error("Problem loading XML: see above.");
            return null;
        }
        return wrapper.testPlan;
    } catch (CannotResolveClassException e) {
        if (file != null) {
            throw new IllegalArgumentException("Problem loading XML from:'" + file.getAbsolutePath()
                    + "', cannot determine class for element: " + e, e);
        } else {
            throw new IllegalArgumentException("Problem loading XML, cannot determine class for element: " + e,
                    e);
        }
    } catch (ConversionException | NoClassDefFoundError e) {
        if (file != null) {
            throw new IllegalArgumentException(
                    "Problem loading XML from:'" + file.getAbsolutePath() + "', missing class " + e, e);
        } else {
            throw new IllegalArgumentException("Problem loading XML, missing class " + e, e);
        }
    }

}

From source file:bsb.vote.service.DoVote.java

private static boolean regUser(DefaultHttpClient httpclient)
        throws UnsupportedEncodingException, IOException, JSONException {
    //        httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.ACCEPT_ALL);  
    HttpPost httppost = new HttpPost("http://m.passport.cntv.cn/site/reg");
    System.out.println(": " + httppost.getRequestLine());
    // ??// ww  w . j  av  a  2 s.c  om
    //??
    String n1 = (String.valueOf(System.currentTimeMillis() % (9999999 - 1111111) + 1111111));
    String n2 = (String.valueOf(System.currentTimeMillis() % (999 - 111) + 111));
    String phoneNum = "1" + n1 + n2;
    System.out.print(phoneNum + "\n");
    StringEntity reqEntity = new StringEntity(
            "Form%5Busername%5D=" + phoneNum + "&Form%5Brealname%5D=&Form%5Bpassword%5D=123456&app=bsb");
    // ?   
    httppost.setEntity(reqEntity);
    //
    httppost.setHeader("Host", "m.passport.cntv.cn");
    httppost.setHeader("User-Agent",
            "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16");
    httppost.setHeader("Accept", "application/json");
    httppost.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
    httppost.setHeader("Accept-Encoding", "gzip, deflate");
    httppost.setHeader("X-Requested-With", "XMLHttpRequest");
    httppost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    httppost.setHeader("Referer", "http://m.passport.cntv.cn/html/reg.html?rurl=http%3A%2F%2Fqr.cntv.cn%2Fbsb");
    httppost.setHeader("Connection", "keep-alive");
    httppost.setHeader("Pragma", "no-cache");
    httppost.setHeader("Cache-Control", "no-cache");
    //
    HttpResponse response = httpclient.execute(httppost);

    //        Header[] heads = response.getAllHeaders();
    // ??   
    //        for (Header h : heads) {
    //            System.out.println(h.getName() + ":" + h.getValue());
    //        }

    //???
    response.setEntity(new GzipDecompressingEntity(response.getEntity()));
    HttpEntity entity = response.getEntity();
    // 
    //            GZIPInputStream gInputStream = new GZIPInputStream(entity.getContent());
    //            byte[] by = new byte[1024];
    //            StringBuilder builder = new StringBuilder();
    //            int len = 0;
    //            while ((len = gInputStream.read(by)) != -1) {
    //                builder.append(new String(by, 0, len, "UTF-8"));
    //            }
    InputStreamReader rr = new InputStreamReader(entity.getContent(), "UTF-8");
    BufferedReader reader = new BufferedReader(rr);
    StringBuilder builder = new StringBuilder();
    System.out.println("?-----------------------------------------");
    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        builder.append(line);
    }
    rr.close();
    try {
        JSONObject jsonObject = new JSONObject(builder.toString());
        System.out.println("+++++++++++++++++++++\n" + jsonObject.getInt("error"));
        System.out.println("--------" + jsonObject.getString("msg"));
        if (jsonObject.getInt("error") != 0) {
            try {
                Thread.sleep(60000 * 3);
            } catch (InterruptedException ex) {
                Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        } else {
            return true;
        }
    } catch (JSONException e) {
        return false;
    }
}