List of usage examples for javax.servlet.http HttpServletResponse addHeader
public void addHeader(String name, String value);
From source file:com.wyp.module.controller.LicenseController.java
/** * /*from ww w . j a v a 2s . com*/ * @param response * @param responseJson * @param type */ private void repsonseJsonResult(HttpServletResponse response, String responseJson, String type) { BufferedOutputStream buff = null; StringBuffer write = new StringBuffer(); ServletOutputStream outStr = null; try { outStr = response.getOutputStream();// buff = new BufferedOutputStream(outStr); // ?json?text if ("json".equals(type)) { response.setContentType("application/json");// write.append(responseJson); } else { // ** response.setContentType("text/plain");// response.addHeader("Content-Disposition", "attachment;filename=license.asc");// filename??O String enter = "\r\n"; // json? List<Object> list = parseLicenses(responseJson); for (int i = 0; i < list.size(); i++) { write.append(list.get(i)); write.append(enter); } } buff.write(write.toString().getBytes("UTF-8")); buff.flush(); buff.close(); } catch (Exception e) { e.printStackTrace(); } finally { try { buff.close(); outStr.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:SendWord.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in SendWord servlet."); // add the .doc suffix if it doesn't already exist if (fileName.indexOf(".doc") == -1) fileName = fileName + ".doc"; String wordDir = getServletContext().getInitParameter("word-dir"); if (wordDir == null || wordDir.equals("")) throw new ServletException("Invalid or non-existent wordDir context-param."); ServletOutputStream stream = null;//from www .j a v a 2s.c o m BufferedInputStream buf = null; try { stream = response.getOutputStream(); File doc = new File(wordDir + "/" + fileName); response.setContentType("application/msword"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentLength((int) doc.length()); FileInputStream input = new FileInputStream(doc); buf = new BufferedInputStream(input); int readBytes = 0; while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }
From source file:com.denimgroup.threadfix.webapp.controller.ToolsDownloadController.java
private String doDownload(HttpServletRequest request, HttpServletResponse response, String jarName) { String jarResource = JAR_DOWNLOAD_DIR + jarName; InputStream in = request.getServletContext().getResourceAsStream(jarResource); if (in == null) { exceptionLogService.storeExceptionLog( new ExceptionLog(new FileNotFoundException("File not found for download: " + jarResource))); return index(); }// ww w . jav a2 s.c om try { ServletOutputStream out = response.getOutputStream(); int jarSize = request.getServletContext().getResource(jarResource).openConnection().getContentLength(); if (jarName.endsWith(".jar")) response.setContentType("application/java-archive"); else response.setContentType("application/octet-stream"); ; response.setContentLength(jarSize); response.addHeader("Content-Disposition", "attachment; filename=\"" + jarName + "\""); IOUtils.copy(in, out); in.close(); out.flush(); out.close(); } catch (IOException ioe) { exceptionLogService.storeExceptionLog(new ExceptionLog(ioe)); return index(); } return null; }
From source file:com.w20e.socrates.servlet.WebsurveyServlet.java
/** * Do the thing... If there is no runner (context) in the session, create a * new session based on the given id parameter. If there is also no id * parameter, it's an error. If the id parameter is given, create a new * runner context anyway. If a parameter called regkey is given, this * parameter is used for storage and possibly retrieval of the instance. * This way, a user may provide it's own key. * // w ww . ja va 2s . c om * @param req * The request * @param res * The response * @throws IOException * when some io error occurs * @throws ServletException * when the servlet fails */ public final void doPost(final HttpServletRequest req, final HttpServletResponse res) throws IOException, ServletException { // Always use UTF! res.setContentType("text/html;charset=UTF-8"); req.setCharacterEncoding("UTF-8"); // Thou shalst not cache... res.addHeader("Cache-Control", "no-cache"); res.addHeader("Pragma", "No-Cache"); HttpSession session = this.sessionMgr.getSession(req); // If we don't have a session now, we might as well call it a day... if (session == null) { if (ServletHelper.getCookie(req, "JSESSIONID") != null) { LOGGER.warning("Session timeout"); res.sendRedirect("session-timeout.html"); res.getOutputStream().flush(); return; } else { LOGGER.severe("No session created"); res.sendRedirect("session-creation-error.html"); res.getOutputStream().flush(); return; } } // Hold all enable/disable options // Map<String, String> options = ServletHelper.determineOptions(req); // If no runner yet for this session, create one. We should have // startup param's for the runner, like the questionnaire to run, and // the locale. If these are not available, check for regkey. Else, all fails. // if (session.getAttribute("runnerCtx") == null) { LOGGER.finer("Session instantiated with id " + session.getId()); LOGGER.fine("No runner context available in session; creating one"); if (req.getParameter("id") == null && req.getParameter("regkey") == null) { LOGGER.warning("No id nor regkey parameter in request"); try { res.sendRedirect("session-creation-error.html"); this.sessionMgr.invalidateSession(req); res.getOutputStream().flush(); } catch (IOException e) { LOGGER.severe("Couldn't even send error message..." + e.getMessage()); } return; } if (!initializeRunner(req, res, session, options)) { LOGGER.severe("Could not create runner context. Bye for now."); return; } } // Okido, by now we should have a session, and a valid runner context // stored in the session. // try { WebsurveyContext wwCtx = (WebsurveyContext) session.getAttribute("runnerCtx"); // Now let's see whether this session was deserialized. // if (wwCtx.isInvalid()) { LOGGER.info("Serialized session found!"); // Re-create the context, and attach to WoliWeb context. LOGGER.finer("Model id: " + wwCtx.getModelId()); LOGGER.finer("State id: " + wwCtx.getStateId()); LOGGER.finer("Locale: " + wwCtx.getLocale()); URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId()); RunnerContextImpl ctx = this.runnerFactory.createContext(qUri, null); ctx.setLocale(wwCtx.getLocale()); ctx.setQuestionnaireId(qUri); ctx.getStateManager().setStateById(wwCtx.getStateId()); ctx.setInstance(wwCtx.getInstance()); wwCtx.setRunnerContext(ctx); } RunnerContextImpl ctx = (RunnerContextImpl) wwCtx.getRunnerContext(); LOGGER.finer("Session id " + session.getId()); LOGGER.finer("Context id " + ctx.getInstance().getMetaData().get("key")); // set locale if requested later on, when the survey is well under way... if (req.getParameter("locale") != null && req.getParameter("id") == null) { ctx.setLocale(LocaleUtility.getLocale(req.getParameter("locale"), false)); LOGGER.fine("Locale change requested; set to " + LocaleUtility.getLocale(req.getParameter("locale"), false)); } // even check on locale in instance data... try { Locale instanceLocale = LocaleUtility .getLocale(ctx.getInstance().getNode("locale").getValue().toString(), false); if (instanceLocale != null && instanceLocale != ctx.getLocale()) { LOGGER.fine("Locale is set in instance data: " + instanceLocale); ctx.setLocale(instanceLocale); } } catch (Exception ex) { // not a problem... } // Add specific options // @todo This should move to the runner creation options. if (ctx.getProperty("renderOptions") == null) { ctx.setProperty("renderOptions", options); } else { ((Map<String, String>) ctx.getProperty("renderOptions")).putAll(options); } Map<String, Object> params = ParameterParser.parseParams(req); ctx.setData(params); // Do we have initial data already? if ("true".equals(options.get("enable_preload_params"))) { Node node; for (String key : params.keySet()) { node = ctx.getInstance().getNode(key); if (node != null) { LOGGER.fine("Preloading node value " + params.get(key) + " for node " + node.getName()); node.setValue(params.get(key)); } } } ByteArrayOutputStream output = new ByteArrayOutputStream(); ctx.setOutputStream(output); // @todo: I really don't see why we should re-create the runner for // every post. Actually, the factory holds a reference to existing // runners, so it is not really bad, but I reckon the context should // hold the runner? // URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, wwCtx.getModelId()); Runner runner = this.runnerFactory.createRunner(qUri); if (req.getParameter("previous") == null) { Map<String, Object> meta = ctx.getInstance().getMetaData(); meta.put("time_" + req.getParameter("stateId"), new Date()); } // Always store stateId in instance, for retrieval of state after // serialization. // if (req.getParameter("stateId") != null) { LOGGER.fine("Setting state id to " + req.getParameter("stateId")); ctx.getInstance().getMetaData().put("stateId", req.getParameter("stateId")); if (!ctx.getStateManager().setStateById(req.getParameter("stateId"))) { LOGGER.warning("Couldn't set stateId to " + req.getParameter("stateId")); } } // Go two states back if 'previous' request, and simply execute // 'next'. if (req.getParameter("previous") != null) { ctx.getStateManager().previous(); RenderState state = ctx.getStateManager().previous(); LOGGER.finest("Fill data from instance"); ctx.setProperty("previous", "true"); if (state != null) { // Make sure to fill in existing data, otherwise we'll get // an error // for (Iterator<Renderable> i = state.getItems().iterator(); i.hasNext();) { Renderable r = i.next(); if (r instanceof Control) { String name = ((Control) r).getBind(); params.put(name, ctx.getInstance().getNode(name).getValue()); LOGGER.finest("Set node " + name + " to " + params.get(name)); } } } } else { ctx.setProperty("previous", "false"); } next(ctx, runner); LOGGER.fine("Are we stored yet? " + ctx.getInstance().getMetaData().get("storage-type")); // If we submitted, destroy long session if ("submit".equals(ctx.getInstance().getMetaData().get("storage-type"))) { LOGGER.fine("Invalidating long session"); String surveyId = ctx.getInstance().getMetaData().get("qId").toString(); this.sessionMgr.invalidateLongSession(surveyId, req, res); } // If this was the last action, destroy session. if (!runner.hasNext(ctx)) { this.sessionMgr.invalidateSession(req); } res.getOutputStream().write(output.toByteArray()); res.getOutputStream().flush(); // free resources... ctx.setOutputStream(null); } catch (Exception e) { LOGGER.log(Level.SEVERE, "No runner created", e); throw new ServletException("Runner could not be created: " + e.getMessage()); } }
From source file:org.fao.geonet.api.records.formatters.FormatterApi.java
private void writeOutResponse(ServiceContext context, String metadataUuid, String lang, HttpServletResponse response, FormatType formatType, byte[] formattedMetadata) throws Exception { response.setContentType(formatType.contentType); String filename = "metadata." + metadataUuid + formatType; response.addHeader("Content-Disposition", "inline; filename=\"" + filename + "\""); response.setStatus(HttpServletResponse.SC_OK); if (formatType == FormatType.pdf) { writerAsPDF(context, response, formattedMetadata, lang); } else {/*from ww w.j a v a2 s . co m*/ response.setCharacterEncoding(Constants.ENCODING); response.setContentType("text/html"); response.setContentLength(formattedMetadata.length); response.setHeader("Cache-Control", "no-cache"); response.getOutputStream().write(formattedMetadata); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.GenericCandidaciesDA.java
public ActionForward downloadRecomendationFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { final String confirmationCode = (String) getFromRequest(request, "confirmationCode"); final GenericApplicationLetterOfRecomentation file = getDomainObject(request, "fileExternalId"); if (file != null && file.getRecomentation() != null && file.getRecomentation().getConfirmationCode() != null && ((file.getRecomentation().getGenericApplication().getGenericApplicationPeriod() .isCurrentUserAllowedToMange()) || file.getRecomentation().getConfirmationCode().equals(confirmationCode))) { response.setContentType(file.getContentType()); response.addHeader("Content-Disposition", "attachment; filename=\"" + file.getFilename() + "\""); response.setContentLength(file.getSize().intValue()); final DataOutputStream dos = new DataOutputStream(response.getOutputStream()); dos.write(file.getContent());/* w w w .j a v a 2 s.co m*/ dos.close(); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST)); response.getWriter().close(); } return null; }
From source file:hudson.Functions.java
/** * Used by <tt>layout.jelly</tt> to control the auto refresh behavior. * * @param noAutoRefresh/*from www. ja va2s . c om*/ * On certain pages, like a page with forms, will have annoying interference * with auto refresh. On those pages, disable auto-refresh. */ public static void configureAutoRefresh(HttpServletRequest request, HttpServletResponse response, boolean noAutoRefresh) { if (noAutoRefresh) return; String param = request.getParameter("auto_refresh"); boolean refresh = isAutoRefresh(request); if (param != null) { refresh = Boolean.parseBoolean(param); Cookie c = new Cookie("hudson_auto_refresh", Boolean.toString(refresh)); // Need to set path or it will not stick from e.g. a project page to the dashboard. // Using request.getContextPath() might work but it seems simpler to just use the hudson_ prefix // to avoid conflicts with any other web apps that might be on the same machine. c.setPath("/"); c.setMaxAge(60 * 60 * 24 * 30); // persist it roughly for a month response.addCookie(c); } if (refresh) { response.addHeader("Refresh", "10"); } }
From source file:com.googlecode.noweco.calendar.CaldavServlet.java
@SuppressWarnings("unchecked") @Override/*w ww . java2 s . com*/ public void service(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod(); if (LOGGER.isDebugEnabled()) { List<String> headers = Collections.list((Enumeration<String>) req.getHeaderNames()); LOGGER.debug("Command : {}, Appel : {}, headers {}", new Object[] { method, req.getRequestURI(), headers }); } if (!authent(req)) { resp.addHeader("WWW-Authenticate", "BASIC realm=\"Noweco CalDAV\""); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); return; } String requestURI = req.getRequestURI(); if (requestURI.length() != 0 && requestURI.charAt(0) != '/') { // unknown relative URI resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } try { if (METHOD_PROPFIND.equals(method)) { doPropfind(req, resp); } else if (METHOD_REPORT.equals(method)) { doReport(req, resp); } else { super.service(req, resp); } } catch (Throwable e) { LOGGER.error("Unexpected throwable", e); } }
From source file:UrlServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //get the 'file' parameter String fileName = (String) request.getParameter("file"); if (fileName == null || fileName.equals("")) throw new ServletException("Invalid or non-existent file parameter in UrlServlet servlet."); if (fileName.indexOf(".pdf") == -1) fileName = fileName + ".pdf"; URL pdfDir = null;//from w w w .java 2 s . co m URLConnection urlConn = null; ServletOutputStream stream = null; BufferedInputStream buf = null; try { pdfDir = new URL(getServletContext().getInitParameter("remote-pdf-dir") + fileName); } catch (MalformedURLException mue) { throw new ServletException(mue.getMessage()); } try { stream = response.getOutputStream(); //set response headers response.setContentType("application/pdf"); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); urlConn = pdfDir.openConnection(); response.setContentLength((int) urlConn.getContentLength()); buf = new BufferedInputStream(urlConn.getInputStream()); int readBytes = 0; //read from the file; write to the ServletOutputStream while ((readBytes = buf.read()) != -1) stream.write(readBytes); } catch (IOException ioe) { throw new ServletException(ioe.getMessage()); } finally { if (stream != null) stream.close(); if (buf != null) buf.close(); } }