List of usage examples for java.io BufferedReader read
public int read() throws IOException
From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java
/** * @param command// w w w. j ava2 s . c o m * @throws IOException * @throws InterruptedException */ private void executeCommand(String command) throws IOException, InterruptedException { log.info("Command command[" + command + "]"); ProcessBuilder processBuilder = new ProcessBuilder(command.split("\\s")); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); StringWriter output = new StringWriter(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); try { int ch; while ((ch = reader.read()) != -1) { output.write(ch); } } finally { reader.close(); } int result = process.waitFor(); log.info("Command returnCode[" + result + "] output[" + output.toString() + "]"); if (result != 0) { throw new IOException("Execute command Error command[" + command + "] returnCode[" + result + "] output[" + output.toString() + "]"); } }
From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java
@Test public void testRandomReadOnlyAccessInputStreamOpenAutocloseRead() throws Exception { final FileObject fo = openFileObject(TEST_FILENAME); final RandomAccessContent rac = openRandomAccessContent(fo, RandomAccessMode.READ); final BufferedReader reader = getBufferedReader(rac.getInputStream()); try {// ww w . ja v a2 s . com Thread.sleep(SLEEP_TIME); for (int i = 0; i < TEST_FILE_A_CHARS_NUMBER; i++) { assertTrue('a' == reader.read()); } } finally { rac.close(); } fo.close(); }
From source file:cz.urbangaming.galgs.GAlg.java
private void loadRubyMethodsToMenu(BufferedReader bufferedReader) throws IOException, InterruptedException { String line = null;/* w w w.j a v a 2s. co m*/ rubyMethods.clear(); Log.d(DEBUG_TAG, "I'm in loadRubyMethodsToMenu nad bufferedReader.read():" + bufferedReader.read()); while ((line = bufferedReader.readLine()) != null) { Matcher matcher = pattern.matcher(line); if (matcher.matches() && matcher.group(1) != null && matcher.group(1).length() <= MAX_METHOD_NAME_LENGTH) { Log.d(DEBUG_TAG, "Adding method " + matcher.group(1)); rubyMethods.put(matcher.group(1).hashCode(), matcher.group(1)); } else { Log.d(DEBUG_TAG, "Line [" + line + "] does not contain the expected method..."); } } bufferedReader.close(); }
From source file:net.dv8tion.jda.core.requests.Response.java
protected Response(final okhttp3.Response response, final int code, final String message, final long retryAfter, final Set<String> cfRays) { this.rawResponse = response; this.code = code; this.message = message; this.exception = null; this.retryAfter = retryAfter; this.cfRays = cfRays; if (response == null || response.body().contentLength() == 0) { this.object = null; return;//from ww w . ja va2 s.c o m } InputStream body = null; BufferedReader reader = null; try { body = Requester.getBody(response); // this doesn't add overhead as org.json would do that itself otherwise reader = new BufferedReader(new InputStreamReader(body)); char begin; // not sure if I really like this... but we somehow have to get if this is an object or an array int mark = 1; do { reader.mark(mark++); begin = (char) reader.read(); } while (Character.isWhitespace(begin)); reader.reset(); if (begin == '{') this.object = new JSONObject(new JSONTokener(reader)); else if (begin == '[') this.object = new JSONArray(new JSONTokener(reader)); else this.object = reader.lines().collect(Collectors.joining()); } catch (final Exception e) { throw new RuntimeException("An error occurred while parsing the response for a RestAction", e); } finally { try { body.close(); reader.close(); } catch (NullPointerException | IOException ignored) { } } }
From source file:com.geoservicesapi.services.LocationServices.java
/** * Get the address of a location using its geo-coordinates. * * @param lat/* w ww . j a v a 2 s .co m*/ * Latitude of the location. * @param lng * Longitude of the location. * @return The JSONObject associated with address from geo-coordinates. */ public JSONObject getAddress(String lat, String lng) { JSONObject result = new JSONObject(); if (lat == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "lat"); result.put("error", error); } else if (lng == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "lng"); result.put("error", error); } else if (lat.equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "lat"); result.put("error", error); } else if (lng.equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "lng"); result.put("error", error); } else { double latd = 0; boolean latProblem = false; try { latd = Double.parseDouble(lat); } catch (Exception e) { latProblem = true; } if (latProblem) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "lat"); result.put("error", error); } else { double lngd = 0; boolean lngProblem = false; try { lngd = Double.parseDouble(lng); } catch (Exception e) { lngProblem = true; } if (lngProblem) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "lng"); result.put("error", error); } else { String apiUrl = "http://open.mapquestapi.com/geocoding/v1/reverse?key=" + mapQuestApiKey + "&location=" + latd + "," + lngd; apiUrl = apiUrl.replaceAll(" ", "%20"); try { InputStream is = new URL(apiUrl).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String jsonText = sb.toString(); JSONObject res = new JSONObject(jsonText); JSONObject info = res.getJSONObject("info"); int statusCode = info.getInt("statuscode"); if (statusCode == 0) { JSONArray results = res.getJSONArray("results"); JSONObject resultObject = results.getJSONObject(0); JSONArray locations = resultObject.getJSONArray("locations"); JSONObject location = locations.getJSONObject(0); String street = "", city = "", state = "", country = "", postalCode = ""; try { street = location.getString("street"); } catch (Exception e) { } try { city = location.getString("adminArea5"); } catch (Exception e) { } try { state = location.getString("adminArea3"); } catch (Exception e) { } try { country = location.getString("adminArea1"); } catch (Exception e) { } try { postalCode = location.getString("postalCode"); } catch (Exception e) { } JSONObject address = new JSONObject(); address.put("street", street); address.put("city", city); address.put("state", state); address.put("country", country); address.put("postalCode", postalCode); result.put("address", address); JSONObject providedLocation = new JSONObject(); providedLocation.put("lat", lat); providedLocation.put("lng", lng); result.put("providedLocation", providedLocation); } } catch (Exception e) { JSONObject error = new JSONObject(); error.put("message", "Error processing request. Try again after some time"); result.put("error", error); } } } } return result; }
From source file:org.hibernate.spatial.testing.DataSourceUtils.java
/** * Parses the content of a file into an executable SQL statement. * * @param fileName name of a file containing SQL-statements * * @return/*from ww w. j a v a 2 s . co m*/ * * @throws IOException */ public String parseSqlIn(String fileName) throws IOException { InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (is == null) { throw new RuntimeException("File " + fileName + " not found on Classpath."); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringWriter sw = new StringWriter(); BufferedWriter writer = new BufferedWriter(sw); for (int c = reader.read(); c != -1; c = reader.read()) { writer.write(c); } writer.flush(); return sw.toString(); } finally { if (reader != null) { reader.close(); } is.close(); } }
From source file:com.geoservicesapi.services.DirectionsServices.java
/** * Get the mid point of a route from a source to a destination. * * @param source// w w w. j a va2 s .co m * A key string of the format (lat, lng). * @param destination * A key string of the format (lat, lng). * @return The JSONObject associated with the route. */ public JSONObject getMidpoint(String source, String destination) { JSONObject result = new JSONObject(); if (source == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (destination == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else if (!source.contains(",")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (!destination.contains(",")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else { String slat = "", slng = "", dlat = "", dlng = ""; String[] src = source.split(","); String[] dest = destination.split(","); if (!source.endsWith(",") && !source.startsWith(",")) { slat = src[0]; slng = src[1]; } if (!destination.endsWith(",") && !destination.startsWith(",")) { dlat = dest[0]; dlng = dest[1]; } if (slat.trim().equals("") || slng.trim().equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (dlat.trim().equals("") || dlng.trim().equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else { String apiUrl = "http://open.mapquestapi.com/directions/v2/route?unit=k&key=" + mapQuestApiKey + "&avoids=Toll%20road&from=" + slat + "," + slng + "&to=" + dlat + "," + dlng + "&routeType=fastest"; try { InputStream is = new URL(apiUrl).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String jsonText = sb.toString(); JSONObject res = new JSONObject(jsonText); JSONObject info = (JSONObject) res.getJSONObject("info"); int statusCode = info.getInt("statuscode"); if (statusCode == 0) { JSONObject route = (JSONObject) res.getJSONObject("route"); double distance = route.getDouble("distance"); double mid = distance / 2; JSONArray legs = (JSONArray) route.getJSONArray("legs"); JSONObject midpoint = new JSONObject(); if (legs.length() > 0) { JSONObject leg = (JSONObject) legs.get(0); JSONArray maneuvers = (JSONArray) leg.getJSONArray("maneuvers"); double startLat = 0, startLng = 0, endLat = 0, endLng = 0; double oldDistance = 0; double distanceTillNow = 0; int index = 0; for (; index < maneuvers.length() && distanceTillNow < mid; index++) { JSONObject maneuver = (JSONObject) maneuvers.get(index); double maneuverDistance = maneuver.getDouble("distance"); JSONObject startPoint = maneuver.getJSONObject("startPoint"); startLat = startPoint.getDouble("lat"); startLng = startPoint.getDouble("lng"); oldDistance = distanceTillNow; distanceTillNow += maneuverDistance; } JSONObject lastManeuver = new JSONObject(); if (index == maneuvers.length()) { lastManeuver = (JSONObject) maneuvers.get(index - 1); } else { lastManeuver = (JSONObject) maneuvers.get(index); } JSONObject endPoint = lastManeuver.getJSONObject("startPoint"); endLat = endPoint.getDouble("lat"); endLng = endPoint.getDouble("lng"); if (distanceTillNow < mid) { return null; } double m = (mid - oldDistance) / (distanceTillNow - oldDistance); double midLat = startLat + (endLat - startLat) * m; double midLng = startLng + (endLng - startLng) * m; midpoint.put("lat", midLat); midpoint.put("lng", midLng); } result.put("midway", midpoint); } } catch (Exception e) { JSONObject error = new JSONObject(); error.put("message", "Error processing request. Try again after some time"); result.put("error", error); } } } return result; }
From source file:truesculpt.ui.panels.WebFilePanel.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getManagers().getUtilsManager().updateFullscreenWindowStatus(getWindow()); setContentView(R.layout.webfile);//from w w w . j a v a 2 s. c om getManagers().getUsageStatisticsManager().TrackEvent("OpenFromWeb", "", 1); mWebView = (WebView) findViewById(R.id.webview); mWebView.setWebViewClient(new MyWebViewClient()); WebSettings webSettings = mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); mWebView.addJavascriptInterface(new JavaScriptInterface(this, getManagers()), "Android"); int nVersionCode = getManagers().getUpdateManager().getCurrentVersionCode(); mWebView.loadUrl(mStrBaseWebSite + "?version=" + nVersionCode); mPublishToWebBtn = (Button) findViewById(R.id.publish_to_web); mPublishToWebBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final String name = getManagers().getMeshManager().getName(); final File imagefile = new File(getManagers().getFileManager().GetImageFileName()); final File objectfile = new File(getManagers().getFileManager().GetObjectFileName()); getManagers().getUsageStatisticsManager().TrackEvent("PublishToWeb", name, 1); if (imagefile.exists() && objectfile.exists()) { try { final File zippedObject = File.createTempFile("object", "zip"); zippedObject.deleteOnExit(); BufferedReader in = new BufferedReader(new FileReader(objectfile)); BufferedOutputStream out = new BufferedOutputStream( new GZIPOutputStream(new FileOutputStream(zippedObject))); System.out.println("Compressing file"); int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); long size = 0; size = new FileInputStream(imagefile).getChannel().size(); size += new FileInputStream(zippedObject).getChannel().size(); size /= 1000; final SpannableString msg = new SpannableString( "You will upload your latest saved version of this scupture representing " + size + " ko of data\n\n" + "When clicking the yes button you accept to publish your sculpture under the terms of the creative commons share alike, non commercial license\n" + "http://creativecommons.org/licenses/by-nc-sa/3.0" + "\n\nDo you want to proceed ?"); Linkify.addLinks(msg, Linkify.ALL); AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this); builder.setMessage(msg).setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { PublishPicture(imagefile, zippedObject, name); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); AlertDialog dlg = builder.create(); dlg.show(); // Make the textview clickable. Must be called after // show() ((TextView) dlg.findViewById(android.R.id.message)) .setMovementMethod(LinkMovementMethod.getInstance()); } catch (Exception e) { e.printStackTrace(); } } else { AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this); builder.setMessage( "File has not been saved, you need to save it before publishing\nDo you want to proceed to save window ?") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { ((FileSelectorPanel) getParent()).getTabHost().setCurrentTab(2); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } } }); }
From source file:com.geoservicesapi.services.DirectionsServices.java
/** * Get the route from a source to a destination. * * @param source/*from w w w .j a va2 s . c om*/ * A key string of the format "lat, lng". * @param destination * A key string of the format "lat, lng". * @return The JSONObject associated with the route. */ public JSONObject getRoute(String source, String destination) { JSONObject result = new JSONObject(); if (source == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (destination == null) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are missing in request."); error.put("id", "MISSING_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else if (!source.contains(",")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (!destination.contains(",")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else { String slat = "", slng = "", dlat = "", dlng = ""; String[] src = source.split(","); String[] dest = destination.split(","); if (!source.endsWith(",") && !source.startsWith(",")) { slat = src[0]; slng = src[1]; } if (!destination.endsWith(",") && !destination.startsWith(",")) { dlat = dest[0]; dlng = dest[1]; } if (slat.trim().equals("") || slng.trim().equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "source"); result.put("error", error); } else if (dlat.trim().equals("") || dlng.trim().equals("")) { JSONObject error = new JSONObject(); error.put("message", "One or more parameters are invlid in request."); error.put("id", "INVALID_PARAMETER"); error.put("field", "destination"); result.put("error", error); } else { String apiUrl = "http://open.mapquestapi.com/directions/v2/route?key=" + mapQuestApiKey + "&avoids=Toll%20road&from=" + slat + "," + slng + "&to=" + dlat + "," + dlng + "&routeType=fastest"; try { InputStream is = new URL(apiUrl).openStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } String jsonText = sb.toString(); JSONObject res = new JSONObject(jsonText); JSONObject info = (JSONObject) res.getJSONObject("info"); int statusCode = info.getInt("statuscode"); if (statusCode == 0) { JSONObject route = (JSONObject) res.getJSONObject("route"); boolean hasTollRoad = route.getBoolean("hasTollRoad"); boolean hasCountryCross = route.getBoolean("hasCountryCross"); boolean hasFerry = route.getBoolean("hasFerry"); double distance = route.getDouble("distance"); double fuelUsed = route.getDouble("fuelUsed"); String formattedTime = route.getString("formattedTime"); JSONArray legs = (JSONArray) route.getJSONArray("legs"); JSONObject steps = new JSONObject(); steps.put("hasTollRoad", hasTollRoad); steps.put("hasCountryCross", hasCountryCross); steps.put("hasFerry", hasFerry); steps.put("distance", distance); steps.put("fuelUsed", fuelUsed); steps.put("formattedTime", formattedTime); if (legs.length() > 0) { JSONObject leg = (JSONObject) legs.get(0); JSONArray maneuvers = (JSONArray) leg.getJSONArray("maneuvers"); JSONArray directions = new JSONArray(); String[] turnTypes = { "straight", "slight right", "right", "sharp right", "reverse", "sharp left", "left", "slight left", "right u-turn", "left u-turn", "right merge", "left merge", "right on ramp", "left on ramp", "right off ramp", "left off ramp", "right fork", "left fork", "straight fork", "take transit", "transfer transit", "port transit", "enter transit", "exit transit" }; for (int i = 0; i < maneuvers.length(); i++) { JSONObject maneuver = (JSONObject) maneuvers.get(i); String narrative = maneuver.getString("narrative"); String url = ""; int turnType = maneuver.getInt("turnType"); String transportMode = maneuver.getString("transportMode"); if (i != maneuvers.length() - 1) { url = maneuver.getString("mapUrl"); } String iconUrl = maneuver.getString("iconUrl"); double dis = maneuver.getDouble("distance"); String time = maneuver.getString("formattedTime"); String directionName = ""; try { directionName = maneuver.getString("directionName"); } catch (Exception ignore) { } JSONObject man = new JSONObject(); man.put("narrative", narrative); man.put("url", url); man.put("distance", dis); man.put("time", time); if (turnType == -1) { man.put("turnType", "end"); } else { man.put("turnType", turnTypes[turnType]); } man.put("transportMode", transportMode); man.put("direction", directionName); man.put("iconUrl", iconUrl); directions.put(i, man); } steps.put("directions", directions); } result.put("route", steps); } } catch (Exception e) { JSONObject error = new JSONObject(); error.put("message", "Error processing request. Try again after some time"); result.put("error", error); } } } return result; }
From source file:fr.cobaltians.cobalt.Cobalt.java
private String readFileFromAssets(String file) { try {/*from w ww.j a va 2 s . c om*/ AssetManager assetManager = mContext.getAssets(); InputStream inputStream = assetManager.open(file); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder fileContent = new StringBuilder(); int character; while ((character = bufferedReader.read()) != -1) { fileContent.append((char) character); } return fileContent.toString(); } catch (FileNotFoundException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - readFileFromAssets: " + file + "not found."); } catch (IOException exception) { if (Cobalt.DEBUG) Log.e(Cobalt.TAG, TAG + " - readFileFromAssets: IOException"); exception.printStackTrace(); } return ""; }