List of usage examples for javax.servlet ServletOutputStream flush
public void flush() throws IOException
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]); }/*from w ww. j av a 2 s .co m*/ } 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:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.erasmus.ErasmusIndividualCandidacyProcessPublicDA.java
public ActionForward retrieveApprovedLearningAgreement(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final ApprovedLearningAgreementDocumentFile file = getDomainObject(request, "agreementId"); final String hash = request.getParameter("hash"); final MobilityIndividualApplicationProcess process = file.getProcess(); final DegreeOfficePublicCandidacyHashCode candidacyHashCode = process.getCandidacyHashCode(); if (candidacyHashCode.getValue().equals(hash)) { final byte[] content = file.getContent(); response.setContentLength(content.length); response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + file.getFilename()); final ServletOutputStream writer = response.getOutputStream(); writer.write(content);// www .j a v a 2 s . c om writer.flush(); writer.close(); response.flushBuffer(); } return null; }
From source file:com.haulmont.cuba.restapi.RestFileDownloadController.java
private void writeResponse(HttpServletResponse response, UserSession userSession, FileDescriptor fd) throws IOException { InputStream is = null;//from w ww. j a v a 2 s . c o m ServletOutputStream os = response.getOutputStream(); try { Object context = serverSelector.initContext(); String selectedUrl = serverSelector.getUrl(context); if (selectedUrl == null) { log.debug("Unable to download file: no available server URLs"); error(response); } while (selectedUrl != null) { String url = selectedUrl + fileDownloadContext + "?s=" + userSession.getId() + "&f=" + fd.getId().toString(); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try { HttpResponse httpResponse = httpClient.execute(httpGet); int httpStatus = httpResponse.getStatusLine().getStatusCode(); if (httpStatus == HttpStatus.SC_OK) { HttpEntity httpEntity = httpResponse.getEntity(); if (httpEntity != null) { is = httpEntity.getContent(); IOUtils.copy(is, os); os.flush(); break; } else { log.debug("Unable to download file from " + url + "\nHttpEntity is null"); selectedUrl = failAndGetNextUrl(context, response); } } else { log.debug("Unable to download file from " + url + "\n" + httpResponse.getStatusLine()); selectedUrl = failAndGetNextUrl(context, response); } } catch (IOException ex) { log.debug("Unable to download file from " + url + "\n" + ex); selectedUrl = failAndGetNextUrl(context, response); } finally { IOUtils.closeQuietly(is); httpClient.getConnectionManager().shutdown(); } } } finally { IOUtils.closeQuietly(os); } }
From source file:org.extensiblecatalog.ncip.v2.responder.implprof1.NCIPServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { long respTotalStartTime = System.currentTimeMillis(); String serviceName = "Unknown"; try {/*from w w w . j a v a 2 s .c o m*/ response.setContentType("application/xml; charset=\"utf-8\""); // Note: Statements that might throw exceptions are wrapped in individual try/catch blocks, allowing us // to provide very specific error messages. ServletInputStream inputStream = null; try { inputStream = request.getInputStream(); } catch (IOException e) { returnException(response, "Exception getting ServletInputStream from the HttpServletRequest.", e); } ServiceContext serviceContext = null; try { serviceContext = serviceValidator.getInitialServiceContext(); } catch (ToolkitException e) { returnException(response, "Exception creating initial service context.", e); } NCIPInitiationData initiationData = null; try { initiationData = translator.createInitiationData(serviceContext, inputStream); } catch (ServiceException e) { returnException(response, "Exception creating the NCIPInitiationData object from the servlet's input stream.", e); } catch (ValidationException e) { returnValidationProblem(response, e); } long initPerfSvcStartTime = System.currentTimeMillis(); NCIPResponseData responseData = messageHandler.performService(initiationData, serviceContext); long initPerfSvcEndTime = System.currentTimeMillis(); serviceName = ServiceHelper.getServiceName(initiationData); statisticsBean.record(initPerfSvcStartTime, initPerfSvcEndTime, StatisticsBean.RESPONDER_PERFORM_SERVICE_LABELS, serviceName); InputStream responseMsgInputStream = null; try { responseMsgInputStream = translator.createResponseMessageStream(serviceContext, responseData); } catch (ServiceException e) { returnException(response, "Exception creating the InputStream from the NCIPResponseData object.", e); } catch (ValidationException e) { returnException(response, "Exception creating the InputStream from the NCIPResponseData object.", e); } int bytesAvailable = 0; if (responseMsgInputStream != null) { try { bytesAvailable = responseMsgInputStream.available(); } catch (IOException e) { returnException(response, "Exception getting the count of available bytes from the response message's InputStream.", e); } } int bytesRead = 0; if (bytesAvailable != 0) { byte[] responseMsgBytes = new byte[bytesAvailable]; try { bytesRead = responseMsgInputStream.read(responseMsgBytes, 0, bytesAvailable); } catch (IOException e) { returnException(response, "Exception reading bytes from the response message's InputStream.", e); } if (bytesRead != bytesAvailable) { returnProblem(response, "Bytes read from the response message's InputStream (" + bytesRead + ") are not the same as the number available (" + bytesAvailable + ")."); } else { response.setContentLength(responseMsgBytes.length); // TODO: What about a try/finally that closes the output stream - is that needed? ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); } catch (IOException e) { returnException(response, "Exception getting the HttpServletResponse's OutputStream.", e); } try { outputStream.write(responseMsgBytes); } catch (IOException e) { returnException(response, "Exception writing the NCIP response message to the HttpServletResponse's OutputStream.", e); } try { outputStream.flush(); } catch (IOException e) { returnException(response, "Exception flushing the HttpServletResponse's OutputStream.", e); } } } } catch (Exception e) { returnException(response, "Uncaught exception.", e); } long respTotalEndTime = System.currentTimeMillis(); statisticsBean.record(respTotalStartTime, respTotalEndTime, StatisticsBean.RESPONDER_TOTAL_LABELS, serviceName); }
From source file:com.gae.ImageUpServlet.java
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); //ReturnValue value = new ReturnValue(); MemoryFileItemFactory factory = new MemoryFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); resp.setContentType("image/jpeg"); ServletOutputStream out = resp.getOutputStream(); try {/* w w w.ja v a2s.c o m*/ List<FileItem> list = upload.parseRequest(req); //FileItem list = upload.parseRequest(req); for (FileItem item : list) { if (!(item.isFormField())) { filename = item.getName(); if (filename != null && !"".equals(filename)) { int size = (int) item.getSize(); byte[] data = new byte[size]; InputStream in = item.getInputStream(); in.read(data); ImagesService imagesService = ImagesServiceFactory.getImagesService(); Image newImage = ImagesServiceFactory.makeImage(data); byte[] newImageData = newImage.getImageData(); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), filename.split(".")[0]); out.write(newImageData); out.flush(); DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(kind, skey); Blob blobImage = new Blob(newImageData); DirectBeans_textjson dbeans = new DirectBeans_textjson(); /* ?Date? */ //Entity entity = dbeans.setentity("add", kind, true, key, id, val); //ReturnValue value = dbeans.Called.setentity("add", kind, true, key, id, val); //Entity entity = value.entity; //DirectBeans.ReturnValue value = new DirectBeans.ReturnValue(); DirectBeans_textjson.entityVal eval = dbeans.setentity("add", kind, true, key, id, val); Entity entity = eval.entity; /* ?Date */ //for(int i=0; i<id.length; i++ ){ // if(id[i].equals("image")){ // //filetitle = val[i]; // //imgkey = KeyFactory.createKey(Imagedat.class.getSimpleName(), val[i]); // } //} entity.setProperty("image", blobImage); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd:HHmmss"); sdf.setTimeZone(TimeZone.getTimeZone("JST")); entity.setProperty("moddate", sdf.format(date)); //DatastoreService ds = DatastoreServiceFactory.getDatastoreService(); ds.put(entity); out.println("? KEY:" + key); } } } } catch (FileUploadException e) { e.printStackTrace(); } finally { if (out != null) { out.close(); } } }
From source file:DisplayBlobServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Blob photo = null;//from w w w.j a va 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:annis.gui.servlets.BinaryServlet.java
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { Map<String, String[]> binaryParameter = request.getParameterMap(); String toplevelCorpusName = binaryParameter.get("toplevelCorpusName")[0]; String documentName = binaryParameter.get("documentName")[0]; String mimeType = binaryParameter.get("mime")[0]; try {/* www. j a va 2 s . c o m*/ ServletOutputStream out = response.getOutputStream(); String range = request.getHeader("Range"); HttpSession session = request.getSession(); Object annisServiceURLObject = session.getAttribute(AnnisBaseUI.WEBSERVICEURL_KEY); if (annisServiceURLObject == null || !(annisServiceURLObject instanceof String)) { throw new ServletException("AnnisWebService.URL was not set as init parameter in web.xml"); } String annisServiceURL = (String) annisServiceURLObject; WebResource annisRes = Helper.getAnnisWebResource(annisServiceURL, (AnnisUser) session.getAttribute(AnnisBaseUI.USER_KEY)); WebResource binaryRes = annisRes.path("query").path("corpora") .path(URLEncoder.encode(toplevelCorpusName, "UTF-8")) .path(URLEncoder.encode(documentName, "UTF-8")).path("binary").queryParam("mime", mimeType); if (range != null) { responseStatus206(binaryRes, mimeType, out, response, range); } else { responseStatus200(binaryRes, mimeType, out, response); } out.flush(); } catch (IOException ex) { log.debug("IOException in BinaryServlet", ex); } catch (ClientHandlerException ex) { log.error(null, ex); response.setStatus(500); } catch (UniformInterfaceException ex) { log.error(null, ex); response.setStatus(500); } }
From source file:org.kitodo.services.ProcessService.java
/** * Download docket./*from www .jav a 2s .c om*/ * * @param process object * @return empty string? */ public String downloadDocket(Process process) { if (myLogger.isDebugEnabled()) { myLogger.debug("generate docket for process " + process.getId()); } String rootPath = ConfigMain.getParameter("xsltFolder"); SafeFile xsltFile = new SafeFile(rootPath, "docket.xsl"); if (process.getDocket() != null) { xsltFile = new SafeFile(rootPath, process.getDocket().getFile()); if (!xsltFile.exists()) { Helper.setFehlerMeldung("docketMissing"); return ""; } } FacesContext facesContext = FacesContext.getCurrentInstance(); if (!facesContext.getResponseComplete()) { HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); String fileName = process.getTitle() + ".pdf"; ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext(); String contentType = servletContext.getMimeType(fileName); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); // write run note to servlet output stream try { ServletOutputStream out = response.getOutputStream(); ExportDocket ern = new ExportDocket(); ern.startExport(process, out, xsltFile.getAbsolutePath()); out.flush(); facesContext.responseComplete(); } catch (Exception e) { Helper.setFehlerMeldung("Exception while exporting run note.", e.getMessage()); response.reset(); } } return ""; }
From source file:com.portfolio.data.attachment.FileServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { initialize(request);/*from w w w . j a va 2s.co 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(); } } }