List of usage examples for java.io BufferedReader read
public int read(java.nio.CharBuffer target) throws IOException
From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java
protected CharArrayReader getArrayReader(Reader reader, long size) throws IOException { char[] buf = new char[8192]; CharArrayWriter bufWriter = new CharArrayWriter((size > 0) ? (int) size : 8192); BufferedReader bufReader = new BufferedReader(reader, 8192); for (int read = bufReader.read(buf); read > 0; read = bufReader.read(buf)) { bufWriter.write(buf, 0, read);//from w w w . j a va2 s. co m } bufWriter.flush(); return new CharArrayReader(bufWriter.toCharArray()); }
From source file:nz.co.gregs.dbvolution.datatypes.DBJavaObject.java
@SuppressWarnings("unchecked") private O getFromCharacterReader(ResultSet resultSet, String fullColumnName) throws SQLException, IOException { O obj = null;//from w w w. j a v a2 s . c o m Reader inputReader = null; try { inputReader = resultSet.getCharacterStream(fullColumnName); } catch (NullPointerException nullEx) { ;// NullPointerException is thrown by a SQLite-JDBC bug sometimes. } if (inputReader != null) { if (resultSet.wasNull()) { this.setToNull(); } else { BufferedReader input = new BufferedReader(inputReader); try { List<byte[]> byteArrays = new ArrayList<byte[]>(); int totalBytesRead = 0; try { char[] resultSetBytes; resultSetBytes = new char[100000]; int bytesRead = input.read(resultSetBytes); while (bytesRead > 0) { totalBytesRead += bytesRead; byteArrays.add(String.valueOf(resultSetBytes).getBytes()); resultSetBytes = new char[100000]; bytesRead = input.read(resultSetBytes); } } catch (IOException ex) { Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex); } byte[] bytes = new byte[totalBytesRead]; int bytesAdded = 0; for (byte[] someBytes : byteArrays) { System.arraycopy(someBytes, 0, bytes, bytesAdded, Math.min(someBytes.length, bytes.length - bytesAdded)); bytesAdded += someBytes.length; } byte[] decodeBuffer = Base64.decodeBase64(bytes); ObjectInputStream decodedInput = new ObjectInputStream(new ByteArrayInputStream(decodeBuffer)); try { // this.setValue(decodedInput.readObject()); obj = (O) decodedInput.readObject(); } catch (ClassNotFoundException ex) { Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex); } } finally { input.close(); } } } return obj; }
From source file:nz.co.gregs.dbvolution.datatypes.DBJavaObject.java
@SuppressWarnings("unchecked") private O getFromCLOB(ResultSet resultSet, String fullColumnName) throws SQLException { O returnValue = null;//from w w w . j a va2 s. c o m Clob clob = resultSet.getClob(fullColumnName); if (resultSet.wasNull() || clob == null) { this.setToNull(); } else { try { BufferedReader input = new BufferedReader(clob.getCharacterStream()); try { List<byte[]> byteArrays = new ArrayList<byte[]>(); int totalBytesRead = 0; try { char[] resultSetBytes; resultSetBytes = new char[100000]; int bytesRead = input.read(resultSetBytes); while (bytesRead > 0) { totalBytesRead += bytesRead; byteArrays.add(String.valueOf(resultSetBytes).getBytes()); resultSetBytes = new char[100000]; bytesRead = input.read(resultSetBytes); } } catch (IOException ex) { Logger.getLogger(DBByteArray.class.getName()).log(Level.SEVERE, null, ex); } byte[] bytes = new byte[totalBytesRead]; int bytesAdded = 0; for (byte[] someBytes : byteArrays) { System.arraycopy(someBytes, 0, bytes, bytesAdded, Math.min(someBytes.length, bytes.length - bytesAdded)); bytesAdded += someBytes.length; } ObjectInputStream objectInput = new ObjectInputStream(new ByteArrayInputStream(bytes)); // this.setValue(objectInput.readObject()); returnValue = (O) objectInput.readObject(); } finally { input.close(); } } catch (IOException ex) { Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DBJavaObject.class.getName()).log(Level.SEVERE, null, ex); } } return returnValue; }
From source file:it.gmariotti.android.examples.googleaccount.SmsRestoreGDriveActivity.java
private String getContentFile(File file) { String result;/*from w w w . j a v a 2s . c o m*/ if (file != null && file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) { try { GenericUrl downloadUrl = new GenericUrl(file.getDownloadUrl()); HttpResponse resp = mService.getRequestFactory().buildGetRequest(downloadUrl).execute(); InputStream inputStream = null; try { inputStream = resp.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); char[] buffer = new char[1024]; int num; while ((num = reader.read(buffer)) > 0) { content.append(buffer, 0, num); } result = content.toString(); } finally { if (inputStream != null) { inputStream.close(); } } } catch (IOException e) { // An error occurred. e.printStackTrace(); return null; } } else { // The file doesn't have any content stored on Drive. return null; } return result; }
From source file:com.nginious.http.serialize.JsonDeserializer.java
/** * Deserializes a bean from the JSON body content in the specified HTTP request. * /*w w w . ja v a 2 s . com*/ * @param request the HTTP request * @return the deserialized bean * @throws SerializerException if unable to deserialize bean */ public E deserialize(HttpRequest request) throws SerializerException { if (request.getContentLength() == 0) { return null; } try { BufferedReader reader = request.getReader(); StringBuffer jsonText = new StringBuffer(); char[] buf = new char[1024]; int len = 0; while ((len = reader.read(buf)) > 0) { jsonText.append(buf, 0, len); } JSONObject object = new JSONObject(jsonText.toString()); if (!object.has(this.name)) { throw new SerializerException("Can't find object " + this.name + " in JSON data"); } object = object.getJSONObject(this.name); return deserialize(object); } catch (JSONException e) { throw new SerializerException("Can't deserialize object", e); } catch (IOException e) { throw new SerializerException("Can't deserialize object", e); } }
From source file:com.google.nigori.server.NigoriServlet.java
private String getJsonAsString(HttpServletRequest req, int maxLength) throws ServletException { if (maxLength != 0 && req.getContentLength() > maxLength) { return null; }//from w ww .j a v a2 s.c o m String charsetName = req.getCharacterEncoding(); if (charsetName == null) { charsetName = MessageLibrary.CHARSET; } try { BufferedReader in = new BufferedReader(new InputStreamReader(req.getInputStream(), charsetName)); StringBuilder json = new StringBuilder(); char[] buffer = new char[64 * 1024]; int charsRemaining = maxJsonQueryLength; int charsRead; while ((charsRead = in.read(buffer)) != -1) { charsRemaining -= charsRead; if (charsRemaining < 0) { throw new ServletException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Json request exceeds server maximum length of " + maxLength); } json.append(buffer, 0, charsRead); } return json.toString(); } catch (IOException ioe) { throw new ServletException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal error receiving data from client."); } }
From source file:com.anuta.internal.YangHelperMojo.java
/** * Read the given file and return the content as a string. * * @param file//from w ww . j av a 2 s . c o m * @return * @throws java.io.IOException */ private String readFileAsString(File file) throws java.io.IOException { StringBuilder fileData = new StringBuilder(1000); BufferedReader reader = null; try { reader = new BufferedReader(ReaderFactory.newReader(file, encoding)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } } finally { IOUtil.close(reader); } return fileData.toString(); }
From source file:org.archive.io.GenericReplayCharSequence.java
/** * Converts the first <code>Integer.MAX_VALUE</code> characters from the * file <code>backingFilename</code> from encoding <code>encoding</code> to * encoding <code>WRITE_ENCODING</code> and saves as * <code>this.decodedFile</code>, which is named <code>backingFilename * + "." + WRITE_ENCODING</code>./*from w ww. jav a2 s . co m*/ * * @throws IOException */ protected void decode(InputStream inStream, int prefixMax, String backingFilename, Charset charset) throws IOException { this.charset = charset; // TODO: consider if BufferedReader is helping any // TODO: consider adding TBW 'LimitReader' to stop reading at // Integer.MAX_VALUE characters because of charAt(int) limit BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, charset)); logger.fine("backingFilename=" + backingFilename + " encoding=" + charset + " decodedFile=" + decodedFile); this.prefixBuffer = CharBuffer.allocate(prefixMax); long count = 0; while (count < prefixMax) { int read = reader.read(prefixBuffer); if (read < 0) { break; } count += read; } int ch = reader.read(); if (ch >= 0) { count++; // more to decode to file overflow this.decodedFile = new File(backingFilename + "." + WRITE_ENCODING); FileOutputStream fos; try { fos = new FileOutputStream(this.decodedFile); } catch (FileNotFoundException e) { // Windows workaround attempt System.gc(); System.runFinalization(); this.decodedFile = new File(decodedFile.getAbsolutePath() + ".win"); logger.info("Windows 'file with a user-mapped section open' " + "workaround gc/finalization/name-extension performed."); // try again fos = new FileOutputStream(this.decodedFile); } Writer writer = new OutputStreamWriter(fos, WRITE_ENCODING); writer.write(ch); count += IOUtils.copyLarge(reader, writer); writer.close(); reader.close(); } this.length = Ints.saturatedCast(count); if (count > Integer.MAX_VALUE) { logger.warning("input stream is longer than Integer.MAX_VALUE=" + NumberFormat.getInstance().format(Integer.MAX_VALUE) + " characters -- only first " + NumberFormat.getInstance().format(Integer.MAX_VALUE) + " are accessible through this GenericReplayCharSequence"); } logger.fine("decode: decoded " + count + " characters" + ((decodedFile == null) ? "" : " (" + (count - prefixBuffer.length()) + " to " + decodedFile + ")")); }
From source file:com.panet.imeta.job.entries.dtdvalidator.JobEntryDTDValidator.java
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) { LogWriter log = LogWriter.getInstance(); Result result = previousResult; result.setResult(false);//from w w w. j av a2 s .c o m String realxmlfilename = getRealxmlfilename(); String realDTDfilename = getRealDTDfilename(); FileObject xmlfile = null; FileObject DTDfile = null; try { if (xmlfilename != null && ((dtdfilename != null && !dtdintern) || (dtdintern))) { xmlfile = KettleVFS.getFileObject(realxmlfilename); if (xmlfile.exists()) { //URL xmlFile = new URL (KettleVFS.getFilename(xmlfile)); URL xmlFile = new File(KettleVFS.getFilename(xmlfile)).toURI().toURL(); // open XML File BufferedReader xmlBufferedReader = new BufferedReader( new InputStreamReader(xmlFile.openStream())); StringBuffer xmlStringbuffer = new StringBuffer(""); char[] buffertXML = new char[1024]; int LenXML = -1; while ((LenXML = xmlBufferedReader.read(buffertXML)) != -1) xmlStringbuffer.append(buffertXML, 0, LenXML); // Prepare parsing ... DocumentBuilderFactory DocBuilderFactory = DocumentBuilderFactory.newInstance(); Document xmlDocDTD = null; DocumentBuilder DocBuilder = DocBuilderFactory.newDocumentBuilder(); // Let's try to get XML document encoding DocBuilderFactory.setValidating(false); xmlDocDTD = DocBuilder .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes("UTF-8"))); String encoding = null; if (xmlDocDTD.getXmlEncoding() == null) { encoding = "UTF-8"; } else { encoding = xmlDocDTD.getXmlEncoding(); } int xmlStartDTD = xmlStringbuffer.indexOf("<!DOCTYPE"); if (dtdintern) { // DTD find in the XML document if (xmlStartDTD != -1) { if (log.isBasic()) log.logBasic(toString(), Messages .getString("JobEntryDTDValidator.ERRORDTDFound.Label", realxmlfilename)); } else { if (log.isBasic()) log.logBasic(toString(), Messages .getString("JobEntryDTDValidator.ERRORDTDNotFound.Label", realxmlfilename)); } } else { // DTD in external document // If we find an intern declaration, we remove it DTDfile = KettleVFS.getFileObject(realDTDfilename); if (DTDfile.exists()) { if (xmlStartDTD != -1) { int EndDTD = xmlStringbuffer.indexOf(">", xmlStartDTD); //String DocTypeDTD = xmlStringbuffer.substring(xmlStartDTD, EndDTD + 1); xmlStringbuffer.replace(xmlStartDTD, EndDTD + 1, ""); } String xmlRootnodeDTD = xmlDocDTD.getDocumentElement().getNodeName(); String RefDTD = "<?xml version='" + xmlDocDTD.getXmlVersion() + "' encoding='" + encoding + "'?>\n<!DOCTYPE " + xmlRootnodeDTD + " SYSTEM '" + KettleVFS.getFilename(DTDfile) + "'>\n"; int xmloffsetDTD = xmlStringbuffer.indexOf("<" + xmlRootnodeDTD); xmlStringbuffer.replace(0, xmloffsetDTD, RefDTD); } else { log.logError(Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Subject"), Messages.getString("JobEntryDTDValidator.ERRORDTDFileNotExists.Msg", realDTDfilename)); } } if ((dtdintern && xmlStartDTD == -1 || (!dtdintern && !DTDfile.exists()))) { result.setResult(false); result.setNrErrors(1); } else { DocBuilderFactory.setValidating(true); // Let's parse now ... xmlDocDTD = DocBuilder .parse(new ByteArrayInputStream(xmlStringbuffer.toString().getBytes(encoding))); if (log.isDetailed()) log.logDetailed(Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Subject"), Messages.getString("JobEntryDTDValidator.DTDValidatorOK.Label", realxmlfilename)); // Everything is OK result.setResult(true); } } else { if (!xmlfile.exists()) { log.logError(toString(), Messages.getString("JobEntryDTDValidator.FileDoesNotExist.Label", realxmlfilename)); } result.setResult(false); result.setNrErrors(1); } } else { log.logError(toString(), Messages.getString("JobEntryDTDValidator.AllFilesNotNull.Label")); result.setResult(false); result.setNrErrors(1); } } catch (Exception e) { log.logError(Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Subject"), Messages.getString("JobEntryDTDValidator.ErrorDTDValidator.Label", realxmlfilename, realDTDfilename, e.getMessage())); result.setResult(false); result.setNrErrors(1); } finally { try { if (xmlfile != null) xmlfile.close(); if (DTDfile != null) DTDfile.close(); } catch (IOException e) { } } return result; }
From source file:com.diversityarrays.update.UpdateDialog.java
private void checkForUpdates(PrintStream ps) { StringBuilder sb = new StringBuilder(updateCheckRequest.updateBaseUrl); sb.append(updateCheckRequest.versionCode); if (RunMode.getRunMode().isDeveloper()) { sb.append("-dev"); //$NON-NLS-1$ }/*from ww w . j a v a2s . c om*/ sb.append(".json"); //$NON-NLS-1$ final String updateUrl; updateUrl = sb.toString(); // updateUrl = "NONEXISTENT"; // Uncomment to check error final ProgressMonitor progressMonitor = new ProgressMonitor(updateCheckRequest.owner, Msg.PROGRESS_CHECKING(), null, 0, 0); worker = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { // Thread.sleep(3000); // Uncomment to check delay BufferedReader reader = null; StringBuffer buffer = new StringBuffer(); try { URL url = new URL(updateUrl); reader = new BufferedReader(new InputStreamReader(url.openStream())); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) { if (progressMonitor.isCanceled()) { cancel(true); return null; } buffer.append(chars, 0, read); } } catch (IOException e) { System.err.println("checkForUpdates: " + e.getMessage()); //$NON-NLS-1$ } finally { if (reader != null) { reader.close(); } } return buffer.toString(); } @Override protected void done() { try { String json = get(); Gson gson = new Gson(); setKDXploreUpdate(gson.fromJson(json, KDXploreUpdate.class)); } catch (CancellationException ignore) { } catch (InterruptedException ignore) { } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof UnknownHostException) { String site = extractSite(updateUrl); ps.println(Msg.ERRMSG_UNABLE_TO_CONTACT_UPDATE_SITE(site)); } else { cause.printStackTrace(ps); } if (cause instanceof FileNotFoundException) { FileNotFoundException fnf = (FileNotFoundException) cause; if (updateUrl.equals(fnf.getMessage())) { // Well maybe someone forgot to create the file on // the server! System.err.println("Maybe someone forgot to create the file!"); //$NON-NLS-1$ System.err.println(fnf.getMessage()); setKDXploreUpdate(new KDXploreUpdate(Msg.ERRMSG_PROBLEMS_CONTACTING_UPDATE_SERVER_1())); return; } } String msg = Msg.HTML_PROBLEMS_CONTACTING_UPDATE_2(StringUtil.htmlEscape(updateUrl), cause.getClass().getSimpleName(), StringUtil.htmlEscape(cause.getMessage())); kdxploreUpdate = new KDXploreUpdate(msg); kdxploreUpdate.unknownHost = (cause instanceof UnknownHostException); return; } } private String extractSite(final String updateUrl) { String site = null; int spos = updateUrl.indexOf("://"); if (spos > 0) { int epos = updateUrl.indexOf('/', spos + 1); if (epos > 0) { site = updateUrl.substring(0, epos); } } if (site == null) { site = updateUrl; } return site; } }; Closure<JDialog> onComplete = new Closure<JDialog>() { @Override public void execute(JDialog d) { if (!processReadUrlResult(updateUrl)) { d.dispose(); } else { d.setVisible(true); } } }; SwingWorkerCompletionWaiter waiter = new SwingWorkerCompletionWaiter(this, onComplete); worker.addPropertyChangeListener(waiter); worker.execute(); }