List of usage examples for java.io InputStreamReader read
public int read() throws IOException
From source file:com.motorola.studio.android.utilities.TelnetFrameworkAndroid.java
/** * *//* w w w . j ava 2 s .com*/ public String waitFor(String[] waitForArray) throws IOException { InputStreamReader responseReader = null; StringBuffer answerFromRemoteHost = new StringBuffer(); try { responseReader = new InputStreamReader(telnetClient.getInputStream()); boolean found = false; do { char readChar = 0; long currentTime = System.currentTimeMillis(); long timeoutTime = currentTime + timeout; while (readChar == 0) { if (responseReader == null) { // responseReader can only be set to null if method // releaseTelnetInputStreamReader() // has been called, which should happen if host becomes // unavailable. throw new IOException("Telnet host is unavailable; stopped waiting for answer."); } if (responseReader.ready()) { readChar = (char) responseReader.read(); } else { try { Thread.sleep(50); } catch (InterruptedException e) { // Do nothing } } currentTime = System.currentTimeMillis(); if ((!responseReader.ready()) && (currentTime > timeoutTime)) { throw new IOException("A timeout has occured when trying to read the telnet stream"); } } answerFromRemoteHost.append(readChar); for (String aWaitFor : waitForArray) { found = answerFromRemoteHost.toString().contains(aWaitFor); } } while (!found); } finally { if (responseReader != null) { responseReader.close(); } } return answerFromRemoteHost.toString(); }
From source file:org.rssowl.core.internal.connection.DefaultProtocolHandler.java
private String getEncodingFromXML(InputStreamReader inputReader, IProgressMonitor monitor) throws IOException { String encoding = null;/*w ww . j a v a 2 s .c om*/ /* Read the first line or until the Tag is closed */ StringBuilder strBuf = new StringBuilder(); int c; while (!monitor.isCanceled() && (c = inputReader.read()) != -1) { char character = (char) c; /* Append all Characters, except for closing Tag or CR */ if (character != '>' && character != '\n' && character != '\r') strBuf.append(character); /* Closing Tag is the last one to append */ else if (character == '>') { strBuf.append(character); break; } /* End of Line or Tag reached */ else break; } /* Save the first Line */ String firstLine = strBuf.toString(); /* Look if Encoding is supplied */ if (firstLine.indexOf("encoding") >= 0) { //$NON-NLS-1$ /* Extract the Encoding Value */ String regEx = "<\\?.*encoding=[\"']([^\\s]*)[\"'].*\\?>"; //$NON-NLS-1$ Pattern pattern = Pattern.compile(regEx); Matcher match = pattern.matcher(firstLine); /* Get first matching String */ if (match.find()) return match.group(1); } return encoding; }
From source file:com.example.mahmoud.asynctask_and_network.NetWork.java
public String callURL(String myStringURL) { StringBuilder sb = new StringBuilder(); // String sb=""; // to convert String to URL URL url = null;//from ww w .ja va2 s. c o m //to open Connection with URL URLConnection urlConn = null; //to get InputStrem From Connection InputStreamReader in = null; // to connect inputStrem with bufferedReader BufferedReader bufferedReader = null; try { //1 convert String to URL url = new URL(myStringURL); //2 Open Connection urlConn = url.openConnection(); //3 check if there are newtork found or not if (urlConn != null && urlConn.getInputStream() != null) { // 4 if there are connectio found make connection opent for just 1 minute urlConn.setReadTimeout(60 * 1000); // 5 get inputStrem from connection with the default charset for URL in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset()); // 6 connect inputStrem with bufferedReader bufferedReader = new BufferedReader(in); // 7 Read Data from bufferReader while that we not arrived to final char (-1) String cp; /* while ((cp = bufferedReader.readLine()) != null) { sb.append( cp); // sb.a //sb+=""+((char) cp); }*/ int x; while ((x = in.read()) != -1) { sb.append((char) x); } bufferedReader.close(); } in.close(); } catch (Exception e) { } return sb.toString(); }
From source file:org.opendatakit.briefcase.util.ExportToCsv.java
private String getSubmissionValue(EncryptionInformation ei, TreeElement model, Element element) { // could not find element, return null if (element == null) { return null; }/*from www. j a va2 s . com*/ StringBuilder b = new StringBuilder(); int maxChildren = element.getChildCount(); for (int i = 0; i < maxChildren; i++) { if (element.getType(i) == Node.TEXT) { b.append(element.getText(i)); } } String rawElement = b.toString(); // Field-level encryption support -- experimental if (JavaRosaParserWrapper.isEncryptedField(model)) { InputStreamReader isr = null; try { Cipher c = ei.getCipher("field:" + model.getName(), model.getName()); isr = new InputStreamReader( new CipherInputStream(new ByteArrayInputStream(Base64.decodeBase64(rawElement)), c), "UTF-8"); b.setLength(0); int ch; while ((ch = isr.read()) != -1) { char theChar = (char) ch; b.append(theChar); } return b.toString(); } catch (IOException e) { e.printStackTrace(); log.severe(" element name: " + model.getName() + " exception: " + e.toString()); } catch (InvalidKeyException e) { e.printStackTrace(); log.severe(" element name: " + model.getName() + " exception: " + e.toString()); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); log.severe(" element name: " + model.getName() + " exception: " + e.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); log.severe(" element name: " + model.getName() + " exception: " + e.toString()); } catch (NoSuchPaddingException e) { e.printStackTrace(); log.severe(" element name: " + model.getName() + " exception: " + e.toString()); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { e.printStackTrace(); } } } } return rawElement; }
From source file:org.guvnor.m2repo.backend.server.GuvnorM2Repository.java
private String loadGAVFromJarInternal(final File file) { InputStream is = null;/*from w w w .ja va 2s .c o m*/ InputStreamReader isr = null; try { ZipFile zip = new ZipFile(file); for (Enumeration e = zip.entries(); e.hasMoreElements();) { ZipEntry entry = (ZipEntry) e.nextElement(); if (entry.getName().startsWith("META-INF/maven") && entry.getName().endsWith("pom.properties")) { is = zip.getInputStream(entry); isr = new InputStreamReader(is, "UTF-8"); StringBuilder sb = new StringBuilder(); for (int c = isr.read(); c != -1; c = isr.read()) { sb.append((char) c); } return sb.toString(); } } } catch (ZipException e) { log.error(e.getMessage()); } catch (IOException e) { log.error(e.getMessage()); } finally { if (isr != null) { try { isr.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } } return null; }
From source file:org.icefaces.samples.showcase.util.SourceCodeLoaderConnection.java
/** * Returns formatted source located in the cache, or adds to the cache and * returns the source found at sourceCodePath, removing oldest cached files * if MAX_CACHE_SIZE exceeded. * /*w w w .j a v a2s.c om*/ * Implementing the map interface method `get` to allow parameter passing * in EL versions prior to 2.0 * * @param sourceCodePathObj The String location of the source file relative * to the web application root. * @return The XHTML formatted source code or a stack trace if the URL * could not be UTF-8 encoded. */ public String get(Object sourceCodePathObj) { if (SOURCE_SERVLET_URL == null || MAX_CACHE_SIZE == null || !(sourceCodePathObj instanceof String)) { return null; } String sourceCodePath; // Try encoding sourceCodePathObj parameter, return a stack trace // instead of source if it fails. try { sourceCodePath = URLEncoder.encode((String) sourceCodePathObj, "UTF-8"); } catch (UnsupportedEncodingException e) { logger.severe("UTF-8 is not supported by this platform."); return ""; } CachedSource cs; // Only allow the cache to be accessed by a single user when being used // within one of these blocks. synchronized (cache) { // Search the cache for formatted source code from this path. If it is // found, update the formatted source code with the current timestamp // and return the cached source. if ((cs = (CachedSource) cache.get(sourceCodePath)) != null) { logger.finer("Source Cache Hit."); logger.finest("Hit: " + sourceCodePath); cs.timestamp = System.currentTimeMillis() / 1000; cache.put(cs.path, cs); return cs.source; } } logger.finer("Source Cache Miss."); logger.finest("Miss: " + sourceCodePath); URL servletUrl = null; InputStream inputStream = null; InputStreamReader inputReader = null; try { if (!IS_SECURE) { servletUrl = new URL(SOURCE_SERVLET_URL + sourceCodePath); inputStream = (InputStream) servletUrl.getContent(); } else { // don't use a connection, just access methods directly inputStream = SourceCodeLoaderServlet.getServlet().getSource((String) sourceCodePathObj); } brokenUrl = false; } catch (Exception e) { e.printStackTrace(); logger.severe( "Broken URL for the source code loader (" + SOURCE_SERVLET_URL + "), check your web.xml."); brokenUrl = true; } if (!brokenUrl) { try { // Set up streams and buffers for source servlet reading inputReader = new InputStreamReader(inputStream, "UTF-8"); StringBuilder buf = new StringBuilder(16384); // Read into stringBuilder until EOF int readChar; while ((readChar = inputReader.read()) != -1) { buf.append((char) readChar); } // Extract page content from <body> tag and fix nbsp for valid XHTML String ret = buf.indexOf(" ") != -1 ? buf.substring(buf.indexOf("<body>") + 6, buf.lastIndexOf("</body>")).replace(" ", " ") : buf.toString(); synchronized (cache) { // If cache is full, remove files until the newly loaded string // will fit and add it to the cache while ((ret.length() * 16) + cacheSize > MAX_CACHE_SIZE) { OrderedBidiMap iCache = cache.inverseOrderedBidiMap(); CachedSource c = (CachedSource) iCache.firstKey(); cache.remove(c.path); cacheSize -= c.source.length() * 16; logger.finer("Cache Oversized. Removing oldest file."); logger.finest("Removed: " + c.path); } cache.put(sourceCodePath, new CachedSource(sourceCodePath, ret)); cacheSize += ret.length() * 16; } // Return newly loaded and cached source return ret; } catch (MalformedURLException e) { logger.severe("Attempted to connect to malformed URL."); logger.severe("Likely either EL param or web.xml SOURCE_SERVLET_URL param is incorrectly set"); e.printStackTrace(); } catch (UnsupportedEncodingException e) { logger.severe("UTF-8 is not supported by this platform."); e.printStackTrace(); } catch (IOException e) { logger.severe("IOException raised while reading characters from Servlet response stream."); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception ignoredClose) { } } if (inputReader != null) { try { inputReader.close(); } catch (Exception ignoredClose) { } } } } return ""; }
From source file:org.wings.session.MultipartRequest.java
/** * Parses passed request and stores contained parameters. * * @throws IOException On unrecoverable parsing bugs due to old Tomcat version. *///from w ww . jav a 2 s. c o m protected void processRequest(HttpServletRequest req) throws IOException { String type = req.getContentType(); if (type == null || !type.toLowerCase().startsWith("multipart/form-data")) { urlencodedRequest = true; return; } urlencodedRequest = false; parameters = new HashMap<String, List>(); files = new HashMap<String, UploadedFile>(); for (Iterator iterator = req.getParameterMap().entrySet().iterator(); iterator.hasNext(); /**/) { Map.Entry entry = (Map.Entry) iterator.next(); parameters.put((String) entry.getKey(), new ArrayList(Arrays.asList((String[]) entry.getValue()))); } String boundaryToken = extractBoundaryToken(type); if (boundaryToken == null) { /* * this could happen due to a bug in Tomcat 3.2.2 in combination * with Opera. * Opera sends the boundary on a separate line, which is perfectly * correct regarding the way header may be constructed * (multiline headers). Alas, Tomcat fails to read the header in * the content type line and thus we cannot read it.. haven't * checked later versions of Tomcat, but upgrading is * definitly needed, since we cannot do anything about it here. * (JServ works fine, BTW.) (Henner) */ throw new IOException("Separation boundary was not specified (BUG in Tomcat 3.* with Opera?)"); } MultipartInputStream mimeStream = null; ByteArrayOutputStream headerByteArray; StringBuilder content = new StringBuilder(); HashMap headers = null; int currentByte = 0; int currentPos = 0; int currentTransformByte = 0; String currentParam = null; File uploadFile = null; OutputStream fileStream = null; boolean done; int last = -1; try { mimeStream = new MultipartInputStream(req.getInputStream(), req.getContentLength(), maxSize); while (currentByte != -1) { // Read MIME part header line done = false; headerByteArray = new ByteArrayOutputStream(); while ((currentByte = mimeStream.read()) != -1 && !done) { headerByteArray.write(currentByte); done = (last == '\n' && currentByte == '\r'); last = currentByte; } if (currentByte == -1) break; headers = parseHeader(headerByteArray.toString(req.getCharacterEncoding())); headerByteArray.reset(); currentParam = (String) headers.get("name"); if (headers.size() == 1) { // .. it's not a file byte[] bytes = new byte[req.getContentLength()]; currentPos = 0; while ((currentByte = mimeStream.read()) != -1) { bytes[currentPos] = (byte) currentByte; currentPos++; if (currentPos >= boundaryToken.length()) { int i; for (i = 0; i < boundaryToken.length(); i++) { if (boundaryToken .charAt(boundaryToken.length() - i - 1) != bytes[currentPos - i - 1]) { i = 0; break; } } if (i == boundaryToken.length()) { // end of part .. ByteArrayInputStream bais = new ByteArrayInputStream(bytes, 0, currentPos - boundaryToken.length() - 4); InputStreamReader ir; if (req.getCharacterEncoding() != null) // It's common behaviour of browsers to encode their form input in the character // encoding of the page, though they don't declare the used characterset explicetly // for backward compatibility. ir = new InputStreamReader(bais, req.getCharacterEncoding()); else ir = new InputStreamReader(bais); content.setLength(0); while ((currentTransformByte = ir.read()) != -1) { content.append((char) currentTransformByte); } putParameter(currentParam, content.toString()); break; } } } } else { // .. it's a file String filename = (String) headers.get("filename"); if (filename != null && filename.length() != 0) { // The filename may contain a full path. Cut to just the filename. int slash = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\')); if (slash > -1) { filename = filename.substring(slash + 1); } String name = (String) headers.get("name"); String contentType = (String) headers.get("content-type"); try { uploadFile = File.createTempFile("wings_uploaded", "tmp"); } catch (IOException e) { log.error("couldn't create temp file in '" + System.getProperty("java.io.tmpdir") + "' (CATALINA_TMPDIR set correctly?)", e); throw e; } UploadedFile upload = new UploadedFile(filename, contentType, uploadFile); fileStream = new FileOutputStream(uploadFile); fileStream = UploadFilterManager.createFilterInstance(name, fileStream); AccessibleByteArrayOutputStream byteArray = new AccessibleByteArrayOutputStream(); byte[] bytes = null; int blength = boundaryToken.length(); int i; while ((currentByte = mimeStream.read()) != -1) { byteArray.write(currentByte); for (i = 0; i < blength; i++) { if (boundaryToken.charAt(blength - i - 1) != byteArray.charAt(-i - 1)) { i = 0; if (byteArray.size() > 512 + blength + 2) byteArray.writeTo(fileStream, 512); break; } } if (i == blength) // end of part .. break; } bytes = byteArray.toByteArray(); fileStream.write(bytes, 0, bytes.length - blength - 4); fileStream.close(); files.put(name, upload); putParameter(name, upload.toString()); } else { // workaround for some netscape bug int i; int blength = boundaryToken.length(); while ((currentByte = mimeStream.read()) != -1) { content.append((char) currentByte); if (content.length() >= blength) { for (i = 0; i < blength; i++) { if (boundaryToken.charAt(blength - i - 1) != content .charAt(content.length() - i - 1)) { i = 0; break; } } if (i == blength) break; } } } } currentByte = mimeStream.read(); if (currentByte == '\r' && mimeStream.read() != '\n') log.error("No line return char? " + currentByte); if (currentByte == '-' && mimeStream.read() != '-') log.error("?? No clue " + currentByte); } } catch (IOException ex) { // cleanup and store the exception for notification of SFileChooser log.warn("upload", ex); if (uploadFile != null) uploadFile.delete(); setException(currentParam, ex); } finally { try { fileStream.close(); } catch (Exception ign) { } try { mimeStream.close(); } catch (Exception ign) { } } }
From source file:com.rhfung.P2PDictionary.DataConnection.java
/** * // www.j ava2s . co m * @param reader reader to get bytes from * @param arrayToFill initialized array to fill buffer */ private static byte[] ReadBytes(InputStreamReader reader, int length) { byte[] arrayToFill = new byte[length]; try { for (int i = 0; i < length; i++) { arrayToFill[i] = (byte) reader.read(); // ENSURE this is 8-bit non-UTF reading!!!! } } catch (IOException ex) { throw new RuntimeException("Unexpected IOException during ReadBytes"); } return arrayToFill; }
From source file:AddressBookMIDlet.java
/** * Create a RecordEnumeration from the network. * /*from w ww. jav a 2s . c o m*/ * Query a network service for addresses matching the specified criteria. * The base URL of the service has the query parameters appended. The * request is made and the contents parsed into a Vector which is used as * the basis of the RecordEnumeration. lastname the last name to search for * firstname the first name to search for sortorder the order in which to * sort 1 is by last name, 0 is by first name */ NetworkQuery(String firstname, String lastname, int sortorder) { HttpConnection c = null; int ch; InputStream is = null; InputStreamReader reader; String url; // Format the complete URL to request buffer.setLength(0); buffer.append(baseurl); buffer.append("?last="); buffer.append((lastname != null) ? lastname : empty); buffer.append("&first="); buffer.append((firstname != null) ? firstname : empty); buffer.append("&sort=" + sortorder); url = buffer.toString(); // Open the connection to the service try { c = open(url); results.removeAllElements(); /* * Open the InputStream and construct a reader to convert from bytes * to chars. */ is = c.openInputStream(); reader = new InputStreamReader(is); while (true) { int i = 0; fields[0] = empty; fields[1] = empty; fields[2] = empty; do { buffer.setLength(0); while ((ch = reader.read()) != -1 && (ch != ',') && (ch != '\n')) { if (ch == '\r') { continue; } buffer.append((char) ch); } if (ch == -1) { throw new EOFException(); } if (buffer.length() > 0) { if (i < fields.length) { fields[i++] = buffer.toString(); } } } while (ch != '\n'); if (fields[0].length() > 0) { results.addElement(SimpleRecord.createRecord(fields[0], fields[1], fields[2])); } } } catch (Exception e) { } finally { try { if (is != null) { is.close(); } if (c != null) { c.close(); } } catch (Exception e) { } } resultsEnumeration = results.elements(); }
From source file:de.innovationgate.utils.WGUtils.java
/** * Converts a base64-encoded string into bytes, then constructs a string * from these bytes and returns it/*w w w.ja v a2s. c om*/ * * @param base64 * base64-encoded information as string * @return The decoded string */ public static String base64toString(String base64) { try { byte[] data = Base64.decode(base64); InputStreamReader streamReader = new InputStreamReader(new ByteArrayInputStream(data)); int ch = -1; StringBuffer result = new StringBuffer(); for (ch = streamReader.read(); ch != -1; ch = streamReader.read()) { result.append((char) ch); } return result.toString(); } catch (Exception exc) { exc.printStackTrace(); return null; } }