List of usage examples for java.io InputStreamReader read
public int read(char cbuf[], int offset, int length) throws IOException
From source file:org.pentaho.di.core.vfs.SftpFileSystemWindows.java
/** * * {@link org.apache.commons.vfs2.provider.sftp.SftpFileSystem#executeCommand(java.lang.String, java.lang.StringBuilder) } *//* ww w. j a v a 2 s . co m*/ private int executeCommand(String command, StringBuilder output) throws JSchException, IOException { this.ensureSession(); ChannelExec channel = (ChannelExec) this.session.openChannel("exec"); channel.setCommand(command); channel.setInputStream((InputStream) null); InputStreamReader stream = new InputStreamReader(channel.getInputStream()); channel.setErrStream(System.err, true); channel.connect(); char[] buffer = new char[128]; int read; while ((read = stream.read(buffer, 0, buffer.length)) >= 0) { output.append(buffer, 0, read); } stream.close(); while (!channel.isClosed()) { try { Thread.sleep(100L); } catch (Exception exc) { log.logMinimal("Warning: Error session closing. " + exc.getMessage()); } } channel.disconnect(); return channel.getExitStatus(); }
From source file:com.cloudbees.api.BeesClientBase.java
private String getResponseString(InputStream ins) throws IOException { StringBuffer response = new StringBuffer(); try {// www .j a v a 2s. c om InputStreamReader isr = new InputStreamReader(ins); char[] chars = new char[1024]; int numRead = isr.read(chars, 0, chars.length); while (numRead != -1) { response.append(new String(chars, 0, numRead)); numRead = isr.read(chars, 0, chars.length); } } finally { ins.close(); } return response.toString(); }
From source file:net.unicon.academus.spell.SpellCheckerServlet.java
private void printResource(PrintWriter out, String resource) throws IOException { InputStreamReader is = new InputStreamReader(ctx.getResourceAsStream(resource)); char[] buf = new char[4096]; int r = 0;// w ww. j av a 2 s . c om while ((r = is.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, r); } is.close(); out.flush(); }
From source file:org.andstatus.app.net.HttpConnectionBasic.java
/** * Retrieve the input stream from the HTTP connection. * /*from ww w . j av a 2 s . c o m*/ * @param httpEntity * @return String */ private String retrieveInputStream(HttpEntity httpEntity) { int length = (int) httpEntity.getContentLength(); if (length <= 0) { // Length is unknown or large length = 1024; } StringBuilder stringBuffer = new StringBuilder(length); InputStreamReader inputStreamReader = null; try { inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8); char[] buffer = new char[length]; int count; while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) { stringBuffer.append(buffer, 0, count); } } catch (UnsupportedEncodingException e) { MyLog.e(this, e); } catch (IllegalStateException e) { MyLog.e(this, e); } catch (IOException e) { MyLog.e(this, e); } finally { DbUtils.closeSilently(inputStreamReader); } return stringBuffer.toString(); }
From source file:org.akop.ararat.io.WSJFormatter.java
@Override public void read(Crossword.Builder builder, InputStream inputStream) throws IOException { InputStreamReader reader = new InputStreamReader(inputStream, mEncoding); StringBuilder sb = new StringBuilder(); int nread;/*from w w w.j a va 2 s . co m*/ char[] buffer = new char[4000]; while ((nread = reader.read(buffer, 0, buffer.length)) > -1) { sb.append(buffer, 0, nread); } JSONObject obj; try { obj = new JSONObject(sb.toString()); } catch (JSONException e) { throw new FormatException("Error parsing JSON object", e); } JSONObject dataObj = obj.optJSONObject("data"); if (dataObj == null) { throw new FormatException("Missing 'data'"); } JSONObject copyObj = dataObj.optJSONObject("copy"); if (copyObj == null) { throw new FormatException("Missing 'data.copy'"); } JSONObject gridObj = copyObj.optJSONObject("gridsize"); if (gridObj == null) { throw new FormatException("Missing 'data.copy.gridsize'"); } builder.setTitle(copyObj.optString("title")); builder.setDescription(copyObj.optString("description")); builder.setCopyright(copyObj.optString("publisher")); builder.setAuthor(copyObj.optString("byline")); String pubString = copyObj.optString("date-publish"); try { builder.setDate(PUBLISH_DATE_FORMAT.parse(pubString).getTime()); } catch (ParseException e) { throw new FormatException("Can't parse '" + pubString + "' as publish date"); } int width = gridObj.optInt("cols"); int height = gridObj.optInt("rows"); builder.setWidth(width); builder.setHeight(height); readClues(builder, copyObj, Grid.parseJSON(dataObj.optJSONArray("grid"), width, height)); }
From source file:net.fenyo.gnetwatch.actions.ActionGenericSrc.java
/** * Get data from the external source./*from w ww . j a v a 2 s . c om*/ * @param none. * @return void. * @throws IOException IO exception. * @throws InterruptedException exception. */ // Queue thread // supports any thread public void invoke() throws IOException, InterruptedException { if (isDisposed() == true) return; try { super.invoke(); if (TargetGroup.class.isInstance(getTarget())) { GenericQuerier querier; synchronized (getGUI().getSynchro()) { querier = (GenericQuerier) ((TargetGroup) getTarget()).getGenericQuerier().clone(); } getGUI().setStatus(getGUI().getConfig().getPattern("reading_file", querier.getFileName())); if (last_file_size == -1) { last_file_size = new File(querier.getFileName()).length(); return; } // lire le contenu du fichier int value = -10; int value1 = -10; int value2 = -10; int value3 = -10; int value4 = -10; int value5 = -10; int value6 = -10; int value7 = -10; int value8 = -10; int value9 = -10; int value10 = -10; String units = ""; boolean value_ok = false; final File file = new File(querier.getFileName()); final long new_file_size = file.length(); if (last_file_size == new_file_size) return; last_file_size = new_file_size; FileInputStream byte_stream = null; try { byte_stream = new FileInputStream(file); byte_stream.skip(Math.max(0, last_file_size - 300)); // we want each char having 1 byte length, so we choose US-ASCII character encoding final InputStreamReader char_stream = new InputStreamReader(byte_stream, "US-ASCII"); final char ctab[] = new char[300]; final int nchars = char_stream.read(ctab, 0, 300); if (nchars > 0) { Matcher match = Pattern.compile( "<([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([0-9-]*);([^>]*)>.*?$") .matcher(new String(ctab, 0, nchars)); if (match.find()) { value1 = new Integer(match.group(1)); value2 = new Integer(match.group(2)); value3 = new Integer(match.group(3)); value4 = new Integer(match.group(4)); value5 = new Integer(match.group(5)); value6 = new Integer(match.group(6)); value7 = new Integer(match.group(7)); value8 = new Integer(match.group(8)); value9 = new Integer(match.group(9)); value10 = new Integer(match.group(10)); units = match.group(11); value_ok = true; } else { match = Pattern.compile("([0-9]+).*?$").matcher(new String(ctab, 0, nchars)); if (match.find()) { value = new Integer(match.group(1)); value_ok = true; } } } } finally { if (byte_stream != null) byte_stream.close(); } synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(this); // pour le setDescription() => enlever qd la description ne sera plus persistente if (value_ok) { getTarget().addEvent(new EventGenericSrc(true, value, value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, units)); getGUI().setStatus(getGUI().getConfig().getPattern("new_file_value", GenericTools.formatNumericString(getGUI().getConfig(), new Integer(value < 0 ? value1 : value).toString()))); setDescription("" + GenericTools.formatNumericString(getGUI().getConfig(), new Integer(value < 0 ? value1 : value).toString()) + " " + querier.getUnit()); } else { // getTarget().addEvent(new EventGenericSrc(false)); getGUI().setStatus(getGUI().getConfig().getString("new_file_value_incorrect")); setDescription(getGUI().getConfig().getString("new_file_value_incorrect")); } session.getTransaction().commit(); } catch (final Exception ex) { log.error("Exception", ex); session.getTransaction().rollback(); } } } } } catch (final InterruptedException ex) { synchronized (getGUI().getSynchro()) { synchronized (getGUI().sync_tree) { final Session session = getGUI().getSynchro().getSessionFactory().getCurrentSession(); session.beginTransaction(); try { session.update(this); // pour le setDescription() => enlever qd la description ne sera plus persistente getTarget().addEvent(new EventGenericSrc(false)); // mettre un setstatus comme pour IPv4 // setDescription(getGUI().getConfig().getString("unreachable")); session.getTransaction().commit(); } catch (final Exception ex2) { log.error("Exception", ex2); session.getTransaction().rollback(); } } } throw ex; } }
From source file:com.xorcode.andtweet.net.ConnectionBasicAuth.java
/** * Retrieve the input stream from the HTTP connection. * /*from w w w . j ava2 s .c o m*/ * @param httpEntity * @return String */ private String retrieveInputStream(HttpEntity httpEntity) { int length = (int) httpEntity.getContentLength(); StringBuffer stringBuffer = new StringBuffer(length); try { InputStreamReader inputStreamReader = new InputStreamReader(httpEntity.getContent(), HTTP.UTF_8); char buffer[] = new char[length]; int count; while ((count = inputStreamReader.read(buffer, 0, length - 1)) > 0) { stringBuffer.append(buffer, 0, count); } } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } catch (IllegalStateException e) { Log.e(TAG, e.toString()); } catch (IOException e) { Log.e(TAG, e.toString()); } return stringBuffer.toString(); }
From source file:cn.dreampie.CoffeeCompiler.java
private String readSourceFrom(InputStream inputStream) { final InputStreamReader streamReader = new InputStreamReader(inputStream); try {/* w w w. j a v a2s . c o m*/ try { StringBuilder builder = new StringBuilder(BUFFER_SIZE); char[] buffer = new char[BUFFER_SIZE]; int numCharsRead = streamReader.read(buffer, BUFFER_OFFSET, BUFFER_SIZE); while (numCharsRead >= 0) { builder.append(buffer, BUFFER_OFFSET, numCharsRead); numCharsRead = streamReader.read(buffer, BUFFER_OFFSET, BUFFER_SIZE); } return builder.toString(); } finally { streamReader.close(); } } catch (IOException e) { throw new RuntimeException(e); } }
From source file:apps101.example.json.ItemListLoader.java
@Override public List<Item> loadInBackground() { InputStream inputStream = null; try {// w w w. j a v a 2s . c om URL url = new URL("http://d28rh4a8wq0iu5.cloudfront.net/androidapps101/example-data/shopping.txt"); inputStream = url.openStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8")); StringWriter stringWriter = new StringWriter(); char[] buffer = new char[8192]; // Yes this is an 'Unnecessary buffer' (=twice the memory movement) but Java Streams need an intermediate array // to bulk copy bytes& chars // Cant glue InputStreamReader directly to a StringWriter unless you want to move 1 char at a time :-( int count; while ((count = inputStreamReader.read(buffer, 0, buffer.length)) != -1) { stringWriter.write(buffer, 0, count); } JSONArray jsonArray = new JSONArray(stringWriter.toString()); List<Item> result = new ArrayList<Item>(); for (int i = 0; i < jsonArray.length(); i++) { Item item = new Item(jsonArray.getJSONObject(i)); result.add(item); } return result; } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (Exception ignored) { } } return null; }
From source file:XMLParser.java
/** * Lazily parses the given {@code reader}. The parsing can be terminated by * the {@link LazyHandler} {@code handler} at any point. *///from w w w .j av a 2s.com public static void parse(InputStreamReader reader, LazyHandler handler, boolean includeInnerText, int bufferSize) throws IOException { if (handler == null) throw new IllegalArgumentException("LazyHandler arg must not be null."); char[] cbuf = new char[bufferSize]; int offset = 0; int len = 0; int state = 0; int stateBeforeComment = 0; int mark = -1; int elwsMark = -1; int nsMark = -1; String attrName = null; String attrValue = null; boolean dq = true; boolean searchRoot = true; while ((len = reader.read(cbuf, offset, cbuf.length - offset)) != -1) { for (int i = 0; i < len; i++, offset++) { char c = cbuf[offset]; switch (c) { case '<': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --< comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case 0: state = STATE_EL_STARTING; mark = offset; continue; case STATE_EL_ENDED: case STATE_EL_STARTED: stateBeforeComment = state; state = STATE_EL_STARTING; mark = offset; continue; case STATE_EL_TEXT: stateBeforeComment = state; state = STATE_EL_STARTING; if (mark != -1 && includeInnerText) { handler.characters(cbuf, mark + 1, offset - mark - 1); } mark = offset; continue; } continue; case '>': switch (state) { case STATE_IGNORE: if (stateBeforeComment == 0) state = 0; continue; case STATE_EL_TEXT:// uncommented text case STATE_COMMENT_STARTED: continue; case STATE_CDATA_ENDING: state = STATE_CDATA_STARTED; continue; case STATE_EL_ENDING: state = STATE_EL_ENDED; if (!handler.endElement()) return; elwsMark = -1; continue; case STATE_EL_ATTR_NAME_START: case STATE_EL_STARTING: if (elwsMark == -1) { String name = null; String namespace = null; if (nsMark == -1) name = new String(cbuf, mark + 1, offset - mark - 1).trim(); else { namespace = new String(cbuf, mark + 1, nsMark - mark - 1).trim(); name = new String(cbuf, nsMark + 1, offset - nsMark - 1).trim(); } if (searchRoot) { if (!handler.rootElement(name, namespace)) return; searchRoot = false; } else if (!handler.startElement(name, namespace)) return; } nsMark = -1; elwsMark = -1; state = STATE_EL_STARTED; mark = -1; continue; case STATE_COMMENT_ENDING: state = stateBeforeComment; continue; case STATE_CDATA_ENDED: state = STATE_EL_TEXT; if (mark != -1 && includeInnerText) { handler.characters(cbuf, mark + 1, offset - 2 - mark - 1); } mark = offset; continue; } continue; case '/': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --/ comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_ATTR_NAME_START: mark = -1; state = STATE_EL_ENDING; continue; case STATE_EL_STARTED: state = STATE_EL_TEXT; mark = offset - 1; continue; case STATE_EL_STARTING: if (mark + 1 != offset) { String name = null; String namespace = null; if (nsMark == -1) name = new String(cbuf, mark + 1, offset - mark - 1).trim(); else { namespace = new String(cbuf, mark + 1, nsMark - mark - 1).trim(); name = new String(cbuf, nsMark + 1, offset - nsMark - 1).trim(); } if (searchRoot) { if (!handler.rootElement(name, namespace)) return; searchRoot = false; } else if (!handler.startElement(name, namespace)) return; } state = STATE_EL_ENDING; elwsMark = -1; nsMark = -1; mark = -1; continue; } continue; case ':': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --: comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_STARTING: if (nsMark != -1) throw new IOException("invalid xml."); nsMark = offset; continue; } continue; case '?': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --? comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_STARTING: // uncommented text if (stateBeforeComment == STATE_EL_TEXT) continue; state = STATE_COMMENT_STARTING; mark = -1; continue; } continue; case '!': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --! comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_STARTING: state = STATE_COMMENT_STARTING; mark = -1; continue; } continue; case '[': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --[ comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_COMMENT_STARTING: state = STATE_CDATA_STARTING; if (mark != -1 && includeInnerText) { handler.characters(cbuf, mark + 1, offset - 2 - mark - 1); } mark = -1; continue; case STATE_CDATA_STARTING: state = STATE_CDATA_STARTED; mark = offset; continue; } continue; case ']': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --[ comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_CDATA_STARTED: state = STATE_CDATA_ENDING; continue; case STATE_CDATA_ENDING: state = STATE_CDATA_ENDED; continue; } continue; case '-': switch (state) { case STATE_IGNORE: continue; case STATE_COMMENT_STARTING: state = STATE_COMMENT_DASH_START; continue; case STATE_COMMENT_DASH_START: state = STATE_COMMENT_STARTED; continue; case STATE_COMMENT_STARTED: state = STATE_COMMENT_DASH_END; continue; case STATE_COMMENT_DASH_END: state = STATE_COMMENT_ENDING; continue; case STATE_COMMENT_ENDING:// handle ---- text state = STATE_COMMENT_STARTED; continue; } continue; case '=': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --= comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_ATTR_NAME_START: state = STATE_EL_ATTR_VALUE_START; attrName = new String(cbuf, mark + 1, offset - mark - 1).trim(); mark = -1; continue; } continue; case '\'': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --' comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_ATTR_VALUE_START: dq = false; state = STATE_EL_ATTR_VALUE_END; mark = offset; continue; case STATE_EL_ATTR_VALUE_END: if (dq) continue; state = STATE_EL_STARTING; attrValue = new String(cbuf, mark + 1, offset - mark - 1).trim(); handler.attribute(attrName, attrValue); attrName = null; attrValue = null; mark = -1; continue; } continue; case '"': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_ENDING://handle --" comments state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_ATTR_VALUE_START: dq = true; state = STATE_EL_ATTR_VALUE_END; mark = offset; continue; case STATE_EL_ATTR_VALUE_END: if (!dq) continue; state = STATE_EL_STARTING; attrValue = new String(cbuf, mark + 1, offset - mark - 1).trim(); handler.attribute(attrName, attrValue); attrName = null; attrValue = null; mark = -1; continue; } continue; case ' ': case '\t': case '\r': case '\n': switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_EL_STARTING: state = STATE_EL_ATTR_NAME_START; if (elwsMark == -1) { String name = null; String namespace = null; if (nsMark == -1) name = new String(cbuf, mark + 1, offset - mark - 1).trim(); else { namespace = new String(cbuf, mark + 1, nsMark - mark - 1).trim(); name = new String(cbuf, nsMark + 1, offset - nsMark - 1).trim(); } if (searchRoot) { if (!handler.rootElement(name, namespace)) return; searchRoot = false; } else if (!handler.startElement(name, namespace)) return; } nsMark = -1; elwsMark = offset; mark = offset; continue; } continue; default: switch (state) { case STATE_COMMENT_STARTED: case STATE_IGNORE: continue; case STATE_COMMENT_DASH_END: case STATE_COMMENT_ENDING: state = STATE_COMMENT_STARTED; continue; case STATE_CDATA_ENDING: case STATE_CDATA_ENDED: state = STATE_CDATA_STARTED; continue; case STATE_EL_STARTED: state = STATE_EL_TEXT; if (includeInnerText) mark = offset - 1; continue; case STATE_COMMENT_STARTING: if (stateBeforeComment != 0) throw new IOException("invalid xml."); mark = -1; state = STATE_IGNORE; continue; case STATE_COMMENT_DASH_START: throw new IOException("invalid xml."); } continue; } } if (mark == -1) offset = 0; else { if (state == STATE_EL_TEXT || state == STATE_CDATA_STARTED) { if (includeInnerText) handler.characters(cbuf, mark + 1, offset - mark - 2); offset = 0; mark = -1; } else { // move to the front int copyLen = offset - mark; System.arraycopy(cbuf, mark, cbuf, 0, copyLen); offset = len; mark = 0; } } } }