List of usage examples for java.io BufferedInputStream close
public void close() throws IOException
From source file:SendWord.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendWord servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".doc") == -1) fileName = fileName + ".doc"; String wordDir = getServletContext().getInitParameter("word-dir"); if (wordDir == null || wordDir.equals("")) throw new ServletException("Invalid or non-existent wordDir context-param."); ServletOutputStream stream = null;/*w w w.jav a 2s . c o m*/ BufferedInputStream buf = null; try { stream = response.getOutputStream(); File doc = new File(wordDir + "/" + fileName); response.setContentType("application/msword"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) doc.length()); FileInputStream input = new FileInputStream(doc); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:SendXml.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendXml servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".xml") == -1) fileName = fileName + ".xml"; String xmlDir = getServletContext().getInitParameter("xml-dir"); if (xmlDir == null || xmlDir.equals("")) throw new ServletException("Invalid or non-existent xmlDir context-param."); ServletOutputStream stream = null;/*from www . j a v a2 s .c om*/ BufferedInputStream buf = null; try { stream = response.getOutputStream(); File xml = new File(xmlDir + "/" + fileName); response.setContentType("text/xml"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) xml.length()); FileInputStream input = new FileInputStream(xml); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:geocoder.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods.//from w w w .j av a 2 s. com * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ String params = ""; String adr = ""; String fadr = ""; String reqAdr = ""; String extFileData = ""; String outString = ""; String outStringErr = ""; String line; Integer lineCount = 0; Enumeration enParam = request.getParameterNames(); while (enParam.hasMoreElements()) { String paramName = (String) enParam.nextElement(); params += "[" + paramName + "=" + request.getParameter(paramName) + "]"; if (paramName.equals("adr")) { adr = request.getParameter(paramName); } } String webData = ""; String sender = ""; try { // debug // webDataAr[0] = "120|5000"; Date cDate = new Date(); // int tmpInt = Integer.parseInt(webDataAr[0])+1; // if (tmpInt>360){tmpInt=3;} // webDataAr[0] = tmpInt+""; // locX=777; // locY=777; // String sender // ="v="+cDate.toString()+"&lX="+aValues[0]+"&lY="+aValues[1]+ // "&v0="+mValues[0]+"&v1="+mValues[1]+"&v2="+mValues[2]; Calendar cal = new GregorianCalendar(); int month = cal.get(Calendar.MONTH); month++; //String todayIs= cal.get(Calendar.YEAR) + "-" + month + "-" + cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + " "; String todayIs = cal.get(Calendar.YEAR) + "o" + month + "o" + cal.get(Calendar.DAY_OF_MONTH) + "o" + cal.get(Calendar.HOUR_OF_DAY) + "o" + cal.get(Calendar.MINUTE) + "o" + cal.get(Calendar.SECOND) + "o"; sender = "http://maps.googleapis.com/maps/api/geocode/json?address="; //URLEncoder.encode(adr +" " + city + " " + region, "UTF8"); //String urlStr = "http://92.63.96.27:8180/wm/wm_s?" + sender; //---LOAD FROM FILE------------------------------------------------------------ // process the line. BufferedReader br = new BufferedReader(new FileReader("C:\\system\\temp\\111.txt")); while ((line = br.readLine()) != null) { lineCount++; try { //reqAdr = "?++?+?+9"; String urlStr = "http://maps.googleapis.com/maps/api/geocode/json?address=" + URLEncoder.encode(line, "UTF8"); URL myURL = new URL(urlStr); URLConnection ucon = myURL.openConnection(); InputStream is = ucon.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(50); try { int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } webData = new String(baf.toByteArray()); } finally { // baf.clear(); bis.close(); } if (!webData.equalsIgnoreCase("-")) { String tStr = webData.substring(webData.indexOf("formatted_address") + 21); String formatname = tStr.substring(1, tStr.indexOf("geometry")); String longlat = tStr.substring(tStr.indexOf("location\""), tStr.indexOf("location_")); outString += line + "|" + formatname + "|" + longlat + "|" + "<hr/>";//.substring(webData.indexOf("location"),webData.indexOf("location_type"))+"<hr/>"; // StringTokenizer st = new StringTokenizer(webData, "{"); // while (st.hasMoreTokens()) { // outString += st.nextToken().trim(); // } //outString = "'" + extFileData + "'+'|'+'" + line + "'+'|'+response.results[0].formatted_address+'|'+response.results[0].geometry.location.lat+'|'+response.results[0].geometry.location.lng;+'|';\n"; //fadr = adr.substring(adr.indexOf("formated_address"), adr.length()); // for (int i = 0; i < 99; i++) { // webDataAr[i + 1] = webDataAr[i]; // webDataArTm[i + 1] = webDataArTm[i]; // } // <<<<<<< .mine // StringTokenizer st = new StringTokenizer(webData,"|"); // int i=0; // / while (st.hasMoreTokens()) { // webDataAr[i] = st.nextToken().trim(); // i++; // } // ======= // webDataAr[0] = webData.trim(); // // webDataAr[0] = "120|5000"; // // >>>>>>> .r93 // Log.d("ar_wSndr:", "webData1 [" + webData + "]"); // // webDataAr[0] = "180"; // webDataArTm[0] = System.currentTimeMillis(); } } catch (Exception err) { } } br.close(); // inetView.setText("inet answ: " + new // String(baf.toByteArray())); // inetView.setText("inet answ: " + sender); // Toast.makeText(this, // "Sended to web!:"+sender,Toast.LENGTH_LONG).show(); // Log.d("ar_wSndr:", "ar_" + urlStr + " >>> " + baf.toByteArray()); } catch (Exception e) { // ex = e; // Log.e(getClass().getSimpleName(), "problem encountered", e); e.printStackTrace(); // Log.d("wSndrErr", e.toString()); outStringErr = e.toString(); } out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println( "<title>Servlet geocoder</title>" + "" + "<script src=\"js/jquery-1.11.2.min.js\"></script>"); out.println("<script >function init(){\n" + "var response=" + webData + ";\n"//extFileData + "var outString ='" + outString + "\n';" + "$('#console').text(outString);\n" + "\n" + "}\n" + "</script></head>"); out.println( "<body onLoad='init()'>" + params + "<hr/>" + sender + "<hr/>" + webData + "<hr/>fadr:" + fadr); out.println("<h1>Servlet geocoder at " + request.getContextPath() + "</h1>"); out.println("<div id='console'> </div>"); out.println("<div style='border:solid gray 1px'>" + outString + " </div><hr/>"); out.println("<div style='border:solid red 1px'>" + outStringErr + " </div><hr/>"); out.println("<div style='border:solid blue 1px'>" + lineCount + " </div><hr/>"); out.println("<div style='border:solid green 1px'>" + webData + " </div>"); out.println("</body>"); out.println("</html>"); } }
From source file:gov.medicaid.services.impl.FileNetServiceBean.java
/** * Export the files after enrollment process is completed. * //from w w w. jav a 2s. co m * @param model * enrollment model * @param ticketId * the ticket id * @throws PortalServiceException * if any error occurs */ @Override public void exportFiles(EnrollmentProcess model, long ticketId) throws PortalServiceException { // 1. Create the folder File folder = new File(fileNetFolder, UUID.randomUUID().toString()); folder.mkdir(); // 2. Copy the Provider PDF and save it to FileNet folder ProviderInformationType provider = XMLUtility.nsGetProvider(model); File pdfFile = new File(exportPDFFolder, String.valueOf(ticketId)); BufferedInputStream input = null; BufferedOutputStream output = null; try { output = new BufferedOutputStream( new FileOutputStream(new File(folder.getAbsolutePath(), "Profile.pdf"))); input = new BufferedInputStream(new FileInputStream(pdfFile)); IOUtils.copy(input, output); } catch (IOException e) { throw new PortalServiceException("Failed to create file for FileNet", e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { // ignore } } if (output != null) { try { output.close(); } catch (IOException e) { // ignore } } } Enrollment enrollment = providerEnrollmentService.getTicketDetails(getSystemUser(), ticketId); List<gov.medicaid.entities.Document> attachments = enrollment.getDetails().getAttachments(); for (gov.medicaid.entities.Document attachment : attachments) { BinaryContent content = getEm().find(BinaryContent.class, attachment.getContentId()); try { // 3. Copy the file from DB and save it to FileNet folder File file = new File(folder.getAbsolutePath(), attachment.getFilename()); output = new BufferedOutputStream(new FileOutputStream(file)); input = new BufferedInputStream(content.getContent().getBinaryStream()); IOUtils.copy(input, output); // 4. Create the XML for the file Map<String, String> attributes = new LinkedHashMap<String, String>(); attributes.put("Document Class", "Provider Enrollment"); attributes.put("Provider Type", provider.getProviderType()); if (provider.getApplicantInformation().getOrganizationInformation() != null) { // org provider Organization organization = (Organization) enrollment.getDetails().getEntity(); attributes.put("FEIN", organization.getFein()); attributes.put("Provider Name", organization.getLegalName()); attributes.put("Sub Provider Type", organization.getProviderSubType()); attributes.put("Provider Identifier", String.valueOf(organization.getId())); } else { // ind provider Person person = (Person) enrollment.getDetails().getEntity(); attributes.put("NPI", person.getNpi()); attributes.put("SSN", person.getSsn()); attributes.put("Provider Name", person.getFirstName() + " " + person.getMiddleName() + " " + person.getLastName()); attributes.put("Provider Identifier", String.valueOf(person.getId())); } License license = (License) getEm().createQuery("from License l where l.attachmentId = :id") .setParameter("id", attachment.getId()).getResultList().get(0); attributes.put("In State", license.getIssuingUSState()); attributes.put("PE Document Type", attachment.getType()); attributes.put("License Name", license.getType().getDescription()); String documentName = System.currentTimeMillis() + "_" + attachment.getFilename().toLowerCase() + ".xml"; attributes.put("Document Name", documentName); SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); attributes.put("Document Date", format.format(license.getOriginalIssueDate())); createXML(new File(folder.getAbsolutePath(), documentName), attributes); } catch (FileNotFoundException e) { throw new PortalServiceException("Failed to create file for FileNet", e); } catch (IOException e) { throw new PortalServiceException("Failed to create file for FileNet", e); } catch (SQLException e) { throw new PortalServiceException("Failed to create file for FileNet", e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { // ignore } } if (output != null) { try { output.close(); } catch (IOException e) { // ignore } } } } }
From source file:com.commonsware.android.EMusicDownloader.SingleBook.java
private Bitmap getImageBitmap(String url) { Bitmap bm = null;/*from w w w.j a va 2s. c o m*/ try { URL aURL = new URL(url); HttpURLConnection conn = (HttpURLConnection) aURL.openConnection(); long ifs = 0; ifs = conn.getContentLength(); if (ifs == -1) { conn.disconnect(); conn = (HttpURLConnection) aURL.openConnection(); ifs = conn.getContentLength(); } vArtExists = false; if (ifs > 0) { conn.connect(); InputStream is = conn.getInputStream(); BufferedInputStream bis = new BufferedInputStream(is); bm = BitmapFactory.decodeStream(bis); bis.close(); is.close(); vArtExists = true; } } catch (IOException e) { vArtExists = false; final IOException ef = e; final String urlf = url; } return bm; }
From source file:ejava.projects.edmv.xml.EDmvParserTest.java
public void testParser(String inputFile) throws Exception { log.info("*** testParser:" + inputFile + " ***"); InputStream is = new FileInputStream(inputFile); BufferedInputStream bis = new BufferedInputStream(is); EDmvParser parser = new EDmvParser(Dmv.class, bis); Object object = null;//from w ww.j av a 2 s.com do { object = parser.getObject("Person", "VehicleRegistration"); if (object instanceof Person) { if (((Person) object).getId().contains("1000")) { log.debug("here"); } check((Person) object); } else if (object instanceof VehicleRegistration) { check((VehicleRegistration) object); } else if (object != null) { fail("object of unknown type:" + object); } } while (object != null); bis.close(); }
From source file:edu.ku.brc.specify.plugins.ipadexporter.iPadRepositoryHelper.java
/** * @param urlStr//from w w w . jav a 2 s . c o m * @param tmpFile * @return */ public boolean fillFileFromWeb(final String urlStr, final File tmpFile) { networkConnError = false; try { URL url = new URL(urlStr); InputStream inpStream = url.openStream(); if (inpStream != null) { BufferedInputStream in = new BufferedInputStream(inpStream); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(tmpFile)); do { int numBytes = in.read(bytes); if (numBytes == -1) { break; } bos.write(bytes, 0, numBytes); } while (true); in.close(); bos.close(); return true; } } catch (java.net.UnknownHostException uex) { networkConnError = true; } catch (IOException ex) { ex.printStackTrace(); /*int inx = urlStr.lastIndexOf('/'); File inFile = new File("/Users/rods/workspace/SQLiteExample/"+urlStr.substring(inx)); try { FileUtils.copyFile(inFile, tmpFile); } catch (IOException e) { e.printStackTrace(); }*/ } return false; }
From source file:maltcms.ui.nb.pipelineRunner.options.LocalMaltcmsExecutionPanel.java
private void unzipEntry(ZipFile zipfile, ZipEntry entry, File outputDir) throws IOException { if (entry.isDirectory()) { createDir(new File(outputDir, entry.getName())); return;//www. ja va 2 s .c om } File outputFile = new File(outputDir, entry.getName()); if (!outputFile.getParentFile().exists()) { createDir(outputFile.getParentFile()); } BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry)); try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) { IOUtils.copy(inputStream, outputStream); } finally { inputStream.close(); } }
From source file:de.unirostock.sems.caroweb.Converter.java
private void checkout(HttpServletRequest request, HttpServletResponse response, Path storage, String req) throws ServletException, IOException { Path target = storage.resolve(req).toAbsolutePath().normalize(); if (!target.startsWith(storage) || !Files.exists(target)) { error(request, response, "you're not allowed to download that file."); return;/*from w ww. jav a 2s.c om*/ } try { String mime = target.toString().endsWith("omex") ? "application/zip" : "application/vnd.wf4ever.robundle+zip"; response.reset(); response.setBufferSize(CaRoWebutils.DEFAULT_BUFFER_SIZE); response.setContentType(mime); response.setHeader("Content-Length", String.valueOf(target.toFile().length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + req + "\""); response.setHeader("Expires", CaRoWebutils.downloadDateFormater .format(new Date(System.currentTimeMillis() + CaRoWebutils.CACHE_TIME * 1000))); response.setHeader("Cache-Control", "max-age=" + CaRoWebutils.CACHE_TIME); response.setHeader("Last-Modified", CaRoWebutils.downloadDateFormater .format(new Date(Files.getLastModifiedTime(target).toMillis()))); response.setHeader("ETag", GeneralTools.hash(target + "-" + Files.getLastModifiedTime(target))); BufferedInputStream input = new BufferedInputStream(new FileInputStream(target.toFile()), CaRoWebutils.DEFAULT_BUFFER_SIZE); BufferedOutputStream output = new BufferedOutputStream(response.getOutputStream(), CaRoWebutils.DEFAULT_BUFFER_SIZE); // pass the stream to client byte[] buffer = new byte[CaRoWebutils.DEFAULT_BUFFER_SIZE]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } input.close(); output.close(); return; } catch (IOException e) { // whoops, that's our fault. shouldn't happen. hopefully. LOGGER.error("unable to dump file " + target + " (at least not in an expected form)"); } error(request, response, "couldn't dump file"); }
From source file:it.readbeyond.minstrel.unzipper.Unzipper.java
private String unzip(String inputZip, String destinationDirectory, String mode, JSONObject parameters) throws IOException, JSONException { // store the zip entries to decompress List<String> list = new ArrayList<String>(); // store the zip entries actually decompressed List<String> decompressed = new ArrayList<String>(); // open input zip file File sourceZipFile = new File(inputZip); ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ); // open destination directory, creating it if needed File unzipDestinationDirectory = new File(destinationDirectory); unzipDestinationDirectory.mkdirs();// ww w .j ava2 s. c o m // extract all files if (mode.equals(ARGUMENT_MODE_ALL)) { Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { list.add(zipFileEntries.nextElement().getName()); } } // extract all files except audio and video // (determined by file extension) if (mode.equals(ARGUMENT_MODE_ALL_NON_MEDIA)) { String[] excludeExtensions = JSONArrayToStringArray( parameters.optJSONArray(ARGUMENT_ARGS_EXCLUDE_EXTENSIONS)); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { String name = zipFileEntries.nextElement().getName(); String lower = name.toLowerCase(); if (!isFile(lower, excludeExtensions)) { list.add(name); } } } // extract all small files // maximum size is passed in args parameter // or, if not passed, defaults to const DEFAULT_MAXIMUM_SIZE_FILE if (mode.equals(ARGUMENT_MODE_ALL_SMALL)) { long maximum_size = parameters.optLong(ARGUMENT_ARGS_MAXIMUM_FILE_SIZE, DEFAULT_MAXIMUM_SIZE_FILE); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry ze = zipFileEntries.nextElement(); if (ze.getSize() <= maximum_size) { list.add(ze.getName()); } } } // extract only the requested files if (mode.equals(ARGUMENT_MODE_SELECTED)) { String[] entries = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_ENTRIES)); for (String entry : entries) { ZipEntry ze = zipFile.getEntry(entry); if (ze != null) { list.add(entry); } } } // extract all "structural" files if (mode.equals(ARGUMENT_MODE_ALL_STRUCTURE)) { String[] extensions = JSONArrayToStringArray(parameters.optJSONArray(ARGUMENT_ARGS_EXTENSIONS)); Enumeration<? extends ZipEntry> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { String name = zipFileEntries.nextElement().getName(); String lower = name.toLowerCase(); boolean extract = isFile(lower, extensions); if (extract) { list.add(name); } } } // NOTE list contains only valid zip entries // perform unzip for (String currentEntry : list) { ZipEntry entry = zipFile.getEntry(currentEntry); File destFile = new File(unzipDestinationDirectory, currentEntry); File destinationParent = destFile.getParentFile(); destinationParent.mkdirs(); if (!entry.isDirectory()) { BufferedInputStream is = new BufferedInputStream(zipFile.getInputStream(entry)); int numberOfBytesRead; byte data[] = new byte[BUFFER_SIZE]; FileOutputStream fos = new FileOutputStream(destFile); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE); while ((numberOfBytesRead = is.read(data, 0, BUFFER_SIZE)) > -1) { dest.write(data, 0, numberOfBytesRead); } dest.flush(); dest.close(); is.close(); fos.close(); decompressed.add(currentEntry); } } zipFile.close(); return stringify(decompressed); }