List of usage examples for javax.servlet ServletOutputStream write
public void write(byte b[], int off, int len) throws IOException
len
bytes from the specified byte array starting at offset off
to this output stream. From source file:org.mxhero.engine.plugin.attachmentlink.fileserver.servlet.FileService.java
private void doAction(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ContentService service = null;/*from ww w .j a v a 2 s. c o m*/ InputStream in = null; Long idToSearch = null; String id = req.getParameter("id"); String type = req.getParameter("type"); String email = req.getParameter("email"); MDC.put("message", id); try { if (StringUtils.isEmpty(id) || StringUtils.isEmpty(type)) { log.debug("Error. No params in URL present. Forwarding to error URL page"); req.getRequestDispatcher("/errorParams.jsp").forward(req, resp); } else { ApplicationContext context = WebApplicationContextUtils .getWebApplicationContext(getServletContext()); StandardPBEStringEncryptor encryptor = (StandardPBEStringEncryptor) context.getBean("encryptor"); String decrypt = encryptor.decrypt(id); idToSearch = Long.valueOf(decrypt); log.debug("Trying download to id " + idToSearch); service = context.getBean(ContentService.class); ContentDTO content = service.getContent(idToSearch, email); if (content.hasPublicUrl()) { service.successContent(idToSearch); resp.sendRedirect(content.getPublicUrl()); } else { ServletOutputStream outputStream = resp.getOutputStream(); resp.setContentLength(content.getLength()); resp.setContentType(content.getContentType(type)); if (!content.hasToBeOpen(type)) { resp.setHeader("Content-Type", "application/octet-stream"); resp.addHeader("Content-Disposition", "attachment; filename=\"" + content.getFileName() + "\""); } else { resp.addHeader("Content-Disposition", "filename=\"" + content.getFileName() + "\""); } resp.addHeader("Cache-Control", "no-cache"); in = content.getInputStream(); int BUFF_SIZE = 2048; byte[] buffer = new byte[BUFF_SIZE]; int byteCount = 0; while ((in != null) && (byteCount = in.read(buffer)) != -1) { outputStream.write(buffer, 0, byteCount); } outputStream.flush(); log.debug("Download completed successfuly"); service.successContent(idToSearch); } } } catch (NotAllowedToSeeContentException e) { log.debug("User not more allowed to download content. Forwarding to not allowed page"); req.getRequestDispatcher("/notAllowed.jsp").forward(req, resp); } catch (EmptyResultDataAccessException e) { log.debug("Content not more available. Forwarding to not available page"); req.getRequestDispatcher("/contentNotAvailable.jsp").forward(req, resp); } catch (Exception e) { try { service.failDownload(idToSearch); } catch (Exception e2) { } log.error("Exception: " + e.getClass().getName()); log.error("Message Exception: " + e.getMessage()); log.debug("Error General. Forwarding to page error general"); req.getRequestDispatcher("/error.jsp").forward(req, resp); } finally { if (in != null) { in.close(); } MDC.put("message", id); } }
From source file:org.openmrs.module.DeIdentifiedPatientDataExportModule.api.impl.DeIdentifiedExportServiceImpl.java
public void exportJson(HttpServletResponse response, String ids, Integer pid) { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=patientExportSummary.json"); List<PersonAttributeType> pat = getSavedPersonAttributeList(pid); JSONObject obj = new JSONObject(); JSONObject patientExportSummary = new JSONObject(); JSONArray patients = new JSONArray(); JSONObject patient = new JSONObject(); List<Integer> idsList = multipleIds(ids); PatientService ps = Context.getPatientService(); for (int j = 0; j < idsList.size(); j++) { Patient pt = ps.getPatient(idsList.get(j)); Map patientDemographicData = new HashMap(); for (int i = 0; i < pat.size(); i++) { PersonAttribute pa = pt.getAttribute(pat.get(i)); if (pa != null) patientDemographicData.put(pat.get(i).getName(), pa.getValue()); }/*from ww w .ja v a2 s . c o m*/ patientDemographicData.put("dob", pt.getBirthdate().toString()); pt = setRandomPatientNames(pt); patientDemographicData.put("name", pt.getGivenName().toString() + " " + pt.getMiddleName().toString() + " " + pt.getFamilyName().toString()); List<Obs> obs1 = new ArrayList<Obs>(); Context.clearSession(); ObsService obsService = Context.getObsService(); List<Obs> ob = getOriginalObsList(pt, obsService); obs1 = getEncountersOfPatient(pt, ob, pid); //New obs list - updated List<ConceptSource> cs = getConceptMapping(obs1); for (int i = 0; i < obs1.size(); i++) { Map encounters = new HashMap(); JSONArray en = new JSONArray(); JSONObject enObj = new JSONObject(); en.add(enObj); encounters.put("observations", en); JSONObject conceptObj = new JSONObject(); JSONObject valueObj = new JSONObject(); JSONObject vObj = new JSONObject(); en.add(vObj); conceptObj.put("concept", enObj); valueObj.put("value", vObj); for (int k = 0; k < cs.size(); k++) { if (obs1.get(i).getValueCoded() != null) { vObj.put("valueCoded", obs1.get(i).getValueCoded().toString()); } else if (obs1.get(i).getValueBoolean() != null) { vObj.put("valueCoded", obs1.get(i).getValueBoolean().toString()); } enObj.put("conceptSourceId", cs.get(k).getHl7Code().toString()); enObj.put("conceptSource", cs.get(k).getName().toString()); } enObj.put("conceptID", obs1.get(i).getConcept().toString()); encounters.put("encounterDate", obs1.get(i).getEncounter().getEncounterDatetime().toLocaleString().toString()); encounters.put("encounterLocation", obs1.get(i).getLocation().getAddress1().toString()); patients.add(encounters); } patients.add(patientDemographicData); } patientExportSummary.put("patients", patients); obj.put("patientExportSummary", patientExportSummary); try { FileWriter file = new FileWriter("c:\\test1.json"); file.write(obj.toJSONString()); file.flush(); file.close(); File f = new File("c:\\test1.json"); FileInputStream fileIn = new FileInputStream(f); ServletOutputStream out = response.getOutputStream(); byte[] outputByte = new byte[4096]; //copy binary contect to output stream while (fileIn.read(outputByte, 0, 4096) != -1) { out.write(outputByte, 0, 4096); } fileIn.close(); out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { initialize(request);// w ww.j a va 2 s. c o m int userId = 0; int groupId = 0; String user = ""; String context = request.getContextPath(); String url = request.getPathInfo(); HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } Credential credential = null; try { //On initialise le dataProvider Connection c = null; if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } // ===================================================================================== boolean trace = false; StringBuffer outTrace = new StringBuffer(); StringBuffer outPrint = new StringBuffer(); String logFName = null; response.setCharacterEncoding("UTF-8"); System.out.println("FileServlet::doGet"); try { // ====== URI : /resources/file[/{lang}]/{context-id} // ====== PathInfo: /resources/file[/{uuid}?lang={fr|en}&size={S|L}] pathInfo // String uri = request.getRequestURI(); String[] token = url.split("/"); String uuid = token[1]; //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile:"+request.getRemoteAddr()+":"+uri); /// FIXME: Passe la scurit si la source provient de localhost, il faudrait un change afin de s'assurer que n'importe quel servlet ne puisse y accder String sourceip = request.getRemoteAddr(); System.out.println("IP: " + sourceip); /// Vrification des droits d'accs // TODO: Might be something special with proxy and export/PDF, to investigate if (!ourIPs.contains(sourceip)) { if (userId == 0) throw new RestWebApplicationException(Status.FORBIDDEN, ""); if (!credential.hasNodeRight(userId, groupId, uuid, Credential.READ)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); //throw new Exception("L'utilisateur userId="+userId+" n'a pas le droit READ sur le noeud "+nodeUuid); } } else // Si la requte est locale et qu'il n'y a pas de session, on ignore la vrification { System.out.println("IP OK: bypass"); } /// On rcupre le noeud de la ressource pour retrouver le lien String data = dataProvider.getResNode(uuid, userId, groupId); // javax.servlet.http.HttpSession session = request.getSession(true); //==================================================== //String ppath = session.getServletContext().getRealPath("/"); //logFName = ppath +"logs/logNode.txt"; //==================================================== String size = request.getParameter("size"); if (size == null) size = "S"; String lang = request.getParameter("lang"); if (lang == null) { lang = "fr"; } /* String nodeUuid = uri.substring(uri.lastIndexOf("/")+1); if (uri.lastIndexOf("/")>uri.indexOf("file/")+6) { // -- file/ = 5 carac. -- lang = uri.substring(uri.indexOf("file/")+5,uri.lastIndexOf("/")); } //*/ String ref = request.getHeader("referer"); /// Parse les donnes DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader("<node>" + data + "</node>")); Document doc = documentBuilder.parse(is); DOMImplementationLS impl = (DOMImplementationLS) doc.getImplementation().getFeature("LS", "3.0"); LSSerializer serial = impl.createLSSerializer(); serial.getDomConfig().setParameter("xml-declaration", false); /// Trouve le bon noeud XPath xPath = XPathFactory.newInstance().newXPath(); /// Either we have a fileid per language String filterRes = "//fileid[@lang='" + lang + "']"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); String resolve = ""; if (nodelist.getLength() != 0) { Element fileNode = (Element) nodelist.item(0); resolve = fileNode.getTextContent(); } /// Or just a single one shared if ("".equals(resolve)) { response.setStatus(404); return; } String filterName = "//filename[@lang='" + lang + "']"; NodeList textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filename = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); filename = fileNode.getTextContent(); } String filterType = "//type[@lang='" + lang + "']"; textList = (NodeList) xPath.compile(filterType).evaluate(doc, XPathConstants.NODESET); String type = ""; if (textList.getLength() != 0) { Element fileNode = (Element) textList.item(0); type = fileNode.getTextContent(); } /* String filterSize = "//size[@lang='"+lang+"']"; textList = (NodeList) xPath.compile(filterName).evaluate(doc, XPathConstants.NODESET); String filesize = ""; if( textList.getLength() != 0 ) { Element fileNode = (Element) textList.item(0); filesize = fileNode.getTextContent(); } //*/ System.out.println("!!! RESOLVE: " + resolve); /// Envoie de la requte au servlet de fichiers // http://localhost:8080/MiniRestFileServer/user/claudecoulombe/file/a8e0f07f-671c-4f6a-be6c-9dba12c519cf/ptype/sql /// TODO: Ne plus avoir besoin du switch String urlTarget = "http://" + server + "/" + resolve; // String urlTarget = "http://"+ server + "/user/" + resolve +"/"+ lang + "/ptype/fs"; HttpURLConnection connection = CreateConnection(urlTarget, request); connection.connect(); InputStream input = connection.getInputStream(); String sizeComplete = connection.getHeaderField("Content-Length"); int completeSize = Integer.parseInt(sizeComplete); response.setContentLength(completeSize); response.setContentType(type); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); ServletOutputStream output = response.getOutputStream(); byte[] buffer = new byte[completeSize]; int totalRead = 0; int bytesRead = -1; while ((bytesRead = input.read(buffer, 0, completeSize)) != -1 || totalRead < completeSize) { output.write(buffer, 0, bytesRead); totalRead += bytesRead; } // IOUtils.copy(input, output); // IOUtils.closeQuietly(output); output.flush(); output.close(); input.close(); connection.disconnect(); } catch (RestWebApplicationException e) { logger.error(e.getMessage()); e.printStackTrace(); } catch (Exception e) { logger.error(e.toString() + " -> " + e.getLocalizedMessage()); e.printStackTrace(); //wadbackend.WadUtilities.appendlogfile(logFName, "GETfile: error"+e); } finally { try { dataProvider.disconnect(); } catch (Exception e) { ServletOutputStream out = response.getOutputStream(); out.println("Erreur dans doGet: " + e); out.close(); } } }
From source file:com.spring.tutorial.controllers.DefaultController.java
@RequestMapping(value = "/files/{id}", method = RequestMethod.GET) public String getFile(@PathVariable("id") String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws IOException, Exception { String _id = request.getSession().getAttribute("id").toString(); MongoData data = new MongoData(); GridFS collection = new GridFS(data.getDB(), _id + "_files"); BasicDBObject query = new BasicDBObject(); query.put("_id", new ObjectId(id)); GridFSDBFile file = collection.findOne(query); DBCollection metaFileCollection = data.getDB().getCollection(_id + "_files_meta"); BasicDBObject metaQuery = new BasicDBObject(); metaQuery.put("file-id", new ObjectId(id)); DBObject metaFileDoc = metaFileCollection.findOne(metaQuery); MongoFile metaFile = new MongoFile(metaFileDoc); ServletOutputStream out = response.getOutputStream(); String mimeType = metaFile.getType(); response.setContentType(mimeType);/* w w w . j a v a 2s .com*/ response.setContentLength((int) file.getLength()); String headerKey = "Content-Disposition"; File f = File.createTempFile(file.getFilename(), metaFile.getType().substring(metaFile.getType().indexOf("/") + 1)); String headerValue = String.format("attachment; filename=\"%s\"", file.getFilename()); response.setHeader(headerKey, headerValue); file.writeTo(f); FileInputStream inputStream = new FileInputStream(f); byte[] buffer = new byte[4096]; int bytesRead = -1; while (inputStream.read(buffer, 0, 4096) != -1) { out.write(buffer, 0, 4096); } inputStream.close(); out.flush(); out.close(); return "mydrive/temp"; }
From source file:br.org.indt.ndg.servlets.OpenRosaManagement.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { m_openRosaBD.setPortAndAddress(SystemProperties.getServerAddress()); String action = request.getParameter(ACTION_PARAM); if (SET_AVAILABLE_FOR_USER.equals(action)) { String selectedImei = request.getParameter(SELECTED_IMEI_PARAM); String[] selectedSurveyIds = request.getParameterValues(SELECTED_SURVEY_ID_PARAM); if (selectedImei != null && selectedSurveyIds != null) { log.info("IMEI: " + selectedImei); for (int i = 0; i < selectedSurveyIds.length; i++) { log.info("Survey id:" + selectedSurveyIds[i]); }/* w w w . j a va2s. com*/ } boolean result = m_openRosaBD.makeSurveysAvailableForImei(selectedImei, selectedSurveyIds); request.setAttribute(RESULT_ATTR, result); dispatchSurveysForUserSelectionPage(request, response); } else if (EXPORT_RESULTS_FOR_USER.equals(action)) { ServletOutputStream outputStream = null; FileInputStream fileInputStream = null; DataInputStream dataInputStream = null; File file = null; try { String zipFilename = m_openRosaBD.exportZippedResultsForUser("223344556677"); file = new File(zipFilename); int length = 0; outputStream = response.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType("application/octet-stream"); response.setContentType(mimetype); response.setContentLength((int) file.length()); response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFilename + "\""); byte[] bbuf = new byte[1024]; fileInputStream = new FileInputStream(file); dataInputStream = new DataInputStream(fileInputStream); while ((dataInputStream != null) && ((length = dataInputStream.read(bbuf)) != -1)) { outputStream.write(bbuf, 0, length); } outputStream.flush(); } catch (FileNotFoundException ex) { ex.printStackTrace(); } finally { try { if (fileInputStream != null) fileInputStream.close(); if (dataInputStream != null) dataInputStream.close(); if (fileInputStream != null) fileInputStream.close(); } catch (IOException ex) { ex.printStackTrace(); } file.delete(); } } }
From source file:DisplayBlobServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Blob photo = null;//from ww w. j a v a 2 s. co m Connection conn = null; Statement stmt = null; ResultSet rs = null; String query = "select photo from MyPictures where id = '001'"; ServletOutputStream out = response.getOutputStream(); try { conn = getHSQLConnection(); } catch (Exception e) { response.setContentType("text/html"); out.println("<html><head><title>Person Photo</title></head>"); out.println("<body><h1>Database Connection Problem.</h1></body></html>"); return; } try { stmt = conn.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { photo = rs.getBlob(1); } else { response.setContentType("text/html"); out.println("<html><head><title>Person Photo</title></head>"); out.println("<body><h1>No photo found for id= 001 </h1></body></html>"); return; } response.setContentType("image/gif"); InputStream in = photo.getBinaryStream(); int length = (int) photo.length(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while ((length = in.read(buffer)) != -1) { System.out.println("writing " + length + " bytes"); out.write(buffer, 0, length); } in.close(); out.flush(); } catch (SQLException e) { response.setContentType("text/html"); out.println("<html><head><title>Error: Person Photo</title></head>"); out.println("<body><h1>Error=" + e.getMessage() + "</h1></body></html>"); return; } finally { try { rs.close(); stmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:de.sub.goobi.metadaten.FileManipulation.java
/** * Download file./*from w w w . j av a 2 s .c o m*/ */ public void downloadFile() { URI downloadFile = null; int imageOrder = Integer.parseInt(imageSelection); DocStruct page = metadataBean.getDigitalDocument().getPhysicalDocStruct().getAllChildren().get(imageOrder); String imagename = page.getImageName(); String filenamePrefix = imagename.substring(0, imagename.lastIndexOf(".")); URI processSubTypeURI = serviceManager.getFileService().getProcessSubTypeURI(metadataBean.getProcess(), ProcessSubType.IMAGE, currentFolder); ArrayList<URI> filesInFolder = fileService.getSubUris(processSubTypeURI); for (URI currentFile : filesInFolder) { String currentFileName = fileService.getFileName(currentFile); String currentFileNamePrefix = currentFileName.substring(0, currentFileName.lastIndexOf(".")); if (filenamePrefix.equals(currentFileNamePrefix)) { downloadFile = currentFile; break; } } if (downloadFile == null || !fileService.fileExist(downloadFile)) { List<String> paramList = new ArrayList<>(); // paramList.add(metadataBean.getMyProzess().getTitel()); paramList.add(filenamePrefix); paramList.add(currentFolder); Helper.setFehlerMeldung(Helper.getTranslation("MetsEditorMissingFile", paramList)); return; } FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); InputStream in = null; ServletOutputStream out = null; try { String fileName = fileService.getFileName(downloadFile); ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); in = fileService.read(downloadFile); out = response.getOutputStream(); byte[] buffer = new byte[4096]; int length; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } out.flush(); } catch (IOException e) { logger.error("IOException while exporting run note", e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error(e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.error(e); } } } facesContext.responseComplete(); } }
From source file:org.apache.wookie.WidgetAdminServlet.java
private void doDownload(HttpServletRequest req, HttpServletResponse resp, File f, String original_filename) throws IOException { int BUFSIZE = 1024; // File f = new File(filename); int length = 0; ServletOutputStream op = resp.getOutputStream(); ServletContext context = getServletConfig().getServletContext(); String mimetype = context.getMimeType(f.getAbsolutePath()); //// ww w .ja va 2 s . com // Set the response and go! // // resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); resp.setContentLength((int) f.length()); resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\""); // // Stream to the requester. // byte[] bbuf = new byte[BUFSIZE]; DataInputStream in = new DataInputStream(new FileInputStream(f)); while ((in != null) && ((length = in.read(bbuf)) != -1)) { op.write(bbuf, 0, length); } in.close(); op.flush(); op.close(); }
From source file:org.agnitas.web.NewImportWizardAction.java
/** * Method transfers given file to action response (for user to download) * * @param response action response//from w w w. j a va2 s .co m * @param errors errors * @param outfile file to transfer * @throws IOException exceptions that can occur while working with IO */ private void transferFile(HttpServletResponse response, ActionMessages errors, File outfile) throws IOException { if (outfile != null) { byte bytes[] = new byte[16384]; int len; FileInputStream instream = new FileInputStream(outfile); try { if (outfile.getName().endsWith(".zip")) { response.setContentType("application/zip"); } else if (outfile.getName().endsWith(".txt")) { response.setContentType("application/txt"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + outfile.getName() + "\";"); response.setContentLength((int) outfile.length()); @SuppressWarnings("resource") // Do not close this stream, it's managed by the servlet container ServletOutputStream ostream = response.getOutputStream(); while ((len = instream.read(bytes)) != -1) { ostream.write(bytes, 0, len); } } finally { instream.close(); } } else { errors.add("global", new ActionMessage("error.export.file_not_ready")); } }
From source file:org.etudes.tool.melete.BookmarkPage.java
/** * writes the text file to browser/*from w ww. j av a2 s . c o m*/ * * @param file - * text file to download * @throws Exception */ private void download(File file) throws Exception { FileInputStream fis = null; ServletOutputStream out = null; try { String disposition = "attachment; filename=\"" + file.getName() + "\""; fis = new FileInputStream(file); FacesContext cxt = FacesContext.getCurrentInstance(); ExternalContext context = cxt.getExternalContext(); HttpServletResponse response = (HttpServletResponse) context.getResponse(); response.setContentType("application/text"); // application/text response.addHeader("Content-Disposition", disposition); // Contributed by Diego for ME-233 response.setHeader("Pragma", "public"); response.setHeader("Cache-Control", "public, post-check=0, must-revalidate, pre-check=0"); out = response.getOutputStream(); int len; byte buf[] = new byte[102400]; while ((len = fis.read(buf)) > 0) { out.write(buf, 0, len); } out.flush(); } catch (IOException e) { throw e; } finally { try { if (out != null) out.close(); } catch (IOException e1) { } try { if (fis != null) fis.close(); } catch (IOException e2) { } } }