List of usage examples for java.io BufferedReader read
public int read() throws IOException
From source file:com.google.android.apps.mytracks.TrackListActivity.java
private void checkPriorExceptions(boolean firstTime) { final File file = new File(FileUtils.buildExternalDirectoryPath("error.log")); if (file != null && file.exists() && file.length() > 0) { String msg = getString(R.string.previous_run_crashed); Builder builder = new AlertDialog.Builder(TrackListActivity.this); // User says no builder.setMessage(msg).setNeutralButton(getString(R.string.donot_send_report), new DialogInterface.OnClickListener() { @Override//from w w w .ja v a 2 s . c o m public void onClick(DialogInterface dialog, int which) { // Delete Exceptions File when user presses Ignore if (!file.delete()) Toast.makeText(getApplicationContext(), "Exceptions file not deleted", Toast.LENGTH_LONG).show(); } }); // User says yes builder.setPositiveButton(R.string.send_report, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_EMAIL, new String[] { Constants.BUGS_MAIL }); //$NON-NLS-1$ intent.setType("vnd.android.cursor.dir/email"); //$NON-NLS-1$ intent.putExtra(Intent.EXTRA_SUBJECT, "nogago Tracks bug"); //$NON-NLS-1$ StringBuilder text = new StringBuilder(); text.append("\nDevice : ").append(Build.DEVICE); //$NON-NLS-1$ text.append("\nBrand : ").append(Build.BRAND); //$NON-NLS-1$ text.append("\nModel : ").append(Build.MODEL); //$NON-NLS-1$ text.append("\nProduct : ").append("Tracks"); //$NON-NLS-1$ text.append("\nBuild : ").append(Build.DISPLAY); //$NON-NLS-1$ text.append("\nVersion : ").append(Build.VERSION.RELEASE); //$NON-NLS-1$ text.append("\nApp Starts : ").append(EulaUtils.getAppStart(TrackListActivity.this)); //$NON-NLS-1$ try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); if (info != null) { text.append("\nApk Version : ").append(info.versionName).append(" ") //$NON-NLS-1$//$NON-NLS-2$ .append(info.versionCode); } } catch (NameNotFoundException e) { } try { FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String line; while (br.read() != -1) { if ((line = br.readLine()) != null) { text.append(line); } } br.close(); fr.close(); } catch (IOException e) { Toast.makeText(getApplicationContext(), "Error reading exceptions file!", Toast.LENGTH_LONG) .show(); } intent.putExtra(Intent.EXTRA_TEXT, text.toString()); startActivity(Intent.createChooser(intent, getString(R.string.send_report))); if (!file.delete()) Toast.makeText(getApplicationContext(), "Exceptions file not deleted", Toast.LENGTH_LONG) .show(); } }); builder.show(); } }
From source file:com.villemos.ispace.testclient.TestClientConsumer.java
public void start() throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); boolean exit = false; while (exit == false) { System.out.println("Main"); System.out.println("1. Create new IO."); System.out.println("2. Search."); System.out.println("3. Autocomplete."); System.out.println("4. Print overview."); System.out.println("5. Print one."); System.out.println("6. Print all."); System.out.println("e. Exit."); System.out.print("Choice:"); String command = br.readLine(); if (command.equals("1")) { createInformationObject(br); } else if (command.equals("2")) { performSearch(br);// w w w. j a v a 2 s . com System.out.println("Results will arrive in a second... Press any key to continue..."); int t = br.read(); } else if (command.equals("3")) { autocomplete(br); System.out.println("Results will arrive in a second... Press any key to continue..."); int t = br.read(); } else if (command.equals("4")) { ((TestClientEndpoint) getEndpoint()).getPrinter().printOverview(); } else if (command.equals("5")) { System.out.print("Index:"); int index = Integer.parseInt(br.readLine()); ((TestClientEndpoint) getEndpoint()).getPrinter().printObjectDetails(index); } else if (command.equals("6")) { ((TestClientEndpoint) getEndpoint()).getPrinter().printAllObjectDetail(); } else if (command.equals("e")) { exit = true; } else { System.out.println("Command not recognized."); } } }
From source file:org.infoscoop.request.ProxyRequest.java
public String getResponseBodyAsString(String charset) throws IOException { if (responseBody == null) return null; BufferedReader reader = new BufferedReader(new InputStreamReader(responseBody, charset)); StringBuffer buf = new StringBuffer(); int c;/*from w ww .j a v a 2 s .c om*/ while ((c = reader.read()) > 0) buf.append((char) c); return buf.toString(); }
From source file:com.connectsdk.service.netcast.NetcastHttpServer.java
public void start() { //TODO: this method is too complex and should be refactored if (running)/*from ww w . j av a 2 s.c o m*/ return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d(Util.T, "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.println(); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d(Util.T, "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d(Util.T, "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; bEnabled = enabled.equalsIgnoreCase("true"); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:com.connectsdk.device.netcast.NetcastHttpServer.java
public void start() { if (running)//from ww w . ja v a 2 s . c om return; running = true; try { welcomeSocket = new ServerSocket(this.port); } catch (IOException ex) { ex.printStackTrace(); } while (running) { if (welcomeSocket == null || welcomeSocket.isClosed()) { stop(); break; } Socket connectionSocket = null; BufferedReader inFromClient = null; DataOutputStream outToClient = null; try { connectionSocket = welcomeSocket.accept(); } catch (IOException ex) { ex.printStackTrace(); // this socket may have been closed, so we'll stop stop(); return; } String str = null; int c; StringBuilder sb = new StringBuilder(); try { inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); while ((str = inFromClient.readLine()) != null) { if (str.equals("")) { break; } } while ((c = inFromClient.read()) != -1) { sb.append((char) c); String temp = sb.toString(); if (temp.endsWith("</envelope>")) break; } } catch (IOException ex) { ex.printStackTrace(); } String body = sb.toString(); Log.d("Connect SDK", "got message body: " + body); Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String date = dateFormat.format(calendar.getTime()); String androidOSVersion = android.os.Build.VERSION.RELEASE; PrintWriter out = null; try { outToClient = new DataOutputStream(connectionSocket.getOutputStream()); out = new PrintWriter(outToClient); out.println("HTTP/1.1 200 OK"); out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1"); out.println("Cache-Control: no-store, no-cache, must-revalidate"); out.println("Date: " + date); out.println("Connection: Close"); out.println("Content-Length: 0"); out.flush(); } catch (IOException ex) { ex.printStackTrace(); } finally { try { inFromClient.close(); out.close(); outToClient.close(); connectionSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); InputStream stream = null; try { stream = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser(); SAXParser saxParser; try { saxParser = saxParserFactory.newSAXParser(); saxParser.parse(stream, handler); } catch (IOException ex) { ex.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } if (body.contains("ChannelChanged")) { ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject()); Log.d("Connect SDK", "Channel Changed: " + channel.getNumber()); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, channel); } } } } else if (body.contains("KeyboardVisible")) { boolean focused = false; TextInputStatusInfo keyboard = new TextInputStatusInfo(); keyboard.setRawData(handler.getJSONObject()); try { JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget"); focused = (Boolean) currentWidget.get("focus"); keyboard.setFocused(focused); } catch (JSONException e) { e.printStackTrace(); } Log.d("Connect SDK", "KeyboardFocused?: " + focused); for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, keyboard); } } } } else if (body.contains("TextEdited")) { System.out.println("TextEdited"); String newValue = ""; try { newValue = handler.getJSONObject().getString("value"); } catch (JSONException ex) { ex.printStackTrace(); } Util.postSuccess(textChangedListener, newValue); } else if (body.contains("3DMode")) { try { String enabled = (String) handler.getJSONObject().get("value"); boolean bEnabled; if (enabled.equalsIgnoreCase("true")) bEnabled = true; else bEnabled = false; for (URLServiceSubscription<?> sub : subscriptions) { if (sub.getTarget().equalsIgnoreCase("3DMode")) { for (int i = 0; i < sub.getListeners().size(); i++) { @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners() .get(i); Util.postSuccess(listener, bEnabled); } } } } catch (JSONException e) { e.printStackTrace(); } } } }
From source file:org.apache.jmeter.services.FileServer.java
private BufferedReader getReader(String alias, boolean recycle, boolean firstLineIsNames) throws IOException { FileEntry fileEntry = files.get(alias); if (fileEntry != null) { BufferedReader reader; if (fileEntry.inputOutputObject == null) { reader = createBufferedReader(fileEntry); fileEntry.inputOutputObject = reader; if (firstLineIsNames) { // read first line and forget reader.readLine();/*from w w w. j a v a 2s . co m*/ } } else if (!(fileEntry.inputOutputObject instanceof Reader)) { throw new IOException("File " + alias + " already in use"); } else { reader = (BufferedReader) fileEntry.inputOutputObject; if (recycle) { // need to check if we are at EOF already reader.mark(1); int peek = reader.read(); if (peek == -1) { // already at EOF reader.close(); reader = createBufferedReader(fileEntry); fileEntry.inputOutputObject = reader; if (firstLineIsNames) { // read first line and forget reader.readLine(); } } else { // OK, we still have some data, restore it reader.reset(); } } } return reader; } else { throw new IOException("File never reserved: " + alias); } }
From source file:org.dita.dost.util.ConvertLang.java
private void convertEntityAndCharset(final File inputFile, final String format) { final String fileName = inputFile.getAbsolutePath(); final File outputFile = new File(fileName + FILE_EXTENSION_TEMP); BufferedReader reader = null; BufferedWriter writer = null; try {//from www .j a v a 2s .co m //prepare for the input and output final FileInputStream inputStream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(inputStream, UTF8); //wrapped into reader reader = new BufferedReader(streamReader); final FileOutputStream outputStream = new FileOutputStream(outputFile); //get new charset final String charset = charsetMap.get(format); //convert charset final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset); //wrapped into writer writer = new BufferedWriter(streamWriter); //read a character int charCode = reader.read(); while (charCode != -1) { final String key = String.valueOf(charCode); //Is an entity char if (entityMap.containsKey(key)) { //get related entity final String value = entityMap.get(key); //write entity into output file writer.write(value); } else { //normal process writer.write(charCode); } charCode = reader.read(); } } catch (final FileNotFoundException e) { logger.error(e.getMessage(), e); } catch (final IOException e) { logger.error(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage()); } } if (writer != null) { try { writer.close(); } catch (final IOException e) { logger.error("Failed to close output stream: " + e.getMessage()); } } } try { deleteQuietly(inputFile); moveFile(outputFile, inputFile); } catch (final Exception e) { logger.error("Failed to replace " + inputFile + ": " + e.getMessage()); } }
From source file:org.dita.dost.ant.ConvertLang.java
private void convertEntityAndCharset(final File inputFile, final String format) { final String fileName = inputFile.getAbsolutePath(); final File outputFile = new File(fileName + FILE_EXTENSION_TEMP); BufferedReader reader = null; BufferedWriter writer = null; try {// w ww. java 2 s .co m //prepare for the input and output final FileInputStream inputStream = new FileInputStream(inputFile); final InputStreamReader streamReader = new InputStreamReader(inputStream, UTF8); //wrapped into reader reader = new BufferedReader(streamReader); final FileOutputStream outputStream = new FileOutputStream(outputFile); //get new charset final String charset = charsetMap.get(format); //convert charset final OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, charset); //wrapped into writer writer = new BufferedWriter(streamWriter); updateExceptionCharacters(charset); //read a character int charCode = reader.read(); while (charCode != -1) { final String key = String.valueOf(charCode); //Is an entity char if (entityMap.containsKey(key) && !entityExceptionSet.contains(charCode)) { //get related entity final String value = entityMap.get(key); //write entity into output file writer.write(value); } else { //normal process writer.write(charCode); } charCode = reader.read(); } } catch (final IOException e) { logger.error(e.getMessage(), e); } finally { if (reader != null) { try { reader.close(); } catch (final IOException e) { logger.error("Failed to close input stream: " + e.getMessage()); } } if (writer != null) { try { writer.close(); } catch (final IOException e) { logger.error("Failed to close output stream: " + e.getMessage()); } } } try { deleteQuietly(inputFile); moveFile(outputFile, inputFile); } catch (final Exception e) { logger.error("Failed to replace " + inputFile + ": " + e.getMessage()); } }
From source file:com.servoy.j2db.util.Utils.java
public static String getURLContent(URL url) { StringBuffer sb = new StringBuffer(); String charset = null;/* w ww . jav a2 s .c o m*/ try { URLConnection connection = url.openConnection(); InputStream is = connection.getInputStream(); final String type = connection.getContentType(); if (type != null) { final String[] parts = type.split(";"); for (int i = 1; i < parts.length && charset == null; i++) { final String t = parts[i].trim(); final int index = t.toLowerCase().indexOf("charset="); if (index != -1) charset = t.substring(index + 8); } } InputStreamReader isr = null; if (charset != null) isr = new InputStreamReader(is, charset); else isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); int read = 0; while ((read = br.read()) != -1) { sb.append((char) read); } br.close(); isr.close(); is.close(); } catch (Exception e) { Debug.error(e); } return sb.toString(); }
From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java
/** * @param cmdWithArguments//from w w w . j ava2s. co m * @param wd * @return */ private String execCmd(File wd, String[] cmdWithArguments) { log.debug("executing command: " + Arrays.toString(cmdWithArguments)); StringBuffer out = new StringBuffer(); try { Process p = (wd != null) ? Runtime.getRuntime().exec(cmdWithArguments, null, wd) : Runtime.getRuntime().exec(cmdWithArguments); out.append("Normal cmd output:\n"); Reader reader = new InputStreamReader(p.getInputStream()); BufferedReader input = new BufferedReader(reader); int readChar = 0; while ((readChar = input.read()) != -1) { out.append((char) readChar); } input.close(); reader.close(); out.append("ErrorStream cmd output:\n"); reader = new InputStreamReader(p.getErrorStream()); input = new BufferedReader(reader); readChar = 0; while ((readChar = input.read()) != -1) { out.append((char) readChar); } input.close(); reader.close(); Integer exitValue = p.waitFor(); log.debug("Process exit value: " + exitValue); } catch (Exception e) { log.error("Error while executing command: '" + cmdWithArguments + "'", e); } log.debug("execCmd output: \n" + out.toString()); return out.toString(); }