List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:org.shredzone.cilla.view.ResourceView.java
/** * Streams a resource./*ww w . j av a 2 s. co m*/ */ @View(pattern = "/resource/${#package}/${#name}", name = "resource") public void resourceView(@PathPart("#package") String pack, @PathPart("#name") String name, HttpServletRequest req, HttpServletResponse resp) throws ViewException { if (pack.indexOf("..") > -1 || pack.indexOf('/') > -1 || name.indexOf("..") > -1 || name.indexOf('/') > -1) { throw new PageNotFoundException("resource '" + pack + '/' + name + "' not found"); } try { String key = setup(pack, name); String resourceEtag = etagMap.get(key); resp.setHeader("ETag", resourceEtag); String headerEtag = req.getHeader("If-None-Match"); if (headerEtag != null && headerEtag.equals(resourceEtag)) { throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED); } if (isNotModifiedSince(req, lastModified)) { throw new ErrorResponseException(HttpServletResponse.SC_NOT_MODIFIED); } resp.setContentLength(sizeMap.get(key)); resp.setDateHeader("Last-Modified", lastModified.getTime()); try (InputStream in = ResourceView.class.getResourceAsStream("/public/" + pack + '/' + name)) { FileCopyUtils.copy(in, resp.getOutputStream()); } } catch (IOException ex) { throw new PageNotFoundException("resource '" + pack + '/' + name + "' not found"); } }
From source file:gsn.http.AddressingReqHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); String vsName = request.getParameter("name"); VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName); logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.") .toString());// w w w. ja va 2 s . co m StringBuilder sb = new StringBuilder("<virtual-sensor name=\"").append(vsName).append("\" last-modified=\"") .append(new File(sensorConfig.getFileName()).lastModified()).append("\">\n"); for (KeyValue df : sensorConfig.getAddressing()) sb.append("<predicate key=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString())).append("\">") .append(StringEscapeUtils.escapeXml(df.getValue().toString())).append("</predicate>\n"); sb.append("</virtual-sensor>"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); response.getWriter().write(sb.toString()); }
From source file:com.hyeb.back.controller.CommonController.java
/** * ??//w w w . j a v a 2s .c o m */ @RequestMapping(value = "/captcha", method = RequestMethod.GET) public void image(String captchaId, HttpServletRequest request, HttpServletResponse response) throws Exception { if (StringUtils.isEmpty(captchaId)) { captchaId = request.getSession().getId(); } String pragma = new StringBuffer().append("PowderBy").toString(); String value = new StringBuffer().append("hyeb").toString(); response.addHeader(pragma, value); response.setHeader("Pragma", "no-cache");//HTTP1.0Pragma ??Pragmano-cache,??????? Pragma response.setHeader("Cache-Control", "no-cache");// HTTP1.1?Cache-Control ???,no-cache????? response.setHeader("Cache-Control", "no-store");//HTTP1.1?Cache-Control ???no-store???? response.setDateHeader("Expires", 0);//Expires?GMT???????? response.setContentType("image/jpeg"); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); BufferedImage bufferedImage = captchaService.buildImage(captchaId); ImageIO.write(bufferedImage, "jpg", servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(servletOutputStream); } }
From source file:gsn.http.DataDownload.java
/** * List of the parameters for the requests: * url : /data//from ww w . j a v a2 s . c o m * Example: Getting all the data in CSV format => http://localhost:22001/data?vsName=memoryusage4&fields=heap&display=CSV * another example: http://localhost:22001/data?vsName=memoryusage4&fields=heap&fields=timed&display=CSV&delimiter=other&otherdelimiter=, * <p/> * param-name: vsName : the name of the virtual sensor we need. * param-name: fields [there can be multiple parameters with this name pointing to different fields in the stream element]. * param-name: commonReq (always true !) * param-name: display , if there is a value it should be CSV. * param-name: delimiter, useful for CSV output (can be "tab","space","other") * param-name: otherdelimiter useful in the case of having delimiter=other * param-name: groupby can point to one of the fields in the stream element. In case groupby=timed then the parameter groupbytimed points to the period for which data should be aggregated [in milliseconds]. * param-name: nb give the maximum number of elements to be outputed (most recent values first). * param-name: */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, java.io.IOException { // HttpSession session = req.getSession(); User user = (User) session.getAttribute("user"); res.setHeader("Cache-Control", "no-store"); res.setDateHeader("Expires", 0); res.setHeader("Pragma", "no-cache"); // PrintWriter respond = res.getWriter(); DataEnumerator result = null; try { SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat()); SimpleDateFormat sdf_from_ui = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); TimeZone timeZone = GregorianCalendar.getInstance().getTimeZone(); boolean responseCVS = false; boolean wantTimeStamp = false; boolean wantPk = false; boolean commonReq = true; boolean groupByTimed = false; String vsName = HttpRequestUtils.getStringParameter("vsName", null, req); if (vsName == null) vsName = HttpRequestUtils.getStringParameter("vsname", null, req); if (vsName == null) { res.sendError(WebConstants.MISSING_VSNAME_ERROR, "The virtual sensor name is missing"); return; } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss"); Date currentDate = Calendar.getInstance().getTime(); String filename = vsName + "_" + dateFormat.format(currentDate); if (Main.getContainerConfig().isAcEnabled() == true) { if (user != null) // meaning, that a login session is active, otherwise we couldn't get there if (user.hasReadAccessRight(vsName) == false && user.isAdmin() == false) // ACCESS_DENIED { res.sendError(WebConstants.ACCESS_DENIED, "Access denied to the specified virtual sensor ."); return; } } if (req.getParameter("display") != null && req.getParameter("display").equals("CSV")) { responseCVS = true; res.setContentType("text/csv"); //res.setContentType("text/html"); } else { res.setContentType("text/xml"); } if (req.getParameter("commonReq") != null && req.getParameter("commonReq").equals("false")) { commonReq = false; } String separator = ";"; if (req.getParameter("delimiter") != null && !req.getParameter("delimiter").equals("")) { String reqSeparator = req.getParameter("delimiter"); if (reqSeparator.equals("tab")) { separator = "\t"; } else if (reqSeparator.equals("space")) { separator = " "; } else if (reqSeparator.equals("other") && req.getParameter("otherdelimiter") != null && !req.getParameter("otherdelimiter").equals("")) { separator = req.getParameter("otherdelimiter"); } } String generated_request_query = ""; String expression = ""; String line = ""; String groupby = ""; String[] fields = req.getParameterValues("fields"); if (commonReq) { if (req.getParameter("fields") != null) { for (int i = 0; i < fields.length; i++) { if (fields[i].equals("timed")) { wantTimeStamp = true; } if ("pk".equalsIgnoreCase(fields[i])) wantPk = true; generated_request_query += ", " + fields[i]; } if (!wantPk) generated_request_query += ", pk"; } } else { if (req.getParameter("fields") == null) { respond.println("Request ERROR"); return; } else { for (int i = 0; i < fields.length; i++) { if (fields[i].equals("timed")) { wantTimeStamp = true; } if ("pk".equalsIgnoreCase(fields[i])) wantPk = true; generated_request_query += ", " + fields[i]; } if (!wantPk) generated_request_query += ", pk"; } if (req.getParameter("groupby") != null) { if (req.getParameter("groupby").equals("timed")) { groupByTimed = true; int periodmeasure = 1; if (req.getParameter("groupbytimed") != null) { periodmeasure = new Integer(req.getParameter("groupbytimed")); periodmeasure = java.lang.Math.max(periodmeasure, 1); } generated_request_query += ", Min(timed), FLOOR(timed/" + periodmeasure + ") period "; groupby = "GROUP BY period"; } else { groupby = "GROUP BY " + req.getParameter("groupby"); } } } String where = ""; if (req.getParameter("critfield") != null) { try { String[] critJoin = req.getParameterValues("critJoin"); String[] neg = req.getParameterValues("neg"); String[] critfields = req.getParameterValues("critfield"); String[] critop = req.getParameterValues("critop"); String[] critval = req.getParameterValues("critval"); for (int i = 0; i < critfields.length; i++) { if (critop[i].equals("LIKE")) { if (i > 0) { where += " " + critJoin[i - 1] + " " + neg[i] + " " + critfields[i] + " LIKE '%"; // + critval[i] + "%'"; } else { where += neg[i] + " " + critfields[i] + " LIKE '%"; // + critval[i] + "%'"; } if (critfields[i].equals("timed")) { try { //Date d = sdf.parse(critval[i]); Date d = sdf_from_ui.parse(critval[i]); where += d.getTime(); } catch (Exception e) { where += "0"; } } else { where += critval[i]; } where += "%'"; } else { if (i > 0) { where += " " + critJoin[i - 1] + " " + neg[i] + " " + critfields[i] + " " + critop[i] + " "; //critval[i]; } else { where += neg[i] + " " + critfields[i] + " " + critop[i] + " "; //critval[i]; } if (critfields[i].equals("timed")) { try { //Date d = sdf.parse(critval[i]); Date d = sdf_from_ui.parse(critval[i]); where += d.getTime(); } catch (Exception e) { where += "0"; } } else { where += critval[i]; } } } where = " WHERE " + where; } catch (NullPointerException npe) { where = " "; } } if (!generated_request_query.equals("")) { generated_request_query = generated_request_query.substring(2); if (!commonReq) { expression = generated_request_query; } generated_request_query = "select " + generated_request_query + " from " + vsName + where + " order by timed DESC "; if (commonReq) if (req.getParameter("nb") != null && req.getParameter("nb") != "") { int nb = new Integer(req.getParameter("nb")); if (nb < 0) nb = 0; String limit = ""; if (Main.getStorage(vsName).isH2() || Main.getStorage(vsName).isMysqlDB()) { if (nb >= 0) limit = "LIMIT " + nb + " offset 0"; generated_request_query += limit; } else if (Main.getStorage(vsName).isOracle()) { generated_request_query = "select * from (" + generated_request_query + " ) where rownum <" + (nb + 1); } } generated_request_query += " " + groupby; generated_request_query += ";"; if (req.getParameter("sql") != null) { res.setContentType("text/html"); respond.println("# " + generated_request_query); return; } try { result = Main.getStorage(vsName).streamedExecuteQuery(generated_request_query, true); } catch (SQLException e) { logger.error("ERROR IN EXECUTING, query: " + generated_request_query + " from " + req.getRemoteAddr() + "- " + req.getRemoteHost() + ": " + e.getMessage()); return; } if (!result.hasMoreElements()) { res.setContentType("text/html"); respond.println("No data corresponds to your request"); return; } //get units in hash map Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs(); HashMap<String, String> fieldToUnitMap = new HashMap<String, String>(); VSensorConfig sensorConfig = null; while (vsIterator.hasNext()) { VSensorConfig senConfig = vsIterator.next(); if (vsName.equalsIgnoreCase(senConfig.getName())) { sensorConfig = senConfig; DataField[] dataFieldArray = senConfig.getOutputStructure(); for (DataField df : dataFieldArray) { String unit = df.getUnit(); if (unit == null || unit.trim().length() == 0) unit = ""; fieldToUnitMap.put(df.getName().toLowerCase(), unit); } break; } } line = ""; int nbFields = 0; if (responseCVS) { boolean firstLine = true; res.setHeader("content-disposition", "attachment; filename=" + filename + ".csv"); respond.println("# " + generated_request_query); for (KeyValue df : sensorConfig.getAddressing()) { respond.println( "# " + df.getKey().toString().toLowerCase() + ":" + df.getValue().toString()); } respond.println("# description:" + sensorConfig.getDescription()); LinkedList<StreamElement> streamElements = new LinkedList<StreamElement>(); while (result.hasMoreElements()) { streamElements.add(result.nextElement()); } while (!streamElements.isEmpty()) { StreamElement se = streamElements.removeLast(); if (firstLine) { nbFields = se.getFieldNames().length; if (groupByTimed) { nbFields--; } if (wantTimeStamp) { line += separator + "time"; } for (int i = 0; i < nbFields; i++) //line += delimiter + se.getFieldNames()[i].toString(); if ((!groupByTimed) || (i != fields.length)) { line += separator + fields[i]; } else { line += separator + "time"; } firstLine = false; respond.println(line.substring(separator.length())); line = ""; //units (second line) if (wantTimeStamp) { line += separator + ""; } for (int i = 0; i < nbFields; i++) { if ((!groupByTimed) || (i != fields.length)) { line += separator + fieldToUnitMap.get(fields[i].toLowerCase()); } else { line += separator + ""; } } respond.println(line.substring(separator.length())); } line = ""; if (wantTimeStamp) { Date d = new Date(se.getTimeStamp()); line += separator + sdf.format(d); } for (int i = 0; i < nbFields; i++) //line += delimiter+se.getData( )[ i ].toString( ); if (!commonReq && ((i >= fields.length) || (fields[i].contains("timed")))) { line += separator + sdf.format(se.getData()[i]); } else { line += separator + se.getData()[i].toString(); } respond.println(line.substring(separator.length())); } } else { boolean firstLine = true; res.setHeader("content-disposition", "attachment; filename=" + filename + ".xml"); for (KeyValue df : sensorConfig.getAddressing()) { respond.println( "\t<!-- " + StringEscapeUtils.escapeXml(df.getKey().toString().toLowerCase()) + ":" + StringEscapeUtils.escapeXml(df.getValue().toString()) + " -->"); } respond.println("\t<!-- description:" + StringEscapeUtils.escapeXml(sensorConfig.getDescription()) + " -->"); respond.println("<data>"); LinkedList<StreamElement> streamElements = new LinkedList<StreamElement>(); while (result.hasMoreElements()) { streamElements.add(result.nextElement()); } while (!streamElements.isEmpty()) { StreamElement se = streamElements.removeLast(); if (firstLine) { respond.println("\t<line>"); nbFields = se.getFieldNames().length; if (groupByTimed) { nbFields--; } if (wantTimeStamp) { respond.println("\t\t<field unit=\"\">time</field>"); } for (int i = 0; i < nbFields; i++) { if ((!groupByTimed) || (i != fields.length)) { respond.print( "\t\t<field unit=\"" + fieldToUnitMap.get(fields[i].toLowerCase())); respond.println("\">" + fields[i] + "</field>"); } else { respond.println("\t\t<field unit=\"\">time</field>"); } } //} else { // out.println("\t\t<field>"+expression+"</field>"); //} respond.println("\t</line>"); firstLine = false; } line = ""; respond.println("\t<line>"); if (wantTimeStamp) { Date d = new Date(se.getTimeStamp()); respond.println("\t\t<field>" + sdf.format(d) + "</field>"); } for (int i = 0; i < nbFields; i++) { //if ( !commonReq && expression.contains("timed")) { if (!commonReq && ((i >= fields.length) || (fields[i].contains("timed")))) { respond.println("\t\t<field>" + sdf.format(se.getData()[i]) + "</field>"); } else { if (se.getData()[i] == null) respond.println("\t\t<field>Null</field>"); else respond.println("\t\t<field>" + se.getData()[i].toString() + "</field>"); } } respond.println("\t</line>"); } respond.println("</data>"); } } //*/ else { res.setContentType("text/html"); respond.println("Please select some fields"); } } finally { if (result != null) result.close(); respond.flush(); } }
From source file:org.eclipse.dirigible.runtime.registry.RegistryServlet.java
private boolean setCacheHeaders(IEntity entity, HttpServletRequest request, HttpServletResponse response) throws IOException { boolean cached = false; IEntityInformation entityInformation = entity.getInformation(); String modifiedSinceHeader = request.getHeader(IF_MODIFIED_SINCE_HEADER); if ((entityInformation != null)) { Calendar lastModified = getCalendar(entityInformation.getModifiedAt()); if ((!StringUtils.isEmpty(modifiedSinceHeader))) { Calendar modifiedSince = getCalendar(parseDate(modifiedSinceHeader)); if (lastModified.getTimeInMillis() <= modifiedSince.getTimeInMillis()) { Calendar expires = getCalendar(lastModified); expires.add(Calendar.MONTH, 1); response.setDateHeader(EXPIRES_HEADER, expires.getTimeInMillis()); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); cached = true;//from w ww . j a v a2 s . co m } } response.setDateHeader(LAST_MODIFIED_HEADER, lastModified.getTimeInMillis()); } return cached; }
From source file:org.openiot.gsn.http.AddressingReqHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setStatus(HttpServletResponse.SC_OK); String vsName = request.getParameter("name"); VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName); if (logger.isInfoEnabled()) logger.info(new StringBuilder().append("Structure request for *").append(vsName).append("* received.") .toString());/*from w ww. j ava2 s .c om*/ StringBuilder sb = new StringBuilder("<virtual-sensor name=\"").append(vsName).append("\" last-modified=\"") .append(new File(sensorConfig.getFileName()).lastModified()).append("\">\n"); for (KeyValue df : sensorConfig.getAddressing()) sb.append("<predicate key=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString())).append("\">") .append(StringEscapeUtils.escapeXml(df.getValue().toString())).append("</predicate>\n"); sb.append("</virtual-sensor>"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); response.getWriter().write(sb.toString()); }
From source file:org.sakaiproject.nakamura.http.cache.StaticContentResponseCacheImpl.java
private boolean responseWasFiltered(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain, CacheConfig cacheConfig) throws IOException, ServletException { if (!HttpConstants.METHOD_GET.equals(request.getMethod()) || cacheConfig == null || cacheConfig.getMaxAge() <= 0) { return false; // only GET is ever cacheable, and cacheConfig must exist and have a nonzero maxAge }//w w w . j a v a2s . co m CachedResponse cachedResponse = getCachedResponse(request); if (cachedResponse != null && cachedResponse.isValid()) { TelemetryCounter.incrementValue("http", "StaticContentResponseCacheImpl-hit", getCacheKey(request)); cachedResponse.replay(response); return true; } Long expires = System.currentTimeMillis() + (cacheConfig.getMaxAge() * 1000L); response.setDateHeader("Expires", expires); FilterResponseWrapper filterResponseWrapper = new FilterResponseWrapper(response, false, false, true); filterChain.doFilter(request, filterResponseWrapper); filterResponseWrapper.setDateHeader("Expires", expires); saveCachedResponse(request, filterResponseWrapper.getResponseOperation(), cacheConfig); return true; }
From source file:com.octo.captcha.module.acegi.JCaptchaSoundController.java
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse response) throws Exception { byte[] captchaChallengeAsWav = null; ByteArrayOutputStream wavOutputStream = new ByteArrayOutputStream(); //get the session id that will identify the generated captcha. //the same id must be used to validate the response, the session id is a good candidate! String captchaId = httpServletRequest.getSession().getId(); AudioInputStream challenge = soundCaptchaService.getSoundChallengeForID(captchaId, httpServletRequest.getLocale()); // a jpeg encoder AudioInputStream stream = (AudioInputStream) challenge; // call the ImageCaptchaService method to retrieve a captcha AudioSystem.write(stream, AudioFileFormat.Type.WAVE, wavOutputStream); captchaChallengeAsWav = wavOutputStream.toByteArray(); // configure cache directives response.setHeader("Cache-Control", "no-store"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); //flush content in the response response.setContentType("audio/x-wav"); ServletOutputStream responseOutputStream = response.getOutputStream(); responseOutputStream.write(captchaChallengeAsWav); responseOutputStream.flush();//from w ww . jav a2 s . c o m responseOutputStream.close(); return null; }
From source file:com.pronoiahealth.olhie.server.rest.TVServiceImpl.java
/** * @see com.pronoiahealth.olhie.server.rest.TVService#getVideo(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.String, * javax.servlet.ServletContext)//from w ww .ja v a 2 s .co m */ @Override @GET @Path("/tv/{uniqueNumb}/{programRef}") // @Produces({"application/pdf", "application/octet-stream", "text/html"}) @Produces({ "application/octet-stream" }) @SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR, SecurityRoleEnum.REGISTERED, SecurityRoleEnum.ANONYMOUS }) public InputStream getVideo(@Context HttpServletRequest request, @Context HttpServletResponse response, @PathParam("programRef") String programRef, @Context ServletContext context) throws ServletException, IOException, FileDownloadException { DataInputStream in = null; try { // Get the file contents File programFile = findFile(programRef); if (programFile == null) { throw new FileDownloadException(String.format("Could not find file for id %s", programRef)); } String fileName = programRef.substring(programRef.lastIndexOf("|")); String mimetype = context.getMimeType(fileName); // Base64 unencode byte[] fileBytes = FileUtils.readFileToByteArray(programFile); response.setContentType((mimetype != null) ? mimetype : "application/octet-stream"); // No image caching response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); // response.setContentLength(fileBytes.length); // response.setHeader("Content-Disposition", "inline; filename=" // + fileName); in = new DataInputStream(new ByteArrayInputStream(fileBytes)); return in; } catch (Exception e) { log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e); if (e instanceof FileDownloadException) { throw (FileDownloadException) e; } else { throw new FileDownloadException(e); } } finally { if (in != null) { in.close(); } } }