List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:org.apache.mycat.advisor.common.net.http.HttpService.java
/** * ? header?// w w w. j a v a 2s. c o m * * @param requestUrl * @param requestMethod * @param WithTokenHeader * @param token * @return */ public static String doHttpRequest(String requestUrl, String requestMethod, Boolean WithTokenHeader, String token) { String result = null; InetAddress ipaddr; int responseCode = -1; try { ipaddr = InetAddress.getLocalHost(); StringBuffer buffer = new StringBuffer(); URL url = new URL(requestUrl); HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection(); httpUrlConn.setDoOutput(true); httpUrlConn.setDoInput(true); httpUrlConn.setUseCaches(false); httpUrlConn.setUseCaches(false); httpUrlConn.setRequestProperty("Accept-Charset", DEFAULT_CHARSET); httpUrlConn.setRequestProperty("Content-Type", "application/json;charset=" + DEFAULT_CHARSET); if (WithTokenHeader) { if (token == null) { throw new IllegalStateException("Oauth2 token is not set!"); } httpUrlConn.setRequestProperty("Authorization", "OAuth2 " + token); httpUrlConn.setRequestProperty("API-RemoteIP", ipaddr.getHostAddress()); } // ?GET/POST httpUrlConn.setRequestMethod(requestMethod); if ("GET".equalsIgnoreCase(requestMethod)) httpUrlConn.connect(); // // ???? // if (null != outputJson) { // OutputStream outputStream = httpUrlConn.getOutputStream(); // //?? // outputStream.write(outputJson.getBytes(DEFAULT_CHARSET)); // outputStream.close(); // } // ??? InputStream inputStream = httpUrlConn.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, DEFAULT_CHARSET); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); String str = null; while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } result = buffer.toString(); bufferedReader.close(); inputStreamReader.close(); // ? inputStream.close(); httpUrlConn.disconnect(); } catch (ConnectException ce) { logger.error("server connection timed out.", ce); } catch (Exception e) { logger.error("http request error:", e); } finally { return result; } }
From source file:com.sec.ose.osi.UIMain.java
private static boolean isRunning() { log.debug("Running Test..."); String execCMD = ""; String protexStr = ""; String osName = System.getProperty("os.name").toLowerCase(); if (osName.indexOf("win") >= 0) { // windows execCMD = "TASKLIST /V /FO CSV /FI \"IMAGENAME eq javaw.exe\" /NH"; protexStr = "osit"; } else if (osName.indexOf("nix") >= 0 || osName.indexOf("nux") >= 0) { execCMD = "ps -ef"; protexStr = "java -jar ./lib/" + OSIT_JAR_FILE_NAME; } else {/*w w w . j a v a 2s. com*/ JOptionPane.showMessageDialog(null, osName + " is not supported. The program will be closed.", "Error", JOptionPane.ERROR_MESSAGE); // System.exit(-1); } InputStreamReader isr = null; try { Process p = Runtime.getRuntime().exec(execCMD); isr = new InputStreamReader(p.getInputStream(), "UTF-8"); BufferedReader reader = new BufferedReader(isr); String str = null; int count = 0; while ((str = reader.readLine()) != null) { log.debug("### ONLY ONE OSI PROCESS CHECK : " + str.toLowerCase()); if (str.toLowerCase().contains(protexStr.toLowerCase())) { if (++count > 1) { reader.close(); return true; } } } } catch (IOException e1) { log.warn(e1.getMessage()); } finally { try { if (isr != null) { isr.close(); } } catch (Exception e) { log.debug(e); } } return false; }
From source file:bsb.vote.service.DoVote.java
private static boolean vote(DefaultHttpClient httpclient, String ITEM_ID, String V_ID) throws UnsupportedEncodingException, IOException { // HttpGet httpget = new HttpGet("http://qr.cntv.cn/bsb/vote/Post?itemid=3249&vid=366"); HttpGet httpget = new HttpGet("http://qr.cntv.cn/bsb/vote/Post?itemid=" + ITEM_ID + "&vid=" + V_ID); System.out.println(": " + httpget.getRequestLine()); ///* w ww . j a va2 s. com*/ httpget.setHeader("Host", "qr.cntv.cn"); httpget.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"); httpget.setHeader("Accept", "application/json, text/javascript, */*; q=0.01"); httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); httpget.setHeader("Accept-Encoding", "gzip, deflate"); httpget.setHeader("DNT", "1"); httpget.setHeader("Referer", "http://qr.cntv.cn/bsb"); httpget.setHeader("Connection", "keep-alive"); //httpget.setHeader("Cookie", "m_cntv_app=bsb;m_cntv_gapp=bsb;m_cntv_uid=7047108;m_cntv_nickname=%E5%A4%AE%E8%A7%86%E7%BD%91%E5%8F%8B;m_cntv_avatar=http%3A%2F%2Fm.passport.cntv.cn%2Fimages%2Favatar.jpg;m_cntv_mobile=312fJo3LydoFGja0HbDQVxa8okTmRQFeg90mk9K%2BGB4MxSQnZobzTA;m_cntv_realname=d91arKGm5cJt%2BjsVAqMgDcNhgLiEG3sVY693zP4;m_cntv_auth=070djYVzCvXdNB%2B2D06%2BQz2xUW3RgaNBewF0Os2m05ph2AQ37AXbRaKSZuoD8VEUA7EkpjhMAw;iphoneFix=FixHidden"); // HttpResponse response = httpclient.execute(httpget); // 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()); // response.setEntity(new GzipDecompressingEntity(response.getEntity())); // BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); // 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(); // BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8")); // 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) { if ("??1".equals(jsonObject.getString("msg"))) { return true; } else { try { Thread.sleep(60000 * 3); } catch (InterruptedException ex) { Logger.getLogger(DoVote.class.getName()).log(Level.SEVERE, null, ex); } return false; } } } catch (JSONException e) { return false; } return false; }
From source file:gsn.http.ac.ParameterSet.java
private static void changeSensorName(String filepath, String name) { File f = new File(filepath); Pattern pat = Pattern.compile("name[\\s]*=[\\s]*\"[\\s]*[\\S]+[\\s]*\""); Matcher match;/*from ww w.java2 s . co m*/ FileInputStream fs = null; InputStreamReader in = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); String textinLine; try { fs = new FileInputStream(f); in = new InputStreamReader(fs); br = new BufferedReader(in); while (true) { textinLine = br.readLine(); if (textinLine == null) break; if (textinLine.contains("<virtual-sensor")) { match = pat.matcher(textinLine); match.find(); textinLine = match.replaceFirst("name=\"" + name + "\""); } sb.append(textinLine + "\n"); } fs.close(); in.close(); br.close(); } catch (FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (IOException e) { logger.error(e.getMessage(), e); } try { FileWriter fstream = new FileWriter(f); // write file again BufferedWriter outobj = new BufferedWriter(fstream); outobj.write(sb.toString()); outobj.close(); } catch (Exception e) { logger.error(e.getMessage(), e); } }
From source file:com.qweex.callisto.moar.twit.java
public static String callURL(String myURL) { StringBuilder sb = new StringBuilder(); URLConnection urlConn = null; InputStreamReader in = null; try {/*w w w.j av a2 s. c o m*/ URL url = new URL(myURL); urlConn = url.openConnection(); if (urlConn != null) urlConn.setReadTimeout(60 * 1000); 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) { throw new RuntimeException("Exception while calling URL:" + myURL, e); } return sb.toString(); }
From source file:com.audiokernel.euphonyrmt.cover.AbstractWebCover.java
private static String readInputStream(final InputStream content) { final InputStreamReader inputStreamReader = new InputStreamReader(content); final BufferedReader reader = new BufferedReader(inputStreamReader); /** We have no /idea/ how large the input is going to be. */ //noinspection StringBufferWithoutInitialCapacity final StringBuilder result = new StringBuilder(); String line;/*w ww . j av a 2s . co m*/ try { line = reader.readLine(); do { result.append(line); line = reader.readLine(); } while (line != null); } catch (final IOException e) { if (CoverManager.DEBUG) { Log.e(TAG, "Failed to retrieve the with the buffered reader.", e); } } finally { try { inputStreamReader.close(); reader.close(); } catch (final IOException e) { Log.e(TAG, "Failed to close the buffered reader.", e); } } return result.toString(); }
From source file:com.mpower.daktar.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//from w ww.j av a 2 s . c om * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(final String urlString, final HttpContext localContext, final HttpClient httpclient, final String auth) { URI u = null; try { final URL url = new URL(URLDecoder.decode(urlString, "utf-8")); u = url.toURI(); } catch (final Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + "while accessing" + urlString, 0); } // set up request... final HttpGet req = WebUtils.createOpenRosaHttpGet(u, auth); HttpResponse response = null; try { response = httpclient.execute(req, localContext); final int statusCode = response.getStatusLine().getStatusCode(); final HttpEntity entity = response.getEntity(); if (entity != null && (statusCode != 200 || !entity.getContentType().getValue().toLowerCase() .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML))) { try { // don't really care about the stream... final InputStream is = response.getEntity().getContent(); // read to end of stream... final long count = 1024L; while (is.skip(count) == count) { ; } is.close(); } catch (final Exception e) { e.printStackTrace(); } } if (statusCode != 200) { final String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { final String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase().contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { final String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); final KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); } finally { if (isr != null) { try { isr.close(); } catch (final Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (final Exception e) { // no-op } } } } catch (final Exception e) { e.printStackTrace(); final String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; final Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; final StringBuilder b = new StringBuilder(); for (final Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (final Exception e) { e.printStackTrace(); String cause; if (e.getCause() != null) { cause = e.getCause().getMessage(); } else { cause = e.getMessage(); } final String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:edu.washington.cs.mystatus.odk.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//from www. j a va 2s . c o m * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? MyStatus.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:org.koboc.collect.android.utilities.WebUtils.java
/** * Common method for returning a parsed xml document given a url and the * http context and client objects involved in the web connection. * * @param urlString//from w w w . j a v a 2 s. co m * @param localContext * @param httpclient * @return */ public static DocumentFetchResult getXmlDocument(String urlString, HttpContext localContext, HttpClient httpclient) { URI u = null; try { URL url = new URL(urlString); u = url.toURI(); } catch (Exception e) { e.printStackTrace(); return new DocumentFetchResult(e.getLocalizedMessage() // + app.getString(R.string.while_accessing) + urlString); + ("while accessing") + urlString, 0); } if (u.getHost() == null) { return new DocumentFetchResult("Invalid server URL (no hostname): " + urlString, 0); } // if https then enable preemptive basic auth... if (u.getScheme().equals("https")) { enablePreemptiveBasicAuth(localContext, u.getHost()); } // set up request... HttpGet req = WebUtils.createOpenRosaHttpGet(u); HttpResponse response = null; try { response = httpclient.execute(req, localContext); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (statusCode != HttpStatus.SC_OK) { WebUtils.discardEntityBytes(response); if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // clear the cookies -- should not be necessary? Collect.getInstance().getCookieStore().clear(); } String webError = response.getStatusLine().getReasonPhrase() + " (" + statusCode + ")"; return new DocumentFetchResult(u.toString() + " responded with: " + webError, statusCode); } if (entity == null) { String error = "No entity body returned from: " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } if (!entity.getContentType().getValue().toLowerCase(Locale.ENGLISH) .contains(WebUtils.HTTP_CONTENT_TYPE_TEXT_XML)) { WebUtils.discardEntityBytes(response); String error = "ContentType: " + entity.getContentType().getValue() + " returned from: " + u.toString() + " is not text/xml. This is often caused a network proxy. Do you need to login to your network?"; Log.e(t, error); return new DocumentFetchResult(error, 0); } // parse response Document doc = null; try { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, "UTF-8"); doc = new Document(); KXmlParser parser = new KXmlParser(); parser.setInput(isr); parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true); doc.parse(parser); isr.close(); isr = null; } finally { if (isr != null) { try { // ensure stream is consumed... final long count = 1024L; while (isr.skip(count) == count) ; } catch (Exception e) { // no-op } try { isr.close(); } catch (Exception e) { // no-op } } if (is != null) { try { is.close(); } catch (Exception e) { // no-op } } } } catch (Exception e) { e.printStackTrace(); String error = "Parsing failed with " + e.getMessage() + "while accessing " + u.toString(); Log.e(t, error); return new DocumentFetchResult(error, 0); } boolean isOR = false; Header[] fields = response.getHeaders(WebUtils.OPEN_ROSA_VERSION_HEADER); if (fields != null && fields.length >= 1) { isOR = true; boolean versionMatch = false; boolean first = true; StringBuilder b = new StringBuilder(); for (Header h : fields) { if (WebUtils.OPEN_ROSA_VERSION.equals(h.getValue())) { versionMatch = true; break; } if (!first) { b.append("; "); } first = false; b.append(h.getValue()); } if (!versionMatch) { Log.w(t, WebUtils.OPEN_ROSA_VERSION_HEADER + " unrecognized version(s): " + b.toString()); } } return new DocumentFetchResult(doc, isOR); } catch (Exception e) { clearHttpConnectionManager(); e.printStackTrace(); String cause; Throwable c = e; while (c.getCause() != null) { c = c.getCause(); } cause = c.toString(); String error = "Error: " + cause + " while accessing " + u.toString(); Log.w(t, error); return new DocumentFetchResult(error, 0); } }
From source file:com.baifendian.swordfish.execserver.utils.OsUtil.java
/** * ?/*from ww w . j av a 2s.c o m*/ * * @return */ public static List<String> getUserList() { List<String> userList = new ArrayList<>(); InputStreamReader inputs = null; BufferedReader buffer = null; try { inputs = new InputStreamReader(new FileInputStream("/etc/passwd")); buffer = new BufferedReader(inputs); String line; while (true) { line = buffer.readLine(); if (line == null) { break; } if (line.contains(":")) { String[] userInfo = line.split(":"); userList.add(userInfo[0]); } } } 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 userList; }