List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:org.nsesa.editor.gwt.an.amendments.server.service.WordExportService.java
@Override public void export(AmendmentContainerDTO object, HttpServletResponse response) throws IOException { response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); response.setHeader("Content-Disposition", "attachment;filename=" + object.getAmendmentContainerID() + ".docx"); response.setCharacterEncoding("UTF8"); final String content = object.getBody(); final InputSource inputSource; inputSource = new InputSource(new StringReader(content)); try {//from w ww . j a v a 2s. co m final NodeModel model = NodeModel.parse(inputSource); final Configuration configuration = new Configuration(); configuration.setDefaultEncoding("UTF-8"); configuration.setDirectoryForTemplateLoading(template.getFile().getParentFile()); final StringWriter sw = new StringWriter(); Map<String, Object> root = new HashMap<String, Object>(); root.put("amendment", model); configuration.getTemplate(template.getFile().getName()).process(root, sw); byte[] bytes = sw.toString().getBytes("utf-8"); IOUtils.copy(new ByteArrayInputStream(bytes), response.getOutputStream()); response.setContentLength(sw.toString().length()); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("Could not read file.", e); } catch (SAXException e) { throw new RuntimeException("Could not parse file.", e); } catch (ParserConfigurationException e) { throw new RuntimeException("Could not parse file.", e); } catch (TemplateException e) { throw new RuntimeException("Could not load template.", e); } }
From source file:cn.lhfei.fu.web.controller.TeacherController.java
/** * Method for handling file download request from client *///w w w . ja v a2s . c o m @RequestMapping(value = "downloadImg", method = RequestMethod.GET) public void downloadImg(HttpServletRequest request, HttpServletResponse response, @RequestParam("id") int id) throws IOException { try { HomeworkArchive homeworkArchive = homeworkArchiveService.read(id); if (null != homeworkArchive) { File file = new File(homeworkArchive.getArchivePath()); String fileName = homeworkArchive.getArchiveName(); //fileName = java.net.URLEncoder.encode(fileName,"UTF-8"); // get your file as InputStream InputStream is = new FileInputStream(file); response.setContentType("application/image;charset=UTF-8"); response.setContentLength(new Long(file.length()).intValue()); response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".jpg; charset=UTF-8"); // copy it to response's OutputStream org.apache.commons.io.IOUtils.copy(is, response.getOutputStream()); response.flushBuffer(); } } catch (IOException ex) { log.error(ex.getMessage(), ex); throw new RuntimeException("IOError writing file to output stream", ex); } }
From source file:edu.mayo.cts2.framework.plugin.service.lexevs.bulk.mapversion.controller.MapVersionBulkDownloadController.java
/** * Download.//from w w w.ja va 2 s .c om * * @param response the response * @param codingschemes the codingschemes * @param fields the fields * @param separator the separator * @throws LBException the lB exception */ @RequestMapping(value = "/exporter/map") public void download(HttpServletResponse response, @RequestParam(value = "map", required = true) String map, @RequestParam(value = "fields", defaultValue = "") String fields, @RequestParam(value = "separator", defaultValue = DEFAULT_SEPARATOR) char separator, @RequestParam(value = "filename", defaultValue = DEFAULT_FILE_NAME) String filename) throws LBException { List<String> fieldsList; if (StringUtils.isBlank(fields)) { fieldsList = DEFAULT_FIELDS; } else { fieldsList = Arrays.asList(StringUtils.split(fields, ',')); } this.setHeaders(response, filename); String[] parts = StringUtils.split(map, ':'); CodingSchemeReference reference = new CodingSchemeReference(); reference.setCodingScheme(parts[0]); if (parts.length == 2) { reference.setVersionOrTag(Constructors.createCodingSchemeVersionOrTagFromVersion(parts[1])); } try { this.mapVersionBulkDownloader.download(response.getOutputStream(), reference, fieldsList, separator); } catch (IOException e) { throw new RuntimeException(e); } try { response.flushBuffer(); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public void handleConnect(HttpServletRequest request, HttpServletResponse response) throws IOException { String uri = request.getRequestURI(); String port = ""; String host = ""; int c = uri.indexOf(':'); if (c >= 0) { port = uri.substring(c + 1);/*w ww . j av a2 s.c o m*/ host = uri.substring(0, c); if (host.indexOf('/') > 0) host = host.substring(host.indexOf('/') + 1); } InetSocketAddress inetAddress = new InetSocketAddress(host, Integer.parseInt(port)); // if // (isForbidden(HttpMessage.__SSL_SCHEME,addrPort.getHost(),addrPort.getPort(),false)) // { // sendForbid(request,response,uri); // } // else { InputStream in = request.getInputStream(); final OutputStream out = response.getOutputStream(); final Socket socket = new Socket(inetAddress.getAddress(), inetAddress.getPort()); response.setStatus(200); response.setHeader("Connection", "close"); response.flushBuffer(); // try { // Thread copy = new Thread(new Runnable() { // public void run() { // try { IOUtils.copy(socket.getInputStream(), out); // } catch (IOException e) { // e.printStackTrace(); // } // } // }); // copy.start(); IOUtils.copy(in, socket.getOutputStream()); // copy.join(); // copy.join(10000); // } // catch (InterruptedException e) { // e.printStackTrace(); // } } }
From source file:org.eclipse.vorto.repository.web.ModelRepositoryController.java
@ApiOperation(value = "Download a Model specified by Model ID") @RequestMapping(value = "/file/{namespace}/{name}/{version:.+}", method = RequestMethod.GET) public void downloadModelById( @ApiParam(value = "Namespace", required = true) final @PathVariable String namespace, @ApiParam(value = "Name", required = true) final @PathVariable String name, @ApiParam(value = "Version", required = true) final @PathVariable String version, @ApiParam(value = "Output Type", required = true) final @RequestParam(value = "output", required = false) String outputType, @ApiParam(value = "Response", required = true) final HttpServletResponse response) { Objects.requireNonNull(namespace, "namespace must not be null"); Objects.requireNonNull(name, "name must not be null"); Objects.requireNonNull(version, "version must not be null"); final ModelId modelId = new ModelId(name, namespace, version); logger.info("downloadModelById: [" + modelId.toString() + "] - Fullpath: [" + modelId.getFullPath() + "]"); final ContentType contentType = getContentType(outputType); byte[] modelContent = modelRepository.getModelContent(modelId, contentType); if (modelContent != null && modelContent.length > 0) { final ModelResource modelResource = modelRepository.getById(modelId); response.setHeader(CONTENT_DISPOSITION, ATTACHMENT_FILENAME + getFileName(modelResource, contentType)); response.setContentType(APPLICATION_OCTET_STREAM); try {//from w w w.ja va 2 s. c o m IOUtils.copy(new ByteArrayInputStream(modelContent), response.getOutputStream()); response.flushBuffer(); } catch (IOException e) { throw new RuntimeException("Error copying file.", e); } } else { throw new RuntimeException("File not found."); } }
From source file:io.apiman.manager.ui.server.servlets.UrlFetchProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///from w w w.ja v a 2 s . c om @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = req.getHeader("X-Apiman-Url"); //$NON-NLS-1$ if (url == null) { resp.sendError(500, "No URL specified in X-Apiman-Url"); //$NON-NLS-1$ return; } URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); InputStream remoteIS = null; OutputStream responseOS = null; try { 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); } 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:com.emergya.persistenceGeo.web.RestLayersAdminController.java
/** * This method loads layers.json related with a user * /*from w ww .j a v a 2 s.c o m*/ * @param username * * @return JSON file with layers */ @RequestMapping(value = "/persistenceGeo/getLayerResource/{layerId}", method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE }) public void loadLayer(@PathVariable String layerId, HttpServletResponse response) { try { /* //TODO: Secure with logged user String username = ((UserDetails) SecurityContextHolder.getContext() .getAuthentication().getPrincipal()).getUsername(); */ response.setContentType("application/xml"); response.setHeader("Content-Disposition", "attachment; filename=test.xml"); IOUtils.copy(new FileInputStream(loadedLayers.get(Long.decode(layerId))), response.getOutputStream()); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.apache.roller.weblogger.ui.struts2.ajax.CommentDataServlet.java
/** * Accepts request with comment 'id' parameter and returns comment id and * content in JSON format. For example comment with id "3454545346" and * content "hi there" will be represented as: * {id : "3454545346", content : "hi there"} *///from www .j a v a 2 s.c o m public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Weblogger roller = WebloggerFactory.getWeblogger(); try { WeblogEntryManager wmgr = roller.getWeblogEntryManager(); WeblogEntryComment c = wmgr.getComment(request.getParameter("id")); if (c == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } else { // need post permission to view comments RollerSession rses = RollerSession.getRollerSession(request); Weblog weblog = c.getWeblogEntry().getWebsite(); if (weblog.hasUserPermission(rses.getAuthenticatedUser(), WeblogPermission.POST)) { String content = Utilities.escapeHTML(c.getContent()); content = WordUtils.wrap(content, 72); content = StringEscapeUtils.escapeJavaScript(content); String json = "{ id: \"" + c.getId() + "\"," + "content: \"" + content + "\" }"; response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/html; charset=utf-8"); response.getWriter().print(json); response.flushBuffer(); response.getWriter().flush(); response.getWriter().close(); } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); } } } catch (Exception e) { throw new ServletException(e.getMessage()); } }
From source file:org.eclipse.smarthome.ui.icon.internal.IconServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getDateHeader("If-Modified-Since") > startupTime) { resp.setStatus(304);//w ww . j av a 2s . c om return; } String category = getCategory(req); Format format = getFormat(req); String state = getState(req); String iconSetId = getIconSetId(req); IconProvider topProvider = null; int maxPrio = Integer.MIN_VALUE; for (IconProvider provider : iconProvider) { Integer prio = provider.hasIcon(category, iconSetId, format); if (prio != null && prio > maxPrio) { maxPrio = prio; topProvider = provider; } } if (topProvider != null) { if (format.equals(Format.SVG)) { resp.setContentType("image/svg+xml"); } else { resp.setContentType("image/png"); } resp.setDateHeader("Last-Modified", new Date().getTime()); ServletOutputStream os = resp.getOutputStream(); try (InputStream is = topProvider.getIcon(category, iconSetId, state, format)) { IOUtils.copy(is, os); resp.flushBuffer(); } catch (IOException e) { logger.error("Failed sending the icon byte stream as a response: {}", e.getMessage()); resp.sendError(500, e.getMessage()); } } else { resp.sendError(404); } }
From source file:architecture.ee.web.spring.controller.DownloadController.java
@RequestMapping(value = "/files/{fileId:[\\p{Digit}]+}/{filename:.+}", method = { RequestMethod.GET, RequestMethod.POST })//from w ww. j a va 2s .c o m @ResponseBody public void downloadFile(@PathVariable("fileId") Long fileId, @PathVariable("filename") String filename, @RequestParam(value = "thumbnail", defaultValue = "false", required = false) boolean thumbnail, @RequestParam(value = "width", defaultValue = "150", required = false) Integer width, @RequestParam(value = "height", defaultValue = "150", required = false) Integer height, HttpServletResponse response) throws IOException { try { if (fileId > 0 && StringUtils.isNotEmpty(filename)) { Attachment attachment = attachmentManager.getAttachment(fileId); if (StringUtils.equals(filename, attachment.getName())) { if (thumbnail) { if (StringUtils.startsWithIgnoreCase(attachment.getContentType(), "image") || StringUtils.endsWithIgnoreCase(attachment.getContentType(), "pdf")) { InputStream input = attachmentManager.getAttachmentImageThumbnailInputStream(attachment, width, height); response.setContentType(attachment.getThumbnailContentType()); response.setContentLength(attachment.getThumbnailSize()); IOUtils.copy(input, response.getOutputStream()); response.flushBuffer(); } } else { InputStream input = attachmentManager.getAttachmentInputStream(attachment); response.setContentType(attachment.getContentType()); response.setContentLength(attachment.getSize()); IOUtils.copy(input, response.getOutputStream()); response.setHeader("contentDisposition", "attachment;filename=" + getEncodedFileName(attachment)); response.flushBuffer(); } } else { throw new NotFoundException(); } } else { throw new NotFoundException(); } } catch (NotFoundException e) { response.sendError(404); } }