List of usage examples for java.io InputStreamReader close
public void close() throws IOException
From source file:com.jaxio.celerio.util.IOUtil.java
/** * Write to a string the bytes read from an input stream. * * @param charset the charset used to read the input stream * @return the inputstream as a string/*ww w . j a v a 2 s .co m*/ */ public String inputStreamToString(InputStream is, String charset) throws IOException { InputStreamReader isr = null; if (null == charset) { isr = new InputStreamReader(is); } else { isr = new InputStreamReader(is, charset); } StringWriter sw = new StringWriter(); int c = -1; while ((c = isr.read()) != -1) { sw.write(c); } isr.close(); return sw.getBuffer().toString(); }
From source file:org.apache.storm.utils.Utils.java
public static Map<String, Object> fromCompressedJsonConf(byte[] serialized) { try {//from ww w . ja v a 2 s . c o m ByteArrayInputStream bis = new ByteArrayInputStream(serialized); InputStreamReader in = new InputStreamReader(new GZIPInputStream(bis)); Object ret = JSONValue.parseWithException(in); in.close(); return (Map<String, Object>) ret; } catch (IOException | ParseException e) { throw new RuntimeException(e); } }
From source file:org.deegree.portal.standard.nominatim.control.SearchNominatimListener.java
public void actionPerformed(WebEvent event, ResponseHandler responseHandler) throws IOException { String address = getInitParameter("address"); String queryString = (String) event.getParameter().get("QUERYSTRING"); String searchBox = null;//from www .ja v a 2 s .c o m try { searchBox = getSearchBox(); } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } String charEnc = getRequest().getCharacterEncoding(); if (charEnc == null) { charEnc = Charset.defaultCharset().displayName(); } queryString = "q=" + URLEncoder.encode(queryString, "UTF-8") + "&format=xml&limit=100&viewbox=" + searchBox; LOG.logInfo("Nominatim search query: ", address + "?" + queryString); HttpMethod method = HttpUtils.performHttpGet(address, queryString, 60000, null, null, null); InputStreamReader isr = new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"); XMLFragment xml = new XMLFragment(); try { xml.load(isr, address); } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } finally { isr.close(); } if (LOG.getLevel() == ILogger.LOG_DEBUG) { LOG.logDebug(xml.getAsPrettyString()); } List<String[]> result = new ArrayList<String[]>(100); Map<String, String> bboxes = new HashMap<String, String>(100); try { List<Node> nodes = XMLTools.getNodes(xml.getRootElement(), "place", CommonNamespaces.getNamespaceContext()); for (Node node : nodes) { String place = XMLTools.getNodeAsString(node, "@display_name", CommonNamespaces.getNamespaceContext(), ""); String osm_id = XMLTools.getNodeAsString(node, "@osm_id", CommonNamespaces.getNamespaceContext(), ""); result.add(new String[] { place, osm_id }); String boundingbox = XMLTools.getNodeAsString(node, "@boundingbox", CommonNamespaces.getNamespaceContext(), ""); bboxes.put(osm_id, boundingbox); } } catch (Exception e) { LOG.logError(e.getMessage(), e); ExceptionBean eb = new ExceptionBean(getClass().getName(), e.getMessage()); responseHandler.writeAndClose(true, eb); return; } HttpSession session = ((HttpServletRequest) getRequest()).getSession(true); session.setAttribute("NominatimBBOXES", bboxes); // result page uses UTF-8 encoding responseHandler.setContentType("application/json; charset=" + charEnc); responseHandler.writeAndClose(false, result); }
From source file:in.co.praveenkumar.tumtumtracker.LeftNavigationFragment.java
void InitRoutesIfRequired() { List<TTTRoute> routes = TTTRoute.listAll(TTTRoute.class); if (routes.size() != 0) return;// ww w . j a v a 2 s . com AssetManager assetManager = context.getAssets(); try { InputStreamReader reader = new InputStreamReader(assetManager.open("routes.json")); GsonExclude ex = new GsonExclude(); Gson gson = new GsonBuilder().addDeserializationExclusionStrategy(ex) .addSerializationExclusionStrategy(ex).create(); TTTRouteResponse response = gson.fromJson(reader, TTTRouteResponse.class); reader.close(); routes = response.getRoutes(); } catch (Exception e) { e.printStackTrace(); } for (int i = 0; i < routes.size(); i++) routes.get(i).save(); }
From source file:com.aokyu.dev.pocket.http.HttpResponse.java
public String getResponseAsString() throws IOException { InputStream input = mConnection.getInputStream(); InputStreamReader reader = null; BufferedReader buffer = null; String response = null;//from w w w. j a v a2s .c o m try { reader = new InputStreamReader(input); buffer = new BufferedReader(reader); String line = null; StringBuilder builder = new StringBuilder(); while ((line = buffer.readLine()) != null) { builder.append(line); } response = builder.toString(); } finally { if (buffer != null) { buffer.close(); } if (reader != null) { reader.close(); } } return response; }
From source file:org.jinos.transport.HttpTransport.java
/** * Call the service//from w ww . ja v a 2 s .c om * * @param <T> The return type * @param envelope The request envelope * @param resultClass The class of the result in the response * @param httpHeaders The custom Http headers * @return The response * @throws Exception An exception */ public <T> T call(String reqXMLString, Class<T> resultClass, Map<String, String> httpHeaders) throws Exception { try { long start = System.nanoTime(); HttpPost post = new HttpPost(this.getUrl()); post.setEntity(new StringEntity(reqXMLString)); post.setHeader("Content-type", "text/xml; charset=UTF-8"); if (httpHeaders != null) { for (Map.Entry<String, String> entry : httpHeaders.entrySet()) { post.setHeader(entry.getKey(), entry.getValue()); } } /* if (this.getUsername() != null && this.getPassword() != null) { post.addHeader("Authorization", "Basic " + Base64Encoder.encodeString(this.getUsername() + ":" + this.getPassword())); }*/ HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 6000); /* if (this.isDEBUG()) { Log.i(this.getClass().getSimpleName(), "Request: " + envelope.toString()); }*/ HttpClient client = new DefaultHttpClient(httpParameters); HttpResponse response = client.execute(post); int status = response.getStatusLine().getStatusCode(); Log.i(this.getClass().getSimpleName(), "The server has been replied. " + ((System.nanoTime() - start) / 1000) + "us, status is " + status); start = System.nanoTime(); InputStream is = response.getEntity().getContent(); if (true) { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); StringBuilder sb = new StringBuilder(); for (String line = br.readLine(); line != null; line = br.readLine()) { sb.append(line); sb.append("\n"); } Log.i(this.getClass().getSimpleName(), "Response: " + sb.toString()); br.close(); isr.close(); is.close(); is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8")); Log.i(this.getClass().getSimpleName(), "DEBUG mode delay: " + ((System.nanoTime() - start) / 1000) + "us"); start = System.nanoTime(); } /* GenericHandler handler = new GenericHandler(resultClass, this.isDEBUG()); if (status == 200) { handler.parseWithPullParser(is); } else { throw new Exception("Can't parse the response, status: " + status); } Log.i(this.getClass().getSimpleName(), "The reply has been parsed: " + ((System.nanoTime() - start) / 1000) + "us"); */ //return (T) handler.getObject(); return null; } catch (Exception e) { Log.e(this.getClass().getSimpleName(), e.toString(), e); throw e; } }
From source file:gov.medicaid.verification.BaseSOAPClient.java
/** * Invokes the web service using the request provided. * * @param serviceURL the end point reference * @param original the payload//from ww w . ja v a2 s .c om * @return the response * @throws IOException for IO errors while executing the request * @throws TransformerException for any transformation errors */ protected String invoke(String serviceURL, String original) throws IOException, TransformerException { URL url = new URL(serviceURL); HttpURLConnection rc = (HttpURLConnection) url.openConnection(); rc.setRequestMethod("POST"); rc.setDoOutput(true); rc.setDoInput(true); rc.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); System.out.println("before transform:" + original); String request = transform(requestXSLT, original); System.out.println("after transform:" + request); int len = request.length(); rc.setRequestProperty("Content-Length", Integer.toString(len)); rc.connect(); OutputStreamWriter out = new OutputStreamWriter(rc.getOutputStream()); out.write(request, 0, len); out.flush(); InputStreamReader read; try { read = new InputStreamReader(rc.getInputStream()); } catch (IOException e) { read = new InputStreamReader(rc.getErrorStream()); } try { String response = IOUtils.toString(read); System.out.println("actual result:" + response); String transformedResponse = transform(responseXSLT, response); System.out.println("transformed result:" + transformedResponse); return transformedResponse; } finally { read.close(); rc.disconnect(); } }
From source file:me.Aron.Heinecke.fbot.lib.Socket.java
/*** * Performs the login into fronter based on the DB credentials * Requires the tokens form getReqID//from w ww. j a va 2 s .co m * @return site content */ public synchronized String login() throws ClientProtocolException, IOException { String url = "https://fronter.com/giessen/index.phtml"; //create client & post HttpPost post = new HttpPost(url); // add header post.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); post.setHeader("Accept-Encoding", "gzip, deflate"); post.setHeader("Accept-Language", "de-de,de;q=0.8,en-us;q=0.5,en;q=0.3"); post.setHeader("Connection", "keep-alive"); post.setHeader("DNT", "1"); post.setHeader("Host", "fronter.com"); post.setHeader("Referer", "https://fronter.com/giessen/index.phtml"); post.setHeader("User-Agent", UA); // set login parameters & fake normal login data List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(); urlParameters.add(new BasicNameValuePair("SSO_COMMAND", "")); urlParameters.add(new BasicNameValuePair("SSO_COMMAND_SECHASH", fbot.getDB().getSSOCOM())); urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_HEIGH...", "1080")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_SCREEN_WIDTH", "1920")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_HEIGH...", "914")); urlParameters.add(new BasicNameValuePair("USER_INITIAL_WINDOW_WIDTH", "1920")); urlParameters.add(new BasicNameValuePair("USER_SCREEN_SIZE", "")); urlParameters.add(new BasicNameValuePair("chp", "")); urlParameters.add(new BasicNameValuePair("fronter_request_token", fbot.getDB().getReqtoken())); urlParameters.add(new BasicNameValuePair("mainurl", "main.phtml")); urlParameters.add(new BasicNameValuePair("newlang", "de")); urlParameters.add(new BasicNameValuePair("password", fbot.getDB().getPass())); urlParameters.add(new BasicNameValuePair("saveid", "-1")); urlParameters.add(new BasicNameValuePair("username", fbot.getDB().getUser())); //create gzip encoder UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(urlParameters); urlEncodedFormEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF_8")); post.setEntity(urlEncodedFormEntity); //Create own context which stores the cookies HttpClientContext context = HttpClientContext.create(); HttpResponse response = client.execute(post, context); if (fbot.isDebug()) { fbot.getLogger().debug("socket", "Sending POST request to URL: " + url); fbot.getLogger().debug("socket", "Response code: " + response.getStatusLine().getStatusCode()); fbot.getLogger().log("debug", "socket", context.getCookieStore().getCookies()); } // input-stream with gzip-accept InputStream input = response.getEntity().getContent(); InputStreamReader isr = new InputStreamReader(input); BufferedReader rd = new BufferedReader(isr); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } input.close(); isr.close(); rd.close(); fbot.getDB().setCookieStore(context.getCookieStore()); return result.toString(); }
From source file:livecanvas.mesheditor.MeshEditor.java
private void open(File file) { if (file == null) { FileDialog fd = new FileDialog(JOptionPane.getFrameForComponent(MeshEditor.this), "Load"); fd.setVisible(true);//from w w w. j a v a2 s .com String file_str = fd.getFile(); if (file_str == null) { return; } file = new File(fd.getDirectory() + "/" + file_str); } try { StringWriter out = new StringWriter(); InputStreamReader in = new InputStreamReader(new FileInputStream(file)); Utils.copy(in, out); in.close(); out.close(); clear(); JSONObject doc = new JSONObject(out.toString()); Layer rootLayer = Layer.fromJSON(doc.getJSONObject("rootLayer")); layersView.setRootLayer(rootLayer); rootLayer.setCanvas(canvas); for (Layer layer : rootLayer.getSubLayersRecursively()) { layer.setCanvas(canvas); } JSONObject canvasJSON = doc.optJSONObject("canvas"); if (canvasJSON != null) { canvas.fromJSON(canvasJSON); } canvas.setCurrLayer(rootLayer); } catch (Exception e1) { e1.printStackTrace(); String msg = "An error occurred while trying to load."; JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(MeshEditor.this), msg, "Error", JOptionPane.ERROR_MESSAGE); } repaint(); }
From source file:edu.ucla.cs.nopainnogame.WatchActivity.java
public void setFileData(String userName, String fileSuffix, String today, int value) { String filename = userName + fileSuffix; FileOutputStream fos;/* w w w. j a va 2s . c o m*/ InputStream is; int numBytes = 0; //String test = "";//for debugging try { is = openFileInput(filename); numBytes = is.available(); InputStreamReader ir = new InputStreamReader(is); char[] buf = new char[numBytes]; ir.read(buf); fos = openFileOutput(filename, Context.MODE_PRIVATE); String data = today + " " + value + "\n"; data = data + String.valueOf(buf); fos.write(data.getBytes()); //fos.write(test.getBytes());//for debugging fos.flush(); ir.close(); is.close(); fos.close(); } catch (FileNotFoundException fe) { System.err.println("Error: User file not found."); fe.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }