List of usage examples for javax.servlet.http HttpServletResponse flushBuffer
public void flushBuffer() throws IOException;
From source file:nl.fontys.fhict.jea.gwt.jee7.server.bus.FileUploadServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("working?"); // process only multipart requests if (ServletFileUpload.isMultipartContent(req)) { // Create a factory for disk-based file items FileItemFactory factory = new DiskFileItemFactory(); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Parse the request try {/* www .ja v a 2 s . c o m*/ List<FileItem> items = upload.parseRequest(req); for (FileItem item : items) { // process only file upload - discard other form item types if (item.isFormField()) { continue; } String fileName = item.getName(); // get only the file name not whole path if (fileName != null) { fileName = FilenameUtils.getName(fileName); } File uploadedFile = new File(UPLOAD_DIRECTORY, fileName); uploadedFile.delete(); if (uploadedFile.createNewFile()) { item.write(uploadedFile); } else { throw new IOException("The file already exists in repository."); } ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedImage in = ImageIO.read(uploadedFile); try { ImageIO.write(in, "png", baos); } catch (IOException e) { e.printStackTrace(); } String imageString = "data:image/png;base64," + DatatypeConverter.printBase64Binary(baos.toByteArray()); serviceBean.setPicture(req.getRemoteUser(), imageString); resp.setStatus(HttpServletResponse.SC_CREATED); resp.setContentType("image/png"); resp.getWriter().print(imageString); resp.flushBuffer(); } } catch (Exception e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred while creating the file : " + e.getMessage()); } } else { resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request contents type is not supported by the servlet."); } }
From source file:de.unirostock.sems.cbarchive.web.servlet.DownloadServlet.java
private void downloadFile(HttpServletRequest request, HttpServletResponse response, UserManager user, String archiveId, String filePath) throws IOException { Archive archive = null;/*from ww w. j a va 2 s. c o m*/ CombineArchive combineArchive = null; try { archive = user.getArchive(archiveId, true); combineArchive = archive.getArchive(); } catch (FileNotFoundException | CombineArchiveWebException e) { LOGGER.warn(e, MessageFormat.format( "Archive FileNotFound Exception, while handling donwload request for File {2} in Archive {1} in Workspace {0}", user.getWorkingDir(), archive, filePath)); response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } // check if file exits in the archive ArchiveEntry entry = combineArchive.getEntry(filePath); if (entry == null) { LOGGER.warn(MessageFormat.format("File not found in archive {1} in Workspace {0} : file = {2}", user.getWorkingDir(), archiveId, filePath)); response.sendError(HttpServletResponse.SC_NOT_FOUND, "File not found in archive."); if (archive != null) archive.close(); return; } // set the filename of the response response.addHeader("Content-Disposition", MessageFormat.format("inline; filename=\"{0}\"", entry.getFileName())); // extract the file try { File tempFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, entry.getFileName()); entry.extractFile(tempFile); // set the mime type of the response response.setContentType(Files.probeContentType(tempFile.toPath())); OutputStream output = response.getOutputStream(); InputStream input = new FileInputStream(tempFile); // copy the streams IOUtils.copy(input, output); // flush'n'close output.flush(); output.close(); input.close(); response.flushBuffer(); // remove the temp file tempFile.delete(); if (archive != null) archive.close(); } catch (IOException e) { LOGGER.warn(MessageFormat.format( "Error while extracting and serving file in archive {1} in Workspace {0} : file = {2}", user.getWorkingDir(), archiveId, filePath)); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error while extracting and serving file."); if (archive != null) archive.close(); return; } }
From source file:edu.jhu.cvrg.ceptools.main.PubMedSearch.java
public void downloadFile(String filename, String filetype) { //The filetypes used are as follows- //doc|docx|xls|xlsx|pdf|abf|xml|pgf|pul|amp|dat|txt|zip|tar String contentType = ""; if (filetype.equals("zip")) { contentType = "application/zip"; } else if (filetype.equals("tar")) { contentType = "application/tar"; } else if (filetype.equals("xls") || filetype.equals("xlsx")) { contentType = "application/xls"; }// w w w . ja v a2 s.co m else if (filetype.equals("doc") || filetype.equals("docx")) { contentType = "application/doc"; } else if (filetype.equals("pdf")) { contentType = "application/pdf"; } else if (filetype.equals("xml")) { contentType = "text/xml"; } else { contentType = "text/plain"; } FacesContext facesContext = (FacesContext) FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); PortletResponse portletResponse = (PortletResponse) externalContext.getResponse(); HttpServletResponse response = PortalUtil.getHttpServletResponse(portletResponse); File file = new File(selecteddownloadfile.getLocalfilestore(), filename); BufferedInputStream input = null; BufferedOutputStream output = null; try { input = new BufferedInputStream(new FileInputStream(file), 10240); response.reset(); response.setHeader("Content-Type", contentType); response.setHeader("Content-Length", String.valueOf(file.length())); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); response.flushBuffer(); output = new BufferedOutputStream(response.getOutputStream(), 10240); byte[] buffer = new byte[10240]; int length; while ((length = input.read(buffer)) > 0) { output.write(buffer, 0, length); } output.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } } facesContext.responseComplete(); }
From source file:org.alfresco.repo.webdav.auth.BaseNTLMAuthenticationFilter.java
/** * Process a type 1 NTLM message/*from w w w . ja va2 s . c o m*/ * * @param type1Msg Type1NTLMMessage * @param req HttpServletRequest * @param res HttpServletResponse * @exception IOException */ protected void processType1(Type1NTLMMessage type1Msg, HttpServletRequest req, HttpServletResponse res) throws IOException { if (getLogger().isDebugEnabled()) getLogger().debug("Received type1 " + type1Msg); // Get the existing NTLM details NTLMLogonDetails ntlmDetails = null; HttpSession session = req.getSession(); ntlmDetails = (NTLMLogonDetails) session.getAttribute(NTLM_AUTH_DETAILS); // Check if cached logon details are available if (ntlmDetails != null && ntlmDetails.hasType2Message() && ((nltmAuthenticator.getNTLMMode() == NTLMMode.PASS_THROUGH && ntlmDetails.hasAuthenticationToken()) || !ntlmDetails.hasAuthenticationToken())) { // Get the authentication server type2 response Type2NTLMMessage cachedType2 = ntlmDetails.getType2Message(); byte[] type2Bytes = cachedType2.getBytes(); String ntlmBlob = "NTLM " + new String(Base64.encodeBase64(type2Bytes)); if (getLogger().isDebugEnabled()) getLogger().debug("Sending cached NTLM type2 to client - " + cachedType2); // Send back a request for NTLM authentication res.setHeader(WWW_AUTHENTICATE, ntlmBlob); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.flushBuffer(); } else { // Clear any cached logon details session.removeAttribute(NTLM_AUTH_DETAILS); // Set the 8 byte challenge for the new logon request byte[] challenge = null; NTLMPassthruToken authToken = null; if (nltmAuthenticator.getNTLMMode() == NTLMMode.MD4_PROVIDER) { // Generate a random 8 byte challenge challenge = new byte[8]; DataPacker.putIntelLong(m_random.nextLong(), challenge, 0); } else { // Get the client domain String domain = type1Msg.getDomain(); if (domain == null || domain.length() == 0) { domain = mapClientAddressToDomain(req.getRemoteAddr()); } if (getLogger().isDebugEnabled()) getLogger().debug("Client domain " + domain); // Create an authentication token for the new logon authToken = new NTLMPassthruToken(domain); // Run the first stage of the passthru authentication to get the challenge nltmAuthenticator.authenticate(authToken); // Get the challenge from the token if (authToken.getChallenge() != null) { challenge = authToken.getChallenge().getBytes(); } } // Get the flags from the client request and mask out unsupported features int ntlmFlags = type1Msg.getFlags() & m_ntlmFlags; // Build a type2 message to send back to the client, containing the challenge List<TargetInfo> tList = new ArrayList<TargetInfo>(); String srvName = getServerName(); tList.add(new TargetInfo(NTLM.TargetServer, srvName)); Type2NTLMMessage type2Msg = new Type2NTLMMessage(); type2Msg.buildType2(ntlmFlags, srvName, challenge, null, tList); // Store the NTLM logon details, cache the type2 message, and token if using passthru ntlmDetails = new NTLMLogonDetails(); ntlmDetails.setType2Message(type2Msg); ntlmDetails.setAuthenticationToken(authToken); session.setAttribute(NTLM_AUTH_DETAILS, ntlmDetails); if (getLogger().isDebugEnabled()) getLogger().debug("Sending NTLM type2 to client - " + type2Msg); // Send back a request for NTLM authentication byte[] type2Bytes = type2Msg.getBytes(); String ntlmBlob = "NTLM " + new String(Base64.encodeBase64(type2Bytes)); res.setHeader(WWW_AUTHENTICATE, ntlmBlob); res.setStatus(HttpServletResponse.SC_UNAUTHORIZED); res.flushBuffer(); } }
From source file:io.fabric8.maven.impl.MavenSecureHttpContext.java
public boolean authenticate(HttpServletRequest request, HttpServletResponse response) { // Return immediately if the header is missing String authHeader = request.getHeader(HEADER_AUTHORIZATION); if (authHeader != null && authHeader.length() > 0) { // Get the authType (Basic, Digest) and authInfo (user/password) // from the header authHeader = authHeader.trim();//www.j a v a 2 s. c o m int blank = authHeader.indexOf(' '); if (blank > 0) { String authType = authHeader.substring(0, blank); String authInfo = authHeader.substring(blank).trim(); // Check whether authorization type matches if (authType.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { try { String srcString = base64Decode(authInfo); int i = srcString.indexOf(':'); String username = srcString.substring(0, i); String password = srcString.substring(i + 1); // authenticate Subject subject = doAuthenticate(username, password); if (subject != null) { // as per the spec, set attributes request.setAttribute(HttpContext.AUTHENTICATION_TYPE, HttpServletRequest.BASIC_AUTH); request.setAttribute(HttpContext.REMOTE_USER, username); // succeed return true; } } catch (Exception e) { // Ignore } } } } // request authentication try { response.setHeader(HEADER_WWW_AUTHENTICATE, AUTHENTICATION_SCHEME_BASIC + " realm=\"" + this.realm + "\""); // must response with status and flush as Jetty may report org.eclipse.jetty.server.Response Committed before 401 null response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.setContentLength(0); response.flushBuffer(); } catch (IOException ioe) { // failed sending the response ... cannot do anything about it } // inform HttpService that authentication failed return false; }
From source file:de.mpg.mpdl.inge.pubman.web.servlet.RedirectServlet.java
/** * {@inheritDoc}// ww w. j av a 2 s.c om */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getPathInfo().substring(1); boolean download = ("download".equals(req.getParameter("mode"))); boolean tme = ("tme".equals(req.getParameter("mode"))); String userHandle = req.getParameter(LoginHelper.PARAMETERNAME_USERHANDLE); // no component -> viewItemOverviewPage if (!id.contains("/component/")) { StringBuffer redirectUrl = new StringBuffer(); LoginHelper loginHelper = (LoginHelper) req.getSession().getAttribute("LoginHelper"); if (loginHelper != null && loginHelper.isDetailedMode()) { redirectUrl.append("/pubman/faces/viewItemFullPage.jsp?itemId=" + id); } else { redirectUrl.append("/pubman/faces/viewItemOverviewPage.jsp?itemId=" + id); } if (userHandle != null) { redirectUrl.append("&" + LoginHelper.PARAMETERNAME_USERHANDLE + "=" + userHandle); } resp.sendRedirect(redirectUrl.toString()); return; } // is component if (id.contains("/component/")) { String[] pieces = id.split("/"); if (pieces.length != 4) { resp.sendError(404, "File not found"); } // open component or download it if (req.getParameter("mode") == null || download) { try { InputStream input = getContentAsInputStream(req, resp, download, pieces); if (input == null) { return; } byte[] buffer = new byte[2048]; int numRead; long numWritten = 0; OutputStream out = resp.getOutputStream(); while ((numRead = input.read(buffer)) != -1) { logger.debug(numRead + " bytes read."); out.write(buffer, 0, numRead); resp.flushBuffer(); numWritten += numRead; } input.close(); out.close(); } catch (URISyntaxException e) { throw new ServletException(e); } } // view technical metadata if (tme) { OutputStream out = resp.getOutputStream(); resp.setCharacterEncoding("UTF-8"); try { InputStream input = getContentAsInputStream(req, resp, false, pieces); if (input == null) { return; } String b = new String(); try { b = getTechnicalMetadataByTika(input); } catch (TikaException e) { logger.warn("TikaException when parsing " + pieces[3], e); } catch (SAXException e) { logger.warn("SAXException when parsing " + pieces[3], e); } resp.setHeader("Content-Type", "text/plain; charset=UTF-8"); out.write(b.toString().getBytes()); return; } catch (Exception e) { throw new ServletException(e); } } } }
From source file:io.ericwittmann.corsproxy.ProxyServlet.java
/** * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) *///w w w. j a v a 2 s.c om @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String url = "https://issues.jboss.org" + req.getPathInfo(); if (req.getQueryString() != null) { url += "?" + req.getQueryString(); } System.out.println("Proxying to: " + url); boolean isWrite = req.getMethod().equalsIgnoreCase("post") || req.getMethod().equalsIgnoreCase("put"); URL remoteUrl = new URL(url); HttpURLConnection remoteConn = (HttpURLConnection) remoteUrl.openConnection(); if (isWrite) { remoteConn.setDoOutput(true); } String auth = req.getHeader("Authorization"); if (auth != null) { remoteConn.setRequestProperty("Authorization", auth); } if (isWrite) { InputStream requestIS = null; OutputStream remoteOS = null; try { requestIS = req.getInputStream(); remoteOS = remoteConn.getOutputStream(); IOUtils.copy(requestIS, remoteOS); remoteOS.flush(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); return; } finally { IOUtils.closeQuietly(requestIS); IOUtils.closeQuietly(remoteOS); } } InputStream remoteIS = null; OutputStream responseOS = null; try { 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-2$ remoteIS = remoteConn.getInputStream(); responseOS = resp.getOutputStream(); IOUtils.copy(remoteIS, responseOS); resp.flushBuffer(); } catch (Exception e) { e.printStackTrace(); resp.sendError(500, e.getMessage()); } finally { IOUtils.closeQuietly(responseOS); IOUtils.closeQuietly(remoteIS); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.externalServices.SetEmailDA.java
public ActionForward setEmail(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final String host = HostAccessControl.getRemoteAddress(request); final String ip = request.getRemoteAddr(); final String password = request.getParameter("password"); final String userUId = request.getParameter("userUId"); final String email = URLDecoder.decode(request.getParameter("email"), "UTF-8"); String message = "ko"; try {/*ww w .j ava2 s . c o m*/ SetEmail.run(host, ip, password, userUId, email); final User user = User.findByUsername(userUId); if (user.getPerson() != null && user.getPerson().getStudent() != null) { final Student student = user.getPerson().getStudent(); for (final Registration registration : student.getRegistrationsSet()) { final StudentCandidacy candidacy = registration.getStudentCandidacy(); if (candidacy != null && (candidacy instanceof DegreeCandidacy || candidacy instanceof IMDCandidacy) && candidacy.getExecutionYear().isCurrent() && !candidacy.getCandidacySituationsSet().isEmpty()) { new PDFGeneratorThread(candidacy.getExternalId(), request.getServerName(), request.getServerPort(), request.getContextPath(), request.getServletPath()) .start(); } } } message = "ok"; } catch (NotAuthorizedException ex) { message = "Not authorized"; } catch (UserAlreadyHasEmailException ex) { message = "User already has email."; } catch (UserDoesNotExistException ex) { message = "User does not exist."; } catch (Throwable ex) { message = ex.getMessage(); logger.error(ex.getMessage(), ex); } finally { final ServletOutputStream servletOutputStream = response.getOutputStream(); response.setContentType("text/html"); servletOutputStream.print(message); servletOutputStream.flush(); response.flushBuffer(); } return null; }
From source file:de.mpg.escidoc.pubman.servlet.RedirectServlet.java
/** * {@inheritDoc}/*from w w w . ja va 2s . c om*/ */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getPathInfo().substring(1); boolean download = ("download".equals(req.getParameter("mode"))); boolean tme = ("tme".equals(req.getParameter("mode"))); String userHandle = req.getParameter(LoginHelper.PARAMETERNAME_USERHANDLE); // no component -> viewItemOverviewPage if (!id.contains("/component/")) { StringBuffer redirectUrl = new StringBuffer(); LoginHelper loginHelper = (LoginHelper) req.getSession().getAttribute("LoginHelper"); if (loginHelper != null && loginHelper.isDetailedMode()) { redirectUrl.append("/pubman/faces/viewItemFullPage.jsp?itemId=" + id); } else { redirectUrl.append("/pubman/faces/viewItemOverviewPage.jsp?itemId=" + id); } if (userHandle != null) { redirectUrl.append("&" + LoginHelper.PARAMETERNAME_USERHANDLE + "=" + userHandle); } resp.sendRedirect(redirectUrl.toString()); return; } // is component if (id.contains("/component/")) { String[] pieces = id.split("/"); if (pieces.length != 4) { resp.sendError(404, "File not found"); } // open component or download it if (req.getParameter("mode") == null || download) { try { InputStream input = getContentAsInputStream(req, resp, download, pieces); if (input == null) { return; } byte[] buffer = new byte[2048]; int numRead; long numWritten = 0; OutputStream out = resp.getOutputStream(); while ((numRead = input.read(buffer)) != -1) { logger.debug(numRead + " bytes read."); out.write(buffer, 0, numRead); resp.flushBuffer(); numWritten += numRead; } input.close(); out.close(); } catch (URISyntaxException e) { throw new ServletException(e); } } // view technical metadata if (tme) { OutputStream out = resp.getOutputStream(); resp.setCharacterEncoding("UTF-8"); try { if ("jhove".equals(PropertyReader.getProperty("escidoc.pubman.tme.configuration"))) { String technicalMetadata = getTechnicalMetadataByJhove(pieces); resp.setHeader("Content-Type", "text/xml; charset=UTF-8"); out.write(technicalMetadata.getBytes()); } else { InputStream input = getContentAsInputStream(req, resp, false, pieces); if (input == null) { return; } String b = new String(); try { b = getTechnicalMetadataByTika(input); } catch (TikaException e) { logger.warn("TikaException when parsing " + pieces[3], e); } catch (SAXException e) { logger.warn("SAXException when parsing " + pieces[3], e); } resp.setHeader("Content-Type", "text/plain; charset=UTF-8"); out.write(b.toString().getBytes()); return; } } catch (Exception e) { throw new ServletException(e); } } } }
From source file:org.fao.unredd.portal.ApplicationController.java
@RequestMapping(value = "/report.json", method = RequestMethod.POST) public void buildCustomReport(HttpServletRequest request, HttpServletResponse response) throws IOException, JAXBException { response.setContentType("application/json;charset=UTF-8"); // Get posted attributes @SuppressWarnings("unchecked") Map<String, String> attributes = flattenParamValues(request.getParameterMap()); // Get Chart Script Resource from ChartScriptId parameter long chartScriptId = Long.valueOf(attributes.get("ChartScriptId")); // POSTed body, should be a WKT geometry String wktROI = getRequestBodyAsString(request, response); try {/*from ww w. jav a 2 s .com*/ // Generate Report ReportManager report = new ReportManager(getGeostore(), config.getProperties()); String reportContents = report.get(wktROI, chartScriptId); // Persist report in GeoStore, get the URL Long reportId = getGeostore().insertReport(attributes, reportContents); String resourceName = getGeostore().getClient().getResource(reportId).getName(); String reportURL = getGeostore().getClient().getGeostoreRestUrl() + "/misc/category/name/Report/resource/name/" + resourceName + "/data?name=" + attributes.get("UserName") + " Stats"; // Build JSON response String responseBody = "{ \n" + " \"success\": true, \n" + " \"response_type\": \"result_embedded\", \n" + " \"link\": { \n" + " \"type\": \"text/html\", \n" + " \"href\": \"" + reportURL + "\" \n" + " } \n" + "}"; response.getWriter().print(responseBody); } catch (ReportException e) { // Will send the errorCause whose name equals the RealTimeStatsException.Code name ErrorCause cause = ErrorCause.valueOf(e.getCode().name()); response.setStatus(cause.status); response.getWriter().write(cause.getJson()); } response.flushBuffer(); }