List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:alpha.portal.webapp.controller.PayloadVersionsController.java
/** * Gets the payload.//from w w w. j a va2 s . c o m * * @param request * the request * @param response * the response * @return the payload * @throws IOException * Signals that an I/O exception has occurred. */ @RequestMapping(method = RequestMethod.GET, params = { "seqNumber" }) public String getPayload(final HttpServletRequest request, final HttpServletResponse response) throws IOException { final Locale locale = request.getLocale(); if ((request.getParameter("card") == null) || (request.getParameter("case") == null)) { this.saveError(request, this.getText("payloadVersions.cardNotFound", locale)); return ""; } final String cardId = request.getParameter("card"); final String caseId = request.getParameter("case"); final AlphaCard currentCard = this.alphaCardManager.get(new AlphaCardIdentifier(caseId, cardId)); final Payload payload = this.payloadManager .getVersion(new PayloadIdentifier(currentCard.getPayload().getPayloadIdentifier().getPayloadId(), Long.parseLong(request.getParameter("seqNumber")))); if (payload != null) { final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(payload.getContent())); response.setBufferSize(payload.getContent().length); response.setContentType(payload.getMimeType()); response.setHeader("Content-Disposition", "attachment; filename=\"" + payload.getFilename() + "\""); response.setContentLength(payload.getContent().length); FileCopyUtils.copy(in, response.getOutputStream()); in.close(); response.getOutputStream().flush(); response.getOutputStream().close(); } return "redirect:/payloadVersions?case=" + currentCard.getAlphaCardIdentifier().getCaseId() + "&card=" + currentCard.getAlphaCardIdentifier().getCardId(); }
From source file:com.lock.unlockInfo.servlet.SubmitUnlockImg.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpResponseModel responseModel = new HttpResponseModel(); try {//from w w w .jav a2s. c o m 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:com.nookdevs.library.Smashwords.java
@Override public void downloadBook(ScannedFile file) { try {/*w ww . j a va2 s .c o m*/ if (m_User == null) { getUser(); } nookLib.waitForNetwork(lock); HttpPost request = new HttpPost(file.getDownloadUrl()); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", m_User)); nvps.add(new BasicNameValuePair("password", m_Pass)); request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpClient.execute(request); String type = response.getEntity().getContentType().getValue(); InputStream in = response.getEntity().getContent(); if (type.contains("xml")) { XmlPullParserFactory fact = XmlPullParserFactory.newInstance(); fact.setNamespaceAware(false); XmlPullParser parser = fact.newPullParser(); parser.setInput(in, null); while ((parser.next()) != XmlPullParser.END_DOCUMENT) { String text = parser.getText(); if (text == null) { continue; } text = text.trim(); if (text.equals("\n") || text.equals("")) { continue; } if (text.startsWith("http")) { file.setDownloadUrl(text); downloadBook(file); return; } } // failed. throw new Exception("Invalid data returned."); } else if (type.contains("html")) { throw new Exception("Invalid data returned."); } int idx = file.getDownloadUrl().lastIndexOf('/'); String name = m_BaseDir + file.getDownloadUrl().substring(idx + 1); BufferedInputStream bis = new BufferedInputStream(in, 8096); FileOutputStream fout = new FileOutputStream(new File(name)); byte[] buffer = new byte[8096]; int len; while ((len = bis.read(buffer)) >= 0) { fout.write(buffer, 0, len); } bis.close(); fout.close(); file.setPathName(name); file.setStatus(null); file.updateLastAccessDate(); updateBookInDB(file); nookLib.getHandler().post(new Runnable() { public void run() { Toast.makeText(nookLib, R.string.download_complete, Toast.LENGTH_SHORT).show(); } }); close(); } catch (Exception ex) { Log.e("Smashwords", "exception while downloading book", ex); nookLib.getHandler().post(new Runnable() { public void run() { Toast.makeText(nookLib, R.string.download_failed, Toast.LENGTH_LONG).show(); } }); file.setStatus(BNBooks.DOWNLOAD); close(); } finally { if (lock.isHeld()) { lock.release(); } } return; }
From source file:au.com.addstar.SpigotDirectDownloader.java
public boolean downloadUpdate(ResourceInfo info, File file, Long timeOut) throws InvalidDownloadException, ConnectionFailedException { try {/*from w ww. j a va 2 s .c o m*/ webClient.getOptions().setThrowExceptionOnFailingStatusCode(false); Resource resource = api.getResourceManager().getResourceById(info.id, spigotUser); if (info.premium && !owned.contains(resource.getResourceId())) { return false; } Page page = webClient.getPage(resource.getDownloadURL()); webClient.waitForBackgroundJavaScript(timeOut); // todo need to add check for need purchase or no auth. BufferedInputStream in = new java.io.BufferedInputStream( page.getEnclosingWindow().getEnclosedPage().getWebResponse().getContentAsStream()); java.io.FileOutputStream fos = new java.io.FileOutputStream(file); java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 1024); byte[] data = new byte[1024]; int x; while ((x = in.read(data, 0, 1024)) >= 0) { bout.write(data, 0, x); } bout.close(); in.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } Plugin plugin = Plugin.checkDownloadedVer(file); if (plugin == null || plugin.getVersion() == null) { FileUtils.deleteQuietly(file); if (timeOut < 15000L && info.external) { downloadUpdate(info, file, timeOut + 5000L); } throw new InvalidDownloadException("File did not contain a plugin.yml"); } return true; }
From source file:com.cypress.cysmart.RDKEmulatorView.MicrophoneEmulatorFragment.java
private byte[] getBytesFromFile(File fileToConvert) { int size = (int) fileToConvert.length(); byte[] bytes = new byte[size]; try {// www.j a v a 2s .c o m BufferedInputStream buf = new BufferedInputStream(new FileInputStream(fileToConvert)); buf.read(bytes, 0, bytes.length); buf.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Logger.e("Read file Length" + bytes.length); return bytes; }
From source file:com.redhat.rhn.frontend.xmlrpc.system.crash.CrashHandler.java
/** * Download a base64 encoded crash file. * @param loggedInUser The current user/* ww w .j a v a 2s. c o 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:de.rub.syssec.saaf.analysis.steps.extract.ApkUnzipper.java
/** * Extracts the given apk into the given destination directory * /*from w w w . ja v a 2 s . com*/ * @param archive * - the file to extract * @param dest * - the destination directory * @throws IOException */ public static void extractApk(File archive, File dest) throws IOException { @SuppressWarnings("resource") // Closing it later results in an error ZipFile zipFile = new ZipFile(archive); Enumeration<? extends ZipEntry> entries = zipFile.entries(); BufferedOutputStream bos = null; BufferedInputStream bis = null; while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryFileName = entry.getName(); byte[] buffer = new byte[16384]; int len; File dir = buildDirectoryHierarchyFor(entryFileName, dest);// destDir if (!dir.exists()) { dir.mkdirs(); } if (!entry.isDirectory()) { if (entry.getSize() == 0) { LOGGER.warn("Found ZipEntry \'" + entry.getName() + "\' with size 0 in " + archive.getName() + ". Looks corrupted."); continue; } try { bos = new BufferedOutputStream(new FileOutputStream(new File(dest, entryFileName)));// destDir,... bis = new BufferedInputStream(zipFile.getInputStream(entry)); while ((len = bis.read(buffer)) > 0) { bos.write(buffer, 0, len); } bos.flush(); } catch (IOException ioe) { LOGGER.warn("Failed to extract entry \'" + entry.getName() + "\' from archive. Results for " + archive.getName() + " may not be accurate"); } finally { if (bos != null) bos.close(); if (bis != null) bis.close(); // if (zipFile != null) zipFile.close(); } } } }
From source file:azkaban.webapp.servlet.LoginAbstractAzkabanServlet.java
private boolean handleFileGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (webResourceDirectory == null) { return false; }//w w w. j a va 2s . c o m // Check if it's a resource String prefix = req.getContextPath() + req.getServletPath(); String path = req.getRequestURI().substring(prefix.length()); int index = path.lastIndexOf('.'); if (index == -1) { return false; } String extension = path.substring(index); if (contextType.containsKey(extension)) { File file = new File(webResourceDirectory, path); if (!file.exists() || !file.isFile()) { return false; } resp.setContentType(contextType.get(extension)); OutputStream output = resp.getOutputStream(); BufferedInputStream input = null; try { input = new BufferedInputStream(new FileInputStream(file)); IOUtils.copy(input, output); } finally { if (input != null) { input.close(); } } output.flush(); return true; } return false; }
From source file:com.ichi2.libanki.Exporter.java
private void writeEntry(BufferedInputStream bis, ZipEntry ze) throws IOException { byte[] buf = new byte[BUFFER_SIZE]; mZos.putNextEntry(ze);//from w w w . ja v a 2 s . c o m int len; while ((len = bis.read(buf, 0, BUFFER_SIZE)) != -1) { mZos.write(buf, 0, len); } mZos.closeEntry(); bis.close(); }
From source file:com.robertszkutak.androidexamples.imgurexample.ImgurExampleActivity.java
public void uploadImage() { String imagePath = path.getText().toString(); String ext = imagePath.substring(imagePath.length() - 5); if (!ext.matches(".jpeg") && !ext.matches(".JPEG")) ext = imagePath.substring(imagePath.length() - 4); FileInputStream in;// w w w . j a v a2s . c o m BufferedInputStream buf; Bitmap bMap = null; try { in = new FileInputStream(imagePath); buf = new BufferedInputStream(in); bMap = BitmapFactory.decodeStream(buf); if (in != null) in.close(); if (buf != null) buf.close(); } catch (Exception e) { Log.e("Error reading file", e.toString()); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (ext.matches(".jpeg") || ext.matches(".JPEG") || ext.matches(".jpg") || ext.matches(".JPG")) bMap.compress(CompressFormat.JPEG, 0, bos);//TODO : Figure out how to retain high quality JPG if (ext.matches(".png") || ext.matches(".PNG")) bMap.compress(CompressFormat.PNG, 0, bos); //TODO : Figure out GIF String data = null; data = Base64.encodeToString(bos.toByteArray(), false); HttpPost hpost = new HttpPost("http://api.imgur.com/2/account/images"); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("image", data)); nameValuePairs.add(new BasicNameValuePair("type", "base64")); try { hpost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { debug += e.toString(); } consumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); consumer.setTokenWithSecret(token, secret); try { consumer.sign(hpost); } catch (OAuthMessageSignerException e) { debug += e.toString(); } catch (OAuthExpectationFailedException e) { debug += e.toString(); } catch (OAuthCommunicationException e) { debug += e.toString(); } DefaultHttpClient client = new DefaultHttpClient(); HttpResponse resp = null; try { resp = client.execute(hpost); } catch (ClientProtocolException e) { debug += e.toString(); } catch (IOException e) { debug += e.toString(); } String result = null; try { result = EntityUtils.toString(resp.getEntity()); } catch (ParseException e) { debug += e.toString(); } catch (IOException e) { debug += e.toString(); } debug += result; debugStatus.setText(debug); }