List of usage examples for java.io BufferedInputStream read
public int read(byte b[]) throws IOException
b.length
bytes of data from this input stream into an array of bytes. From source file:si.mazi.rescu.HttpTemplate.java
/** * <p>/*from www . jav a 2s. c om*/ * Reads an InputStream as a String allowing for different encoding types * </p> * * @param inputStream The input stream * @param responseEncoding The encoding to use when converting to a String * @return A String representation of the input stream * @throws IOException If something goes wrong */ String readInputStreamAsEncodedString(InputStream inputStream, String responseEncoding) throws IOException { if (inputStream == null) { return null; } String responseString; if (responseEncoding != null) { // Have an encoding so use it StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, responseEncoding)); for (String line; (line = reader.readLine()) != null;) { sb.append(line); } responseString = sb.toString(); } else { // No encoding specified so use a BufferedInputStream StringBuilder sb = new StringBuilder(); BufferedInputStream bis = new BufferedInputStream(inputStream); byte[] byteContents = new byte[4096]; int bytesRead; String strContents; while ((bytesRead = bis.read(byteContents)) != -1) { strContents = new String(byteContents, 0, bytesRead); sb.append(strContents); } responseString = sb.toString(); } // System.out.println("responseString: " + responseString); return responseString; }
From source file:DatabaseListener.java
/** * <p>Calculate and return an absolute pathname to the XML file to contain * our persistent storage information.</p> * * @return Absolute path to XML file.//from w w w .j ava2s .c om * @throws Exception if an input/output error occurs */ private String calculatePath() throws Exception { // Can we access the database via file I/O? String path = context.getRealPath(pathname); if (path != null) { return (path); } // Does a copy of this file already exist in our temporary directory File dir = (File) context.getAttribute("javax.servlet.context.tempdir"); File file = new File(dir, "struts-example-database.xml"); if (file.exists()) { return (file.getAbsolutePath()); } // Copy the static resource to a temporary file and return its path InputStream is = context.getResourceAsStream(pathname); BufferedInputStream bis = new BufferedInputStream(is, 1024); FileOutputStream os = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(os, 1024); byte buffer[] = new byte[1024]; while (true) { int n = bis.read(buffer); if (n <= 0) { break; } bos.write(buffer, 0, n); } bos.close(); bis.close(); return (file.getAbsolutePath()); }
From source file:eu.scape_project.arc2warc.PayloadContent.java
private void copyAndCheck(OutputStream outputStream) throws IOException { MessageDigest md;/*from www. j a v a 2 s . c om*/ try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException("SHA-1 not known"); } BufferedInputStream buffis = new BufferedInputStream(inputStream); BufferedOutputStream buffos = new BufferedOutputStream(outputStream); try { byte[] tempBuffer = new byte[BUFFER_SIZE]; int bytesRead; boolean firstByteArray = true; while ((bytesRead = buffis.read(tempBuffer)) != -1) { md.update(tempBuffer, 0, bytesRead); buffos.write(tempBuffer, 0, bytesRead); if (doPayloadIdentification && firstByteArray && bytesRead > 0) { identified = identifyPayloadType(tempBuffer); } firstByteArray = false; } digestStr = "sha1:" + calcDigest(md); consumed = true; } finally { IOUtils.closeQuietly(buffis); IOUtils.closeQuietly(buffos); } }
From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseModel responseModel = new HttpResponseModel(); try {/* ww w . j a v a 2 s. com*/ boolean isMultipart = ServletFileUpload.isMultipartContent(request); // ??? if (isMultipart) { Hashtable<String, String> htSubmitParam = new Hashtable<String, String>(); // ?? List<String> fileList = new ArrayList<String>();// // DiskFileItemFactory?? // ????List // list??? FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items = upload.parseRequest(request); Iterator<FileItem> iterator = items.iterator(); while (iterator.hasNext()) { FileItem item = iterator.next(); if (item.isFormField()) { // ? String sFieldName = item.getFieldName(); String sFieldValue = item.getString("UTF-8"); htSubmitParam.put(sFieldName, sFieldValue); } else { // ,??? String newFileName = System.currentTimeMillis() + "_" + UUID.randomUUID().toString() + ".jpg"; File filePath = new File( getServletConfig().getServletContext().getRealPath(Constants.File_Upload)); if (!filePath.exists()) { filePath.mkdirs(); } File file = new File(filePath, newFileName); if (!file.exists()) { file.createNewFile(); } //? BufferedInputStream bis = new BufferedInputStream(item.getInputStream()); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); byte[] b = new byte[1024]; int length = 0; while ((length = bis.read(b)) > 0) { bos.write(b, 0, length); } bos.close(); bis.close(); //?url String fileUrl = request.getRequestURL().toString(); fileUrl = fileUrl.substring(0, fileUrl.lastIndexOf("/")); //?URL fileUrl = fileUrl + Constants.File_Upload + "/" + newFileName; /**/ fileList.add(fileUrl); } } // String unlockInfoId = htSubmitParam.get("UnlockInfoId"); String imgType = htSubmitParam.get("ImgType"); String newFileUrl = fileList.get(0); UnlockInfoService unlockInfoService = (UnlockInfoService) context.getBean("unlockInfoService"); UnlockInfo unlockInfo = unlockInfoService.queryByPK(Long.valueOf(unlockInfoId)); if (imgType.equals("customerIdImg")) { unlockInfo.setCustomerIdImg(newFileUrl); } else if (imgType.equals("customerDrivingLicenseImg")) { unlockInfo.setCustomerDrivingLicenseImg(newFileUrl); } else if (imgType.equals("customerVehicleLicenseImg")) { unlockInfo.setCustomerVehicleLicenseImg(newFileUrl); } else if (imgType.equals("customerBusinessLicenseImg")) { unlockInfo.setCustomerBusinessLicenseImg(newFileUrl); } else if (imgType.equals("customerIntroductionLetterImg")) { unlockInfo.setCustomerIntroductionLetterImg(newFileUrl); } else if (imgType.equals("unlockWorkOrderImg")) { unlockInfo.setUnlockWorkOrderImg(newFileUrl); } /**/ unlockInfoService.update(unlockInfo); } } catch (Exception e) { e.printStackTrace(); responseModel.responseCode = "0"; responseModel.responseMessage = e.toString(); } /* ??? */ response.setHeader("content-type", "text/json;charset=utf-8"); response.getOutputStream().write(responseModel.toByteArray()); }
From source file:edu.ku.brc.helpers.HTTPGetter.java
/** * Performs a "generic" HTTP request and fill member variable with results * use "getDigirResultsetStr" to get the results as a String * * @param url URL to be executed//from w w w . ja va 2 s.c o m * @param fileCache the file to place the results * @return returns an error code */ public byte[] doHTTPRequest(final String url, final File fileCache) { byte[] bytes = null; Exception excp = null; status = ErrorCode.NoError; // Create an HttpClient with the MultiThreadedHttpConnectionManager. // This connection manager must be used if more than one thread will // be using the HttpClient. httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); GetMethod method = null; try { method = new GetMethod(url); //log.debug("getting " + method.getURI()); //$NON-NLS-1$ httpClient.executeMethod(method); // get the response body as an array of bytes long bytesRead = 0; if (fileCache == null) { bytes = method.getResponseBody(); bytesRead = bytes.length; } else { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileCache)); bytes = new byte[4096]; InputStream ins = method.getResponseBodyAsStream(); BufferedInputStream bis = new BufferedInputStream(ins); while (bis.available() > 0) { int numBytes = bis.read(bytes); if (numBytes > 0) { bos.write(bytes, 0, numBytes); bytesRead += numBytes; } } bos.flush(); bos.close(); bytes = null; } log.debug(bytesRead + " bytes read"); //$NON-NLS-1$ } catch (ConnectException ce) { excp = ce; log.error(String.format("Could not make HTTP connection. (%s)", ce.toString())); //$NON-NLS-1$ status = ErrorCode.HttpError; } catch (HttpException he) { excp = he; log.error(String.format("Http problem making request. (%s)", he.toString())); //$NON-NLS-1$ status = ErrorCode.HttpError; } catch (IOException ioe) { excp = ioe; log.error(String.format("IO problem making request. (%s)", ioe.toString())); //$NON-NLS-1$ status = ErrorCode.IOError; } catch (java.lang.IllegalArgumentException ioe) { excp = ioe; log.error(String.format("IO problem making request. (%s)", ioe.toString())); //$NON-NLS-1$ status = ErrorCode.IOError; } catch (Exception e) { excp = e; log.error("Error: " + e); //$NON-NLS-1$ status = ErrorCode.Error; } finally { // always release the connection after we're done if (isThrowingErrors && status != ErrorCode.NoError) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HTTPGetter.class, excp); } if (method != null) method.releaseConnection(); //log.debug("Connection released"); //$NON-NLS-1$ } if (listener != null) { if (status == ErrorCode.NoError) { listener.completed(this); } else { listener.completedWithError(this, status); } } return bytes; }
From source file:com.xeiam.xchange.rest.HttpTemplate.java
/** * <p>//from ww w . j a v a2s. co m * Reads an InputStream as a String allowing for different encoding types * </p> * * @param inputStream The input stream * @param responseEncoding The encoding to use when converting to a String * @return A String representation of the input stream * @throws IOException If something goes wrong */ String readInputStreamAsEncodedString(InputStream inputStream, String responseEncoding) throws IOException { String responseString; if (responseEncoding != null) { // Have an encoding so use it StringBuilder sb = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, responseEncoding)); for (String line; (line = reader.readLine()) != null;) { sb.append(line); } responseString = sb.toString(); } else { // No encoding specified so use a BufferedInputStream StringBuilder sb = new StringBuilder(); BufferedInputStream bis = new BufferedInputStream(inputStream); byte[] byteContents = new byte[4096]; int bytesRead; String strContents; while ((bytesRead = bis.read(byteContents)) != -1) { strContents = new String(byteContents, 0, bytesRead); sb.append(strContents); } responseString = sb.toString(); } // System.out.println("responseString: " + responseString); return responseString; }
From source file:com.redhat.rhn.frontend.xmlrpc.system.crash.CrashHandler.java
/** * Download a base64 encoded crash file. * @param loggedInUser The current user//from w ww . ja va 2 s .co m * @param crashFileId Crash File ID * @return Return a byte array of the crash file. * @throws IOException if there is an exception * * @xmlrpc.doc Download a crash file. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param("int", "crashFileId") * @xmlrpc.returntype base64 - base64 encoded crash file. */ public byte[] getCrashFile(User loggedInUser, Integer crashFileId) throws IOException { CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(loggedInUser, new Long(crashFileId.longValue())); String path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashFile.getCrash().getStoragePath() + "/" + crashFile.getFilename(); File file = new File(path); if (file.length() > freeMemCoeff * Runtime.getRuntime().freeMemory()) { throw new CrashFileDownloadException("api.crashfile.download.toolarge"); } byte[] plainFile = new byte[(int) file.length()]; FileInputStream fis = new FileInputStream(file); BufferedInputStream br = new BufferedInputStream(fis); if (br.read(plainFile) != file.length()) { throw new CrashFileDownloadException("api.package.download.ioerror"); } fis.close(); br.close(); return Base64.encodeBase64(plainFile); }
From source file:components.TumbleItem.java
/** * Load the image for the specified frame of animation. Since * this runs as an applet, we use getResourceAsStream for * efficiency and so it'll work in older versions of Java Plug-in. *///from w w w.j a v a 2 s . c om protected ImageIcon loadImage(int imageNum) { String path = dir + "/T" + imageNum + ".gif"; int MAX_IMAGE_SIZE = 2400; //Change this to the size of //your biggest image, in bytes. int count = 0; BufferedInputStream imgStream = new BufferedInputStream(this.getClass().getResourceAsStream(path)); if (imgStream != null) { byte buf[] = new byte[MAX_IMAGE_SIZE]; try { count = imgStream.read(buf); imgStream.close(); } catch (java.io.IOException ioe) { System.err.println("Couldn't read stream from file: " + path); return null; } if (count <= 0) { System.err.println("Empty file: " + path); return null; } return new ImageIcon(Toolkit.getDefaultToolkit().createImage(buf)); } else { System.err.println("Couldn't find file: " + path); return null; } }
From source file:com.qut.middleware.metadata.source.impl.MetadataSourceBase.java
/** * Reads the provided input stream, calculates and updates an internal hash. * If the internal hash has changed, the byte array obtained from reading the * InputStream is passed to the processMetadata method, along with the * provided MetadataProcessor object./* w ww .j a v a 2 s .com*/ * @param input Input stream to send * @param processor * @throws IOException */ protected void readMetadata(InputStream input, MetadataProcessor processor) throws IOException { byte[] buf = new byte[BUFFER_LENGTH]; long startTime = System.currentTimeMillis(); // Pipe everything through a digest stream so we get a hash value at the end DigestInputStream digestInput = new DigestInputStream(input, this.getMessageDigestInstance()); BufferedInputStream bufferedInput = new BufferedInputStream(digestInput); ByteArrayOutputStream byteOutput = new ByteArrayOutputStream(); this.logger.debug("Metadata source {} - going to read input stream", this.getLocation()); int bytes = 0; while ((bytes = bufferedInput.read(buf)) != -1) { byteOutput.write(buf, 0, bytes); } bufferedInput.close(); digestInput.close(); byteOutput.close(); long endTime = System.currentTimeMillis(); byte[] document = byteOutput.toByteArray(); byte[] hash = digestInput.getMessageDigest().digest(); this.logger.debug("Metadata source {} - read {} bytes of metadata in {} ms", new Object[] { this.getLocation(), document.length, (endTime - startTime) }); // If the document has changed, the hash will be updated, and then we go to process the new document if (this.updateDigest(hash)) { startTime = System.currentTimeMillis(); this.logger.debug("Metadata source {} - updated. Going to process.", this.getLocation()); this.processMetadata(document, processor); endTime = System.currentTimeMillis(); this.logger.info("Metadata source {} - processed document and updated cache in {} ms", this.getLocation(), (endTime - startTime)); } else { this.logger.info("Metadata source {} - has not been updated.", this.getLocation()); } }
From source file:net.sourceforge.atunes.kernel.modules.network.NetworkHandler.java
@Override public String readURL(final URLConnection connection, final int bytes) throws IOException { BufferedInputStream bis = null; try {//from ww w.j a v a 2 s . co m InputStream input = connection.getInputStream(); bis = new BufferedInputStream(input); byte[] array = new byte[bytes]; int read = bis.read(array); return read != -1 ? new String(array) : null; } finally { ClosingUtils.close(bis); } }