List of usage examples for java.io BufferedInputStream read
public synchronized int read() throws IOException
read
method of InputStream
. From source file:org.caboclo.clients.ApiClient.java
protected void downloadURL(String url, ByteArrayOutputStream bos, Map<String, String> headers) throws IllegalStateException, IOException { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); for (String key : headers.keySet()) { String value = headers.get(key); httpget.setHeader(key, value);//from ww w . jav a 2s . c o m } HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { try { InputStream instream = entity.getContent(); BufferedInputStream bis = new BufferedInputStream(instream); int inByte; while ((inByte = bis.read()) != -1) { bos.write(inByte); } bis.close(); bos.close(); } catch (IOException ex) { ex.printStackTrace(); throw ex; } catch (IllegalStateException ex) { ex.printStackTrace(); httpget.abort(); throw ex; } httpclient.getConnectionManager().shutdown(); } }
From source file:it.eng.spagobi.kpi.service.KpiXmlExporterAction.java
/** * This action is called by the user who wants to export the result of a Kpi in XML * /* w w w.j a v a2 s . com*/ */ public void service(SourceBean serviceRequest, SourceBean serviceResponse) throws Exception { File tmpFile = null; logger.debug("IN"); HttpServletRequest httpRequest = getHttpRequest(); HttpSession session = httpRequest.getSession(); this.freezeHttpResponse(); try { // get KPI result List<KpiResourceBlock> listKpiBlocks = (List<KpiResourceBlock>) session.getAttribute("KPI_BLOCK"); String title = (String) session.getAttribute("TITLE"); String subtitle = (String) session.getAttribute("SUBTITLE"); if (title == null) title = ""; if (subtitle == null) subtitle = ""; // recover BiObject Name Object idObject = serviceRequest.getAttribute(SpagoBIConstants.OBJECT_ID); if (idObject == null) { logger.error("Document id not found"); return; } Integer id = Integer.valueOf(idObject.toString()); BIObject document = DAOFactory.getBIObjectDAO().loadBIObjectById(id); String docName = document.getName(); //Recover user Id HashedMap parameters = new HashedMap(); String userId = null; Object userIdO = serviceRequest.getAttribute("user_id"); if (userIdO != null) userId = userIdO.toString(); it.eng.spagobi.engines.exporters.KpiExporter exporter = new KpiExporter(); tmpFile = exporter.getKpiExportXML(listKpiBlocks, document, userId); String outputType = "XML"; String mimeType = "text/xml"; logger.debug("Report exported succesfully"); HttpServletResponse response = getHttpResponse(); response.setContentType(mimeType); response.setHeader("Content-Disposition", "filename=\"report." + outputType + "\";"); response.setContentLength((int) tmpFile.length()); BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); int b = -1; while ((b = in.read()) != -1) { response.getOutputStream().write(b); } response.getOutputStream().flush(); in.close(); logger.debug("OUT"); } catch (Throwable e) { logger.error("An exception has occured", e); throw new Exception(e); } finally { tmpFile.delete(); } }
From source file:org.pegadi.webapp.view.FileView.java
protected void renderMergedOutputModel(Map map, HttpServletRequest request, HttpServletResponse response) throws IOException { // get the file from the map File file = (File) map.get("file"); // check if it exists if (file == null || !file.exists() || !file.canRead()) { log.warn("Error reading: " + file); try {// ww w . ja va 2s . co m response.sendError(404); } catch (IOException e) { log.error("Could not write to response", e); } return; } // give some info in the response response.setContentType(getServletContext().getMimeType(file.getAbsolutePath())); // files does not change so often, allow three days caching response.setHeader("Cache-Control", "max-age=259200"); response.setContentLength((int) file.length()); // start writing to the response BufferedOutputStream out = null; BufferedInputStream in = null; try { out = new BufferedOutputStream(response.getOutputStream()); in = new BufferedInputStream(new FileInputStream(file)); int c = in.read(); while (c != -1) { out.write(c); c = in.read(); } } finally { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } } }
From source file:fr.gcastel.freeboxV6GeekIncDownloader.services.GeekIncLogoDownloadService.java
public void downloadAndResize(int requiredSize) throws Exception { // Si le logo existe depuis moins d'une semaine, on ne le retlcharge // pas/*from www. j a v a 2 s .c o m*/ if (outFile.exists()) { // Moins une semaine long uneSemainePlusTot = System.currentTimeMillis() - (7 * 24 * 60 * 60 * 1000); if (outFile.lastModified() > uneSemainePlusTot) { Log.i("GeekIncLogoDownloadService", "Le logo a dj t tlcharg il y a moins d'une semaine."); return; } } URLConnection ucon = toDownload.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } bis.close(); is.close(); // Fichier temporaire pour redimensionnement File tmpFile = new File(outFile.getAbsolutePath() + "tmp"); FileOutputStream fos = new FileOutputStream(tmpFile); fos.write(baf.toByteArray()); fos.close(); saveAndResizeFile(tmpFile, outFile, requiredSize); // Suppression du fichier temporaire tmpFile.delete(); }
From source file:org.terracotta.management.cli.rest.AbstractHttpCommand.java
private byte[] toBytes(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (true) { int read = bis.read(); if (read == -1) break; baos.write(read);/*from ww w .j av a 2 s. c o m*/ } baos.close(); return baos.toByteArray(); }
From source file:MainServer.ImageUploadServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); try {//from www . j av a2 s . c o m List<FileItem> items = this.upload.parseRequest(request); if (items != null && !items.isEmpty()) { for (FileItem item : items) { String filename = item.getName(); String filepath = fileDir + File.separator + filename; System.out.println("File path: " + filepath); File file = new File(filepath); InputStream inputStream = item.getInputStream(); BufferedInputStream bis = new BufferedInputStream(inputStream); FileOutputStream fos = new FileOutputStream(file); int f; while ((f = bis.read()) != -1) { fos.write(f); } fos.flush(); fos.close(); bis.close(); inputStream.close(); System.out.println("File: " + filename + "Uploaded"); } } System.out.println("Uploaded!"); out.write("Uploaded!"); } catch (FileUploadException | IOException e) { System.out.println(e); out.write(fileDir); } }
From source file:com.data.RetrieveDataTask.java
protected Boolean doInBackground(Object... params) { try {// www . j a v a 2 s. c om Timber.d("check for updates..."); DataProvider dataProvider = new DataProvider(); boolean isAlreadyStored = false; isAlreadyStored = dataProvider.isDataStored((Activity) params[0]); if (!isAlreadyStored) { Timber.d("no data available, so retrieve data..."); HttpResponse response = new DefaultHttpClient().execute(new HttpGet(Constants.NAME_ROOM_URL)); BufferedInputStream in = new BufferedInputStream(response.getEntity().getContent()); LinkedList<Byte> bytes = new LinkedList<>(); int b; while ((b = in.read()) != -1) { bytes.add((byte) b); } byte[] decryptedData = DecryptionService.decryptData(bytes, (String) params[1]); String data = new String(decryptedData); for (String l : data.split("\n")) { dataProvider.addNewEntry(l, (Activity) params[0]); } } SharedPreferences spData = ((Activity) params[0]).getApplicationContext().getSharedPreferences("Data", 0); int remoteVersion = spData.getInt("DataVersionRemote", 0); spData.edit().putInt("DataVersion", remoteVersion).apply(); Timber.d("... update success"); return true; } catch (Exception e) { Timber.e(e, "... update failure " + e.getMessage()); } return false; }
From source file:Strings.java
/** Process one file */ protected void process(String fileName, InputStream inStream) { try {/*from ww w .j av a 2s . c om*/ int i; char ch; // This line alone cuts the runtime by about 66% on large files. BufferedInputStream is = new BufferedInputStream(inStream); StringBuffer sb = new StringBuffer(); // Read a byte, cast it to char, check if part of printable string. while ((i = is.read()) != -1) { ch = (char) i; if (isStringChar(ch) || (sb.length() > 0 && ch == ' ')) // If so, build up string. sb.append(ch); else { // if not, see if anything to output. if (sb.length() == 0) continue; if (sb.length() >= minLength) { report(fileName, sb); } sb.setLength(0); } } is.close(); } catch (IOException e) { System.out.println("IOException: " + e); } }
From source file:com.athena.peacock.controller.web.as.AutoScalingController.java
@RequestMapping("/xml") public void xml(HttpServletRequest request, HttpServletResponse response) throws Exception { //response.setContentType("application/xml"); response.setContentType("text/xml"); try {//from www.j av a2 s. c om File file = new File(getClass().getResource("/spring/context-common.xml").getFile()); BufferedInputStream fin = new BufferedInputStream(new FileInputStream(file)); BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream()); int read = 0; while ((read = fin.read()) != -1) { outs.write(read); } IOUtils.closeQuietly(fin); IOUtils.closeQuietly(outs); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.norconex.collector.http.fetch.impl.DefaultDocumentFetcher.java
@Override public CrawlStatus fetchDocument(DefaultHttpClient httpClient, HttpDocument doc) { //TODO replace signature with Writer class. LOG.debug("Fetching document: " + doc.getUrl()); HttpGet method = null;//from www . j a va 2 s. c o m try { method = new HttpGet(doc.getUrl()); // Execute the method. HttpResponse response = httpClient.execute(method); int statusCode = response.getStatusLine().getStatusCode(); InputStream is = response.getEntity().getContent(); if (ArrayUtils.contains(validStatusCodes, statusCode)) { //--- Fetch headers --- Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header header = headers[i]; String name = header.getName(); if (StringUtils.isNotBlank(headersPrefix)) { name = headersPrefix + name; } if (doc.getMetadata().getString(name) == null) { doc.getMetadata().addString(name, header.getValue()); } } //--- Fetch body FileOutputStream os = FileUtils.openOutputStream(doc.getLocalFile()); IOUtils.copy(is, os); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); return CrawlStatus.OK; } // read response anyway to be safer, but ignore content BufferedInputStream bis = new BufferedInputStream(is); int result = bis.read(); while (result != -1) { result = bis.read(); } IOUtils.closeQuietly(bis); if (statusCode == HttpStatus.SC_NOT_FOUND) { return CrawlStatus.NOT_FOUND; } LOG.debug("Unsupported HTTP Response: " + response.getStatusLine()); return CrawlStatus.BAD_STATUS; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.error("Cannot fetch document: " + doc.getUrl() + " (" + e.getMessage() + ")", e); } else { LOG.error("Cannot fetch document: " + doc.getUrl() + " (" + e.getMessage() + ")"); } throw new HttpCollectorException(e); } finally { if (method != null) { method.releaseConnection(); } } }