List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:org.geosdi.geoplatform.gui.server.UploadServlet.java
@SuppressWarnings("unchecked") @Override//from www . j ava 2 s .c om public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, GeoPlatformException { // logger.info("Query String: " + req.getQueryString()); // while (req.getParameterMap().keySet().iterator().hasNext()) { // logger.info("Parameter next: " + req.getParameterMap().keySet().iterator().next()); // } // while (req.getParameterNames().hasMoreElements()) { // logger.info("Parameter name: " + req.getParameterNames().nextElement()); // } // while (req.getAttributeNames().hasMoreElements()) { // logger.info("Attribute name: " + req.getAttributeNames().nextElement()); // } String workspace = null; HttpSession session = req.getSession(); Object accountObj = session.getAttribute(SessionProperty.LOGGED_ACCOUNT.toString()); GPAccount account; if (accountObj != null && accountObj instanceof GPAccount) { account = (GPAccount) accountObj; } else { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Session Timeout"); return; } receivedAssertion = (AssertionImpl) session.getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION); // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler /* * Set the size threshold, above which content will be stored on * disk. */ factory.setSizeThreshold(1 * 1024 * 1024); //1 MB ServletFileUpload upload = new ServletFileUpload(factory); File uploadedFile = null; // Parse the request try { List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) { logger.debug("Analyzing item field name: " + item.getFieldName()); logger.debug("Analyzing item string: " + item.getString()); //Ricevo parametro if (item.getFieldName().equals("workspace")) { workspace = item.getString(); logger.debug("Found workspace in request param: " + workspace); } } else { String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } try { uploadedFile = this.publisherFileUtils.createFileWithUniqueName(fileName); item.write(uploadedFile); } catch (Exception ex) { logger.info("ERRORE : " + ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred writing the file: " + ex.getMessage()); throw new GeoPlatformException("Error on uploading shape."); } resp.setStatus(HttpServletResponse.SC_CREATED); resp.flushBuffer(); } } List<InfoPreview> infoPreviews = this.manageUploadedFilePreview(uploadedFile, session.getId(), account.getNaturalID(), workspace); resp.setContentType("text/x-json;charset=UTF-8"); resp.setHeader("Cache-Control", "no-cache"); String result = PublisherFileUtils.generateJSONObjects(infoPreviews); resp.getWriter().write(result); //geoPlatformPublishClient.publish("previews", "dataTest", infoPreview.getDataStoreName()); } catch (FileUploadException ex) { logger.info("ERRORE : " + ex); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred creating the file: " + ex.getMessage()); throw new GeoPlatformException("Error on uploading shape."); } finally { uploadedFile.delete(); resp.getWriter().close(); } } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:com.rr.familyPlanning.ui.adhoc.adhocController.java
@RequestMapping(value = "/DLReport", method = { RequestMethod.GET }) public void DLReport(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletResponse response) throws Exception { Integer reportRequestId = 0;/* w ww . ja v a 2 s.c o m*/ adhocView view = new adhocView(); boolean canViewReport = false; User userDetails = new User(); if (session.getAttribute("userDetails") != null) { userDetails = (User) session.getAttribute("userDetails"); //1 decrpt and get the reportId decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); reportRequestId = Integer.parseInt(result[0].substring(4)); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Accessed Adhoc Report link"); view.setSystemUserId(userDetails.getId()); adhocmanager.saveAdhocView(view); //now we get the report details adhocRequests request = adhocmanager.getAdhocRequestById(reportRequestId); if (request != null) { //we check permission and program if (userDetails.getRoleId() == 3 && request.getSystemUserId() == userDetails.getId() && request.getProgramId() == programId) { canViewReport = true; } else if (userDetails.getRoleId() != 3 && request.getProgramId() == programId) { canViewReport = true; } } //we log them, grab report for them to download //if report doesn't exist we send them back to list with a message if (!canViewReport) { hasPermission = 2; view = new adhocView(); view.setAdhocRequestId(reportRequestId); view.setSystemUserId(userDetails.getId()); view.setAdhocAction("User does not have permission to view adhoc report"); adhocmanager.saveAdhocView(view); throw new Exception("user does not have permission to view adhoc report - " + reportRequestId); } else { //generate the report for user to download //need to get report path String filePath = adhocmanager.getReportPath(programId); String fileName = request.getReportFileName(); try { File f = new File(filePath + fileName); if (!f.exists()) { throw new Exception("Error with File " + filePath + fileName); } } catch (Exception e) { throw new Exception("File does not exists " + filePath + fileName); } try { // get your file as InputStream InputStream is = new FileInputStream(filePath + fileName); // copy it to response's OutputStream String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); view = new adhocView(); view.setSystemUserId(userDetails.getId()); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Viewed Report"); adhocmanager.saveAdhocView(view); //update status if (request.getStatusId() == 3) { request.setStatusId(4); adhocmanager.updateAdHocRequests(request); } /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/DLReport"); ual.setRequestMethod("GET"); ual.setMethodAccessed("DLReport"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(reportRequestId); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); } catch (IOException ex) { ex.printStackTrace(); System.out.println("Error writing file to output stream. Filename was '{}'" + fileName + ex); throw new Exception("Error with File " + filePath + fileName + ex); } } } else { //someone somehow got to this link, we just log //we log who is accessing //now we have report id, we check to see which program it belongs to and if the user has permission hasPermission = 2; /** Log Here **/ userActivityLog ual = new userActivityLog(); ual.setSystemUserId(userDetails.getId()); ual.setMapping("/DLReport"); ual.setRequestMethod("GET"); ual.setMethodAccessed("DLReport"); ual.setModuleId(moduleId); ual.setProgramId(programId); ual.setRelatedId(reportRequestId); ual.setRelatedIdCol("adhocRequestId"); usermanager.saveUserActivityLog(ual); view.setAdhocRequestId(reportRequestId); view.setAdhocAction("Accessed adhoc report link - no user session found"); adhocmanager.saveAdhocView(view); throw new Exception("invalid adhoc report download - " + reportRequestId); } }
From source file:io.apiman.manager.ui.server.servlets.ApiManagerProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *//*from ww w . jav a 2 s . c om*/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { StringBuilder url = new StringBuilder(); String endpoint = getConfig().getManagementApiEndpoint(); if (endpoint == null) { endpoint = getDefaultEndpoint(req); } url.append(endpoint); if (!url.toString().endsWith("/")) { //$NON-NLS-1$ url.append('/'); } String pathInfo = req.getPathInfo(); if (pathInfo != null && pathInfo.startsWith("/")) { //$NON-NLS-1$ url.append(pathInfo.substring(1)); } else { url.append(pathInfo); } String authHeaderValue = null; ApiAuthType authType = getConfig().getManagementApiAuthType(); switch (authType) { case basic: { String username = getConfig().getManagementApiAuthUsername(); String password = getConfig().getManagementApiAuthPassword(); String encoded = base64Encode(username + ":" + password); //$NON-NLS-1$ authHeaderValue = "Basic " + encoded; //$NON-NLS-1$ break; } case authToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); authHeaderValue = "AUTH-TOKEN " + token; //$NON-NLS-1$ break; } case bearerToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); authHeaderValue = "Bearer " + token; //$NON-NLS-1$ break; } case samlBearerToken: { ITokenGenerator tokenGenerator = getTokenGenerator(); BearerTokenCredentialsBean creds = tokenGenerator.generateToken(req); String token = creds.getToken(); // TODO base64 decode the token, then re-encode it with "SAML-BEARER-TOKEN:" authHeaderValue = "Basic SAML-BEARER-TOKEN:" + token; //$NON-NLS-1$ break; } } URL remoteUrl = new URL(url.toString()); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); InputStream remoteIS = null; OutputStream responseOS = null; try { if (authHeaderValue != null) { remoteConn.setRequestProperty("Authorization", authHeaderValue); //$NON-NLS-1$ } remoteConn.connect(); Map<String, List<String>> headerFields = remoteConn.getHeaderFields(); for (String headerName : headerFields.keySet()) { if (headerName == null) { continue; } if (EXCLUDE_HEADERS.contains(headerName)) { continue; } String headerValue = remoteConn.getHeaderField(headerName); resp.setHeader(headerName, headerValue); if (url.toString().contains("apiregistry")) { //$NON-NLS-1$ String type = "json"; //$NON-NLS-1$ if (url.toString().endsWith("xml")) { //$NON-NLS-1$ type = "xml"; //$NON-NLS-1$ } resp.setHeader("Content-Disposition", "attachment; filename=api-registry." + type); //$NON-NLS-1$ //$NON-NLS-2$ } } resp.setHeader("Cache-control", "no-cache, no-store, must-revalidate"); //$NON-NLS-1$ //$NON-NLS-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:org.n52.ar.layar.LayarServlet.java
/** * http://layar.com/documentation/browser/api/getpois-request/ */// w w w .ja va2s. c o m @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String userAgent = request.getHeader("User-agent"); log.debug("User-agent={}", userAgent); /* * mandatory: */ String userId = request.getParameter("userId"); String version = request.getParameter("version"); String countryCode = request.getParameter("countryCode"); String lang = request.getParameter("lang"); String action = request.getParameter("action"); if (action == null) { // response.sendError(HttpServletResponse.SC_BAD_REQUEST, // "Missing parameter 'action'"); // return; log.debug("No action given."); } String latParam = request.getParameter("lat"); if (latParam == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'lat'"); return; } String lonParam = request.getParameter("lon"); if (lonParam == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'lon'"); return; } String radiusParam = request.getParameter("radius"); if (radiusParam == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'radius'"); return; } /* * optional: */ String accurary = request.getParameter("accuracy"); String pageKey = request.getParameter("pageKey"); // String oauth_consumer_key = // request.getParameter("oauth_consumer_key"); // String oauth_signature_method = // request.getParameter("oauth_signature_method"); String radiolist = request.getParameter("RADIOLIST"); String searchbox = request.getParameter("SEARCHBOX"); String custom_slider = request.getParameter("CUSTOM_SLIDER"); String checkboxlist = request.getParameter("CHECKBOXLIST"); String localCountryCode = request.getParameter("localCountryCode"); String alt = request.getParameter("alt"); // current altitude String recognizedReferenceImage = request.getParameter("recognizedReferenceImage"); // convert parameters float lat = Float.parseFloat(latParam); float lon = Float.parseFloat(lonParam); double[] center = new double[] { lat, lon }; float radius = Float.parseFloat(radiusParam); // get nearby sensors LayarResponse layarResponse = new LayarResponse(); layarResponse.layer = request.getParameter("layerName"); if (layarResponse.layer == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameter 'layerName'"); return; } response.setContentType("application/json; charset=utf-8"); JsonGenerator generator = this.factory.createJsonGenerator(response.getWriter()); generator.useDefaultPrettyPrinter(); // query SIR try { Collection<SirPOI> pois = querySIR(center, radius, REQUEST_FORMAT); for (SirPOI sirPOI : pois) { if (sirPOI instanceof Hotspot) { Hotspot h = (Hotspot) sirPOI; layarResponse.hotspots.add(h); } } } catch (Exception e) { log.error("Error querying SIR.", e); layarResponse.errorCode = LayarResponse.CODE_ERROR; layarResponse.errorString = e.toString() + ": " + e.getMessage(); layarResponse.showMessage = "Server side exception!"; } // write response layarResponse.toJSON(generator); // clean up generator.close(); response.flushBuffer(); }
From source file:com.rr.moheals.ui.reports.reportController.java
@RequestMapping(value = "/viewReport", method = { RequestMethod.GET }) public void viewReport(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletResponse response) throws Exception { Integer reportRequestId = 0;/*from ww w. j a v a2s . c o m*/ reportView rv = new reportView(); boolean canViewReport = false; if (session.getAttribute("userDetails") != null) { User userDetails = (User) session.getAttribute("userDetails"); //1 decrpt and get the reportId decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); reportRequestId = Integer.parseInt(result[0].substring(4)); rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link"); rv.setSystemUserId(userDetails.getId()); reportmanager.saveReportView(rv); //now we get the report details reportRequest rr = reportmanager.getReportRequestById(reportRequestId); if (rr != null) { //we check permission and program if (userDetails.getRoleId() == 3 && rr.getSystemUserId() == userDetails.getId() && rr.getProgramId() == programId) { canViewReport = true; } else if (userDetails.getRoleId() != 3 && rr.getProgramId() == programId) { canViewReport = true; } } //we log them, grab report for them to download //if report doesn't exist we send them back to list with a message if (!canViewReport) { rv = new reportView(); rv.setReportRequestId(reportRequestId); rv.setSystemUserId(userDetails.getId()); rv.setReportAction("User does not have permission to view report"); reportmanager.saveReportView(rv); throw new Exception("user does not have permission - " + reportRequestId); } else { //generate the report for user to download //need to get report path String filePath = reportmanager.getReportPath(programId); String fileName = rr.getReportFileName(); try { File f = new File(filePath + fileName); if (!f.exists()) { throw new Exception("Error with File " + filePath + fileName); } } catch (Exception e) { try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("File does not exists " + filePath + fileName); } catch (Exception ex1) { throw new Exception("File does not exists " + filePath + fileName + ex1); } } try { // get your file as InputStream InputStream is = new FileInputStream(filePath + fileName); // copy it to response's OutputStream String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); rv = new reportView(); rv.setSystemUserId(userDetails.getId()); rv.setReportRequestId(reportRequestId); rv.setReportAction("Viewed Report"); reportmanager.saveReportView(rv); //update status if (rr.getStatusId() == 3) { rr.setStatusId(4); reportmanager.updateReportRequest(rr); } } catch (IOException ex) { ex.printStackTrace(); System.out.println("Error writing file to output stream. Filename was '{}'" + fileName + ex); try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("Error with File " + filePath + fileName + ex); } catch (Exception e) { throw new Exception("Error with File " + filePath + fileName + ex); } } } } else { //someone somehow got to this link, we just log //we log who is accessing //now we have report id, we check to see which program it belongs to and if the user has permission rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link - no user session found"); reportmanager.saveReportView(rv); throw new Exception("invalid report download - " + reportRequestId); } }
From source file:org.apache.nutch.searcher.response.json.JSONResponseWriter.java
public void writeResponse(SearchResults results, HttpServletRequest request, HttpServletResponse response) throws IOException { // the function name, if any wrapping the JSON output String func = RequestUtils.getStringParameter(request, "func"); // create the JSON object and add common values JSONObject jsonObj = new JSONObject(); jsonObj.accumulate("query", results.getQuery()); jsonObj.accumulate("lang", results.getLang()); jsonObj.accumulate("sort", results.getSort()); jsonObj.accumulate("reverse", results.isReverse()); jsonObj.accumulate("start", results.getStart()); jsonObj.accumulate("end", results.getEnd()); jsonObj.accumulate("rows", results.getRows()); jsonObj.accumulate("totalhits", results.getTotalHits()); jsonObj.accumulate("withSummary", results.isWithSummary()); String[] searchFields = results.getFields(); Set<String> fieldSet = new HashSet<String>(); if (searchFields != null && searchFields.length > 0) { jsonObj.accumulate("fields", StringUtils.join(searchFields, ",")); for (int i = 0; i < searchFields.length; i++) { fieldSet.add(searchFields[i]); }//from w w w .ja va2s . c o m } // add the documents from search hits JSONArray docsAr = new JSONArray(); HitDetails[] details = results.getDetails(); Hit[] hits = results.getHits(); Summary[] summaries = results.getSummaries(); for (int i = 0; i < details.length; i++) { // every document has an indexno and an indexdocno JSONObject result = new JSONObject(); HitDetails detail = details[i]; Hit hit = hits[i]; result.accumulate("indexno", hit.getIndexNo()); result.accumulate("indexkey", hit.getUniqueKey()); // don't add summaries not including summaries if (summaries != null && results.isWithSummary()) { Summary summary = summaries[i]; result.accumulate("summary", summary.toString()); } // add the fields from hit details JSONObject fields = new JSONObject(); for (int k = 0; k < detail.getLength(); k++) { String name = detail.getField(k); String[] values = detail.getValues(name); // if we specified fields to return, only return those fields if (fieldSet.size() == 0 || fieldSet.contains(name)) { JSONArray valuesAr = new JSONArray(); for (int m = 0; m < values.length; m++) { valuesAr.add(values[m]); } fields.accumulate(name, valuesAr); } } result.accumulate("fields", fields); docsAr.add(result); } jsonObj.accumulate("documents", docsAr); // pretty printing can be set through configuration, write out the wrapper // function if there is one StringBuilder builder = new StringBuilder(); if (StringUtils.isNotBlank(func)) { builder.append(func + "("); } builder.append(prettyPrint ? jsonObj.toString(2) : jsonObj.toString()); if (StringUtils.isNotBlank(func)) { builder.append(")"); } // Cache control headers SimpleDateFormat sdf = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss 'GMT'"); long relExpiresInMillis = System.currentTimeMillis() + (1000 * maxAgeInSeconds); response.setContentType(contentType); response.setHeader("Cache-Control", "max-age=" + maxAgeInSeconds); response.setHeader("Expires", sdf.format(relExpiresInMillis)); // write out the content to the response response.getOutputStream().write(builder.toString().getBytes()); response.flushBuffer(); }
From source file:org.exem.flamingo.web.filesystem.hdfs.HdfsBrowserController.java
/** * ?? .//from w w w. ja v a 2s.c o m * * @return REST Response JAXB Object */ @RequestMapping(value = "download", method = RequestMethod.GET) @ResponseStatus(HttpStatus.OK) public ResponseEntity download(HttpServletResponse res, @RequestParam String srcPath, @RequestParam String fullyQualifiedPath) { String srcFilePath = getPathFilter(srcPath); String username = SessionUtils.getUsername(); HttpHeaders headers = new HttpHeaders(); if (org.apache.commons.lang.StringUtils.isEmpty(fullyQualifiedPath)) { headers.set("message", "Invalid parameter."); return new ResponseEntity(headers, HttpStatus.BAD_REQUEST); } //TODO HDFS ? ? /*List<String> paths = hdfsBrowserAuthService.getHdfsBrowserPatternAll(username); String hdfsPathPattern = hdfsBrowserAuthService.validateHdfsPathPattern(srcFilePath, paths); Map fileMap = new HashMap(); fileMap.put("username", username); fileMap.put("hdfsPathPattern", hdfsPathPattern); fileMap.put("condition", "downloadFile"); hdfsBrowserAuthService.getHdfsBrowserUserDirAuth(fileMap);*/ boolean isRemoteEngine = Boolean.parseBoolean(isRemote); // Remote ? ? ?, Remote? Store and Forward if (!isRemoteEngine) { String filSplit[] = fullyQualifiedPath.split("/"); String filename = filSplit[filSplit.length - 1]; fileSystemService.validatePath(srcFilePath); HttpResponse execute; try { String namenodeAgentUrl = MessageFormatter .arrayFormat("http://{}:{}/remote/agent/transfer/download?fullyQualifiedPath={}", new Object[] { namenodeAgentAddress, namenodeAgentPort, URLEncoder.encode(fullyQualifiedPath, "UTF-8") }) .getMessage(); HttpGet httpGet = new HttpGet(namenodeAgentUrl); execute = httpClient.execute(httpGet); } catch (Exception ex) { throw new WholeBodyException("File Download Failed"); } if (execute.getStatusLine().getStatusCode() != 200) { throw new WholeBodyException("File Download Failed"); } else { try { InputStream is = execute.getEntity().getContent(); res.setHeader("Content-Length", "" + execute.getEntity().getContentLength()); res.setHeader("Content-Transfer-Encoding", "binary"); res.setHeader("Content-Type", "application/force-download"); res.setHeader("Content-Disposition", MessageFormatter.format("attachment; fullyQualifiedPath={}; filename={};", URLEncoder.encode(fullyQualifiedPath, "UTF-8"), filename).getMessage()); res.setStatus(200); FileCopyUtils.copy(is, res.getOutputStream()); res.flushBuffer(); fileSystemService.validateBeforeDownload(srcFilePath, fullyQualifiedPath, username); return new ResponseEntity(HttpStatus.OK); } catch (Exception ex) { throw new WholeBodyException("File Download Failed", ex); } } } else { try { byte[] bytes = fileSystemService.load(srcFilePath, fullyQualifiedPath, username); res.setHeader("Content-Length", "" + bytes.length); res.setHeader("Content-Transfer-Encoding", "binary"); res.setHeader("Content-Type", "application/force-download"); res.setHeader("Content-Disposition", MessageFormatter.format("attachment; fullyQualifiedPath={};", URLEncoder.encode(fullyQualifiedPath, "UTF-8")).getMessage()); res.setStatus(200); FileCopyUtils.copy(bytes, res.getOutputStream()); res.flushBuffer(); return new ResponseEntity(HttpStatus.OK); } catch (Exception ex) { throw new WholeBodyException("File Download Failed", ex); } } }
From source file:mercury.DigitalMediaController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); try {//from w w w . ja va 2 s .c o m List items = upload.parseRequest(request); Iterator iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { Integer serial = (new DigitalMediaDAO()).uploadToDigitalMedia(item); String filename = item.getName(); if (filename.lastIndexOf('\\') != -1) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') != -1) { filename = filename.substring(filename.lastIndexOf('/') + 1); } String id = serial + ":" + filename; String encodedId = new String(new Base64().encode(id.getBytes())); encodedId = encodedId.replaceAll("\\\\", "_"); if (serial != null && serial != 0) { response.getWriter().write("{success: true, id: \"" + encodedId + "\"}"); return; } } } } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().write("{success: false}"); } else { String decodedId = null; DigitalMediaDTO dto = null; try { String id = request.getParameter("id"); id = id.replaceAll("_", "\\\\"); decodedId = new String(new Base64().decode(id.getBytes())); String[] splitId = decodedId.split(":"); if (splitId.length == 2 && splitId[0].matches("^\\d+$")) { dto = (new DigitalMediaDAO()).getDigitalMedia(Integer.valueOf(splitId[0]), splitId[1]); } } catch (Exception e) { // dto should be null here } InputStream in = null; byte[] bytearray = null; int length = 0; String defaultFile = request.getParameter("default"); response.reset(); try { if (dto != null && dto.getIn() != null) { response.setContentType(dto.getMimeType()); response.setHeader("Content-Disposition", "filename=" + dto.getFileName()); length = dto.getLength(); in = dto.getIn(); } if (in == null && StringUtils.isNotBlank(defaultFile)) { String path = getServletContext().getRealPath("/"); File file = new File(path + defaultFile); length = (int) file.length(); in = new FileInputStream(file); } if (in != null) { bytearray = new byte[length]; int index = 0; OutputStream os = response.getOutputStream(); while ((index = in.read(bytearray)) != -1) { os.write(bytearray, 0, index); } in.close(); } else { response.getWriter().write("{success: false}"); } } catch (Exception e) { e.printStackTrace(); response.getWriter().write("{success: false}"); } response.flushBuffer(); } }
From source file:com.rr.fpdsafetraffic.ui.reports.reportController.java
@RequestMapping(value = "/DLReport", method = { RequestMethod.GET }) public void DLReport(@RequestParam String i, @RequestParam String v, HttpSession session, HttpServletResponse response) throws Exception { Integer reportRequestId = 0;//w w w .j a v a 2 s . com reportView rv = new reportView(); boolean canViewReport = false; if (session.getAttribute("userDetails") != null) { User userDetails = (User) session.getAttribute("userDetails"); //1 decrpt and get the reportId decryptObject decrypt = new decryptObject(); Object obj = decrypt.decryptObject(i, v); String[] result = obj.toString().split((",")); reportRequestId = Integer.parseInt(result[0].substring(4)); rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link"); rv.setSystemUserId(userDetails.getId()); reportmanager.saveReportView(rv); //now we get the report details reportRequest rr = reportmanager.getReportRequestById(reportRequestId); if (rr != null) { //we check permission and program if (userDetails.getRoleId() == 3 && rr.getSystemUserId() == userDetails.getId() && rr.getProgramId() == programId) { canViewReport = true; } else if (userDetails.getRoleId() != 3 && rr.getProgramId() == programId) { canViewReport = true; } } //we log them, grab report for them to download //if report doesn't exist we send them back to list with a message if (!canViewReport) { rv = new reportView(); rv.setReportRequestId(reportRequestId); rv.setSystemUserId(userDetails.getId()); rv.setReportAction("User does not have permission to view report"); reportmanager.saveReportView(rv); throw new Exception("user does not have permission - " + reportRequestId); } else { //generate the report for user to download //need to get report path String filePath = reportmanager.getReportPath(programId); String fileName = rr.getReportFileName(); try { File f = new File(filePath + fileName); if (!f.exists()) { throw new Exception("Error with File " + filePath + fileName); } } catch (Exception e) { try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("File does not exists " + filePath + fileName); } catch (Exception ex1) { throw new Exception("File does not exists " + filePath + fileName + ex1); } } try { // get your file as InputStream InputStream is = new FileInputStream(filePath + fileName); // copy it to response's OutputStream String mimeType = "application/octet-stream"; response.setContentType(mimeType); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); is.close(); rv = new reportView(); rv.setSystemUserId(userDetails.getId()); rv.setReportRequestId(reportRequestId); rv.setReportAction("Viewed Report"); reportmanager.saveReportView(rv); //update status if (rr.getStatusId() == 3) { rr.setStatusId(4); reportmanager.updateReportRequest(rr); } } catch (IOException ex) { ex.printStackTrace(); System.out.println("Error writing file to output stream. Filename was '{}'" + fileName + ex); try { //update file to error rr.setStatusId(5); reportmanager.updateReportRequest(rr); throw new Exception("Error with File " + filePath + fileName + ex); } catch (Exception e) { throw new Exception("Error with File " + filePath + fileName + ex); } } } } else { //someone somehow got to this link, we just log //we log who is accessing //now we have report id, we check to see which program it belongs to and if the user has permission rv.setReportRequestId(reportRequestId); rv.setReportAction("Accessed report link - no user session found"); reportmanager.saveReportView(rv); throw new Exception("invalid report download - " + reportRequestId); } }
From source file:org.jumpmind.symmetric.web.PushUriHandler.java
public void handle(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { String nodeId = ServletUtils.getParameter(req, WebConstants.NODE_ID); String channelId = getChannelId(req); log.info("About to service push request for {}", nodeId); IStagingManager stagingManager = engine.getStagingManager(); IDataLoaderService dataLoaderService = engine.getDataLoaderService(); INodeService nodeService = engine.getNodeService(); IStatisticManager statisticManager = engine.getStatisticManager(); String identityNodeId = nodeService.findIdentityNodeId(); ProcessInfo processInfo = statisticManager .newProcessInfo(new ProcessInfoKey(nodeId, identityNodeId, ProcessType.TRANSFER_FROM, channelId)); BufferedReader reader = null; BufferedWriter writer = null; DataLoaderWorker worker = null;/* w ww. j a v a 2 s.c o m*/ try { Node sourceNode = engine.getNodeService().findNode(nodeId); processInfo.setStatus(ProcessInfo.Status.TRANSFERRING); reader = new BufferedReader(new InputStreamReader(createInputStream(req))); long streamToFileThreshold = parameterService.getLong(ParameterConstants.STREAM_TO_FILE_THRESHOLD); String line = reader.readLine(); StringBuilder batchPrefix = new StringBuilder(); Long batchId = null; while (line != null) { if (line.startsWith(CsvConstants.BATCH)) { batchId = getBatchId(line); IStagedResource resource = stagingManager.create(streamToFileThreshold, Constants.STAGING_CATEGORY_INCOMING, nodeId, batchId); writer = resource.getWriter(); writer.write(batchPrefix.toString()); } else if (line.startsWith(CsvConstants.COMMIT)) { writer.write(line); writer.close(); writer = null; if (worker == null) { worker = dataLoaderService.createDataLoaderWorker(ProcessType.LOAD_FROM_PUSH, channelId, sourceNode); } worker.queueUpLoad(new IncomingBatch(batchId, nodeId)); batchId = null; } if (batchId == null) { batchPrefix.append(line).append("\n"); } else if (writer != null) { writer.write(line); writer.write("\n"); } line = reader.readLine(); } processInfo.setStatus(ProcessInfo.Status.OK); } catch (RuntimeException ex) { processInfo.setStatus(ProcessInfo.Status.ERROR); throw ex; } finally { IOUtils.closeQuietly(reader); IOUtils.closeQuietly(writer); } PrintWriter resWriter = res.getWriter(); if (worker != null) { worker.queueUpLoad(new DataLoaderService.EOM()); while (!worker.isComplete()) { String status = "done"; IncomingBatch batch = worker.waitForNextBatchToComplete(); if (batch == null) { status = "in progress"; batch = worker.getCurrentlyLoading(); } if (batch != null && !(batch instanceof DataLoaderService.EOM)) { ArrayList<IncomingBatch> list = new ArrayList<IncomingBatch>(1); list.add(batch); log.info("sending {} ack ... for {}", status, batch); // TODO 13 support resWriter.write( engine.getTransportManager().getAcknowledgementData(false, identityNodeId, list)); resWriter.write("\n"); resWriter.flush(); } } } res.flushBuffer(); log.debug("Done servicing push request for {}", nodeId); }