List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
/** * Handles a YaCy servlet template, reads the template and replaces the template * items with actual values. Because of supported server side includes target * might not be the same as request.getPathInfo * /* w w w.ja va 2 s . c o m*/ * @param target the path to the template * @param request the remote servlet request * @param response * @throws IOException * @throws ServletException */ protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { Switchboard sb = Switchboard.getSwitchboard(); String localeSelection = sb.getConfig("locale.language", "browser"); if (localeSelection.endsWith("browser")) { String lng = request.getLocale().getLanguage(); if (lng.equalsIgnoreCase("en")) { // because en is handled as "default" in localizer localeSelection = "default"; } else { localeSelection = lng; } } File targetFile = getLocalizedFile(target, localeSelection); File targetClass = rewriteClassFile(_resourceBase.addPath(target).getFile()); String targetExt = target.substring(target.lastIndexOf('.') + 1); long now = System.currentTimeMillis(); if (target.endsWith(".css")) { response.setDateHeader(HeaderFramework.LAST_MODIFIED, now); response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour (which is still often, others use 1 week, month or year) } else if (target.endsWith(".png")) { // expires in 1 minute (reduce heavy image creation load) if (response.containsHeader(HeaderFramework.LAST_MODIFIED)) { response.getHeaders(HeaderFramework.LAST_MODIFIED).clear(); } response.setHeader(HeaderFramework.CACHE_CONTROL, "public, max-age=" + Integer.toString(60)); } else { response.setDateHeader(HeaderFramework.LAST_MODIFIED, now); response.setDateHeader(HeaderFramework.EXPIRES, now); // expires now } if ((targetClass != null)) { serverObjects args = new serverObjects(); Enumeration<String> argNames = request.getParameterNames(); // on ssi jetty dispatcher merged local ssi query parameters while (argNames.hasMoreElements()) { String argName = argNames.nextElement(); // standard attributes are just pushed as string args.put(argName, request.getParameter(argName)); } RequestHeader legacyRequestHeader = generateLegacyRequestHeader(request, target, targetExt); // add multipart-form fields to parameter if (ServletFileUpload.isMultipartContent(request)) { final String bodyEncoding = request.getHeader(HeaderFramework.CONTENT_ENCODING); if (HeaderFramework.CONTENT_ENCODING_GZIP.equalsIgnoreCase(bodyEncoding)) { parseMultipart(new GZIPRequestWrapper(request), args); } else { parseMultipart(request, args); } } // eof modification to read attribute Object tmp; try { if (args.isEmpty()) { // yacy servlets typically test for args != null (but not for args .isEmpty()) tmp = invokeServlet(targetClass, legacyRequestHeader, null); } else { tmp = invokeServlet(targetClass, legacyRequestHeader, args); } } catch (InvocationTargetException e) { if (e.getCause() instanceof InvalidURLLicenceException) { /* A non authaurized user is trying to fetch a image with a bad or already released license code */ response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage()); return; } if (e.getCause() instanceof TemplateMissingParameterException) { /* A template is used but miss some required parameter */ response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getCause().getMessage()); return; } ConcurrentLog.logException(e); throw new ServletException(targetFile.getAbsolutePath()); } catch (IllegalArgumentException | IllegalAccessException e) { ConcurrentLog.logException(e); throw new ServletException(targetFile.getAbsolutePath()); } if (tmp instanceof RasterPlotter || tmp instanceof EncodedImage || tmp instanceof Image) { net.yacy.cora.util.ByteBuffer result = null; if (tmp instanceof RasterPlotter) { final RasterPlotter yp = (RasterPlotter) tmp; // send an image to client result = RasterPlotter.exportImage(yp.getImage(), "png"); } else if (tmp instanceof EncodedImage) { final EncodedImage yp = (EncodedImage) tmp; result = yp.getImage(); /** When encodedImage is empty, return a code 500 rather than only an empty response * as it is better handled across different browsers */ if (result == null || result.length() == 0) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); result.close(); return; } if (yp.isStatic()) { // static image never expires response.setDateHeader(HeaderFramework.EXPIRES, now + 3600000); // expires in 1 hour } } else if (tmp instanceof Image) { final Image i = (Image) tmp; // generate an byte array from the generated image int width = i.getWidth(null); if (width < 0) { width = 96; // bad hack } int height = i.getHeight(null); if (height < 0) { height = 96; // bad hack } final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); bi.createGraphics().drawImage(i, 0, 0, width, height, null); result = RasterPlotter.exportImage(bi, targetExt); } updateRespHeadersForImages(target, response); final String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString()); response.setContentType(mimeType); response.setContentLength(result.length()); response.setStatus(HttpServletResponse.SC_OK); result.writeTo(response.getOutputStream()); result.close(); return; } if (tmp instanceof InputStream) { /* Images and favicons can also be written directly from an inputStream */ updateRespHeadersForImages(target, response); writeInputStream(response, targetExt, (InputStream) tmp); return; } servletProperties templatePatterns; if (tmp == null) { // if no args given, then tp will be an empty Hashtable object (not null) templatePatterns = new servletProperties(); } else if (tmp instanceof servletProperties) { templatePatterns = (servletProperties) tmp; if (templatePatterns.getOutgoingHeader() != null) { // handle responseHeader entries set by servlet ResponseHeader tmpouthdr = templatePatterns.getOutgoingHeader(); for (String hdrkey : tmpouthdr.keySet()) { if (!HeaderFramework.STATUS_CODE.equals(hdrkey)) { // skip default init response status value (not std. ) String val = tmpouthdr.get(hdrkey); if (!response.containsHeader(hdrkey) && val != null) { // to be on the safe side, add only new hdr (mainly used for CORS_ALLOW_ORIGIN) response.setHeader(hdrkey, tmpouthdr.get(hdrkey)); } } } // handle login cookie if (tmpouthdr.getCookiesEntries() != null) { for (Cookie c : tmpouthdr.getCookiesEntries()) { response.addCookie(c); } } } } else { templatePatterns = new servletProperties((serverObjects) tmp); } // handle YaCy http commands // handle action auth: check if the servlets requests authentication if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) { if (!request.authenticate(response)) { return; } //handle action forward } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) { String location = templatePatterns.get(serverObjects.ACTION_LOCATION, ""); if (location.isEmpty()) { location = request.getPathInfo(); } //TODO: handle equivalent of this from httpdfilehandler // final ResponseHeader headers = getDefaultHeaders(request.getPathInfo()); // headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble? response.setHeader(HeaderFramework.LOCATION, location); response.setStatus(HttpServletResponse.SC_FOUND); return; } if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) { sb.setConfig("server.servlets.called", appendPath(sb.getConfig("server.servlets.called", ""), target)); if (args != null && !args.isEmpty()) { sb.setConfig("server.servlets.submitted", appendPath(sb.getConfig("server.servlets.submitted", ""), target)); } // add the application version, the uptime and the client name to every rewrite table templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion()); templatePatterns.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - sb.startupTime) / 1000) / 60); // uptime in minutes templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName()); templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, sb.peers.myID()); templatePatterns.put(servletProperties.PEER_STAT_MYTIME, GenericFormatter.SHORT_SECOND_FORMATTER.format()); templatePatterns.put(servletProperties.RELATIVE_BASE, YaCyDefaultServlet.getRelativeBase(target)); Seed myPeer = sb.peers.mySeed(); templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1); templatePatterns.putHTML("newpeer_peerhash", myPeer.hash); boolean authorized = sb.adminAuthenticated(legacyRequestHeader) >= 2; templatePatterns.put("authorized", authorized ? 1 : 0); // used in templates and other html (e.g. to display lock/unlock symbol) templatePatterns.put("simpleheadernavbar", sb.getConfig("decoration.simpleheadernavbar", "navbar-default")); // add navigation keys to enable or disable menu items templatePatterns.put("navigation-p2p", sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0); templatePatterns.put("navigation-p2p_authorized", authorized ? 1 : 0); String submitted = sb.getConfig("server.servlets.submitted", ""); boolean crawler_enabled = true; /* submitted.contains("Crawler_p") || submitted.contains("ConfigBasic") || submitted.contains("Load_RSS_p");*/ boolean advanced_enabled = crawler_enabled || submitted.contains("IndexImportMediawiki_p") || submitted.contains("CrawlStart"); templatePatterns.put("navigation-crawlmonitor", crawler_enabled); templatePatterns.put("navigation-crawlmonitor_authorized", authorized ? 1 : 0); templatePatterns.put("navigation-advanced", advanced_enabled); templatePatterns.put("navigation-advanced_authorized", authorized ? 1 : 0); templatePatterns.put(SwitchboardConstants.GREETING_HOMEPAGE, sb.getConfig(SwitchboardConstants.GREETING_HOMEPAGE, "")); templatePatterns.put(SwitchboardConstants.GREETING_SMALL_IMAGE, sb.getConfig(SwitchboardConstants.GREETING_SMALL_IMAGE, "")); templatePatterns.put(SwitchboardConstants.GREETING_IMAGE_ALT, sb.getConfig(SwitchboardConstants.GREETING_IMAGE_ALT, "")); templatePatterns.put("clientlanguage", localeSelection); String mimeType = Classification.ext2mime(targetExt, MimeTypes.Type.TEXT_HTML.asString()); InputStream fis; long fileSize = targetFile.length(); if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) { // read file completely into ram, avoid that too many files are open at the same time fis = new ByteArrayInputStream(FileUtils.read(targetFile)); } else { fis = new BufferedInputStream(new FileInputStream(targetFile)); } // set response header response.setContentType(mimeType); response.setStatus(HttpServletResponse.SC_OK); ByteArrayOutputStream bas = new ByteArrayOutputStream(4096); try { // apply templates TemplateEngine.writeTemplate(targetFile.getName(), fis, bas, templatePatterns); // handle SSI parseSSI(bas.toByteArray(), request, response); } finally { try { fis.close(); } catch (IOException ignored) { ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: could not close target file " + targetFile.getName()); } try { bas.close(); } catch (IOException ignored) { /* Should never happen with a ByteArrayOutputStream */ } } } } }
From source file:com.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java
@Override public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (baseRequest.isHandled()) { return;// w w w . j a v a 2 s .c o m } String pathInfo = request.getPathInfo(); // Only serve the content if the request matches the base path. if (pathInfo == null || !pathInfo.startsWith(basePath)) { return; } pathInfo = pathInfo.substring(basePath.length()); if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) { // basepath is /foo and request went to /foobar --> pathInfo starts with bar // basepath is /foo and request went to /foo --> pathInfo should be /index.html return; } // Allow index.html as welcome file if ("/".equals(pathInfo) || "".equals(pathInfo)) { pathInfo = "/index.html"; } boolean skipContent = false; // When a request hits this handler, it will serve something. Either data or an error. baseRequest.setHandled(true); final String method = request.getMethod(); if (!StringUtils.equals(HttpMethods.GET, method)) { if (StringUtils.equals(HttpMethods.HEAD, method)) { skipContent = true; } else { response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } } // Does the request contain an IF_MODIFIED_SINCE header? final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } InputStream resourceStream = null; try { if (pathInfo.startsWith("/")) { final String resourcePath = resourceLocation + pathInfo; resourceStream = getClass().getResourceAsStream(resourcePath); } if (resourceStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo()); if (mime != null) { response.setContentType(mime.toString("ISO8859-1")); } response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L); if (skipContent) { return; } // Send the content out. Lifted straight out of ResourceHandler.java OutputStream out = null; try { out = response.getOutputStream(); } catch (IllegalStateException e) { out = new WriterOutputStream(response.getWriter()); } if (out instanceof AbstractHttpConnection.Output) { ((AbstractHttpConnection.Output) out).sendContent(resourceStream); } else { ByteStreams.copy(resourceStream, out); } } finally { IOUtils.closeQuietly(resourceStream); } }
From source file:org.openiot.gsn.http.OneShotQueryHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { SimpleDateFormat sdf = new SimpleDateFormat(Main.getInstance().getContainerConfig().getTimeFormat()); String vsName = request.getParameter("name"); String vsCondition = request.getParameter("condition"); if (vsCondition == null || vsCondition.trim().length() == 0) vsCondition = " "; else/*from w w w . j a v a2s .c o m*/ vsCondition = " where " + vsCondition; String vsFields = request.getParameter("fields"); if (vsFields == null || vsFields.trim().length() == 0 || vsFields.trim().equals("*")) vsFields = "*"; else vsFields += " , pk, timed"; String windowSize = request.getParameter("window"); if (windowSize == null || windowSize.trim().length() == 0) windowSize = "1"; StringBuilder query = new StringBuilder("select " + vsFields + " from " + vsName + vsCondition + " order by timed DESC limit " + windowSize + " offset 0"); DataEnumerator result; try { result = Main.getStorage(vsName).executeQuery(query, true); } catch (SQLException e) { logger.error("ERROR IN EXECUTING, query: " + query); logger.error(e.getMessage(), e); logger.error("Query is from " + request.getRemoteAddr() + "- " + request.getRemoteHost()); return; } StringBuilder sb = new StringBuilder("<result>\n"); while (result.hasMoreElements()) { StreamElement se = result.nextElement(); sb.append("<stream-element>\n"); for (int i = 0; i < se.getFieldNames().length; i++) { sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\" >"); if (se.getData()[i] != null) if (se.getFieldTypes()[i] == DataTypes.BINARY) sb.append(se.getData()[i].toString()); else sb.append(StringEscapeUtils.escapeXml(se.getData()[i].toString())); sb.append("</field>\n"); } sb.append("<field name=\"timed\" >").append(sdf.format(new Date(se.getTimeStamp()))) .append("</field>\n"); sb.append("</stream-element>\n"); } result.close(); sb.append("</result>"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache"); response.getWriter().write(sb.toString()); }
From source file:com.github.zhanhb.ckfinder.download.PathPartial.java
/** * Serve the specified resource, optionally including the data content. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param content Should the content be included? * @param path the resource to serve//w ww . j a va 2s . co m * * @exception IOException if an input/output error occurs */ private void serveResource(HttpServletRequest request, HttpServletResponse response, boolean content, Path path) throws IOException, ServletException { ActionContext context = new ActionContext().put(HttpServletRequest.class, request) .put(HttpServletResponse.class, response).put(ServletContext.class, request.getServletContext()) .put(Path.class, path); if (path == null) { notFound.handle(context); return; } BasicFileAttributes attr; try { attr = Files.readAttributes(path, BasicFileAttributes.class); } catch (IOException ex) { notFound.handle(context); return; } context.put(BasicFileAttributes.class, attr); boolean isError = response.getStatus() >= HttpServletResponse.SC_BAD_REQUEST; // Check if the conditions specified in the optional If headers are // satisfied. // Checking If headers boolean included = (request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH) != null); String etag = this.eTag.getValue(context); if (!included && !isError && !checkIfHeaders(request, response, attr, etag)) { return; } // Find content type. String contentType = contentTypeResolver.getValue(context); // Get content length long contentLength = attr.size(); // Special case for zero length files, which would cause a // (silent) ISE boolean serveContent = content && contentLength != 0; Range[] ranges = null; if (!isError) { if (useAcceptRanges) { // Accept ranges header response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes"); } // Parse range specifier ranges = serveContent ? parseRange(request, response, attr, etag) : FULL; // ETag header response.setHeader(HttpHeaders.ETAG, etag); // Last-Modified header response.setDateHeader(HttpHeaders.LAST_MODIFIED, attr.lastModifiedTime().toMillis()); } ServletOutputStream ostream = null; if (serveContent) { ostream = response.getOutputStream(); } String disposition = contentDisposition.getValue(context); if (disposition != null) { response.setHeader(HttpHeaders.CONTENT_DISPOSITION, disposition); } // Check to see if a Filter, Valve of wrapper has written some content. // If it has, disable range requests and setting of a content length // since neither can be done reliably. if (isError || ranges == FULL) { // Set the appropriate output headers if (contentType != null) { log.debug("serveFile: contentType='{}'", contentType); response.setContentType(contentType); } if (contentLength >= 0) { setContentLengthLong(response, contentLength); } // Copy the input stream to our output stream (if requested) if (serveContent) { log.trace("Serving bytes"); Files.copy(path, ostream); } } else if (ranges != null && ranges.length != 0) { // Partial content response. response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.length == 1) { Range range = ranges[0]; response.addHeader(HttpHeaders.CONTENT_RANGE, range.toString()); long length = range.end - range.start + 1; setContentLengthLong(response, length); if (contentType != null) { log.debug("serveFile: contentType='{}'", contentType); response.setContentType(contentType); } if (serveContent) { try (InputStream stream = Files.newInputStream(path)) { copyRange(stream, ostream, range, new byte[Math.min((int) length, 8192)]); } } } else { response.setContentType("multipart/byteranges; boundary=" + MIME_SEPARATION); if (serveContent) { copy(path, ostream, ranges, contentType, new byte[Math.min((int) contentLength, 8192)]); } } } }
From source file:org.osaf.cosmo.webcal.WebcalServlet.java
/** * Handles GET requests for calendar collections. Returns a 200 * <code>text/calendar</code> response containing an iCalendar * representation of all of the calendar items within the * collection./*from ww w .j a v a 2s . co m*/ * * Returns 404 if the request's path info does not specify a * collection path or if the identified collection is not found. * * Returns 405 if the item with the identified uid is not a * calendar collection. */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (log.isDebugEnabled()) log.debug("handling GET for " + req.getPathInfo()); // requests will usually come in with the collection's display // name appended to the collection path so that clients will // save the file with that name CollectionPath cp = CollectionPath.parse(req.getPathInfo(), true); if (cp == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } Item item; try { item = contentService.findItemByUid(cp.getUid()); } // handle security errors by returing 403 catch (CosmoSecurityException e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; } if (item == null) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } if (!(item instanceof CollectionItem)) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a collection"); return; } CollectionItem collection = (CollectionItem) item; if (StampUtils.getCalendarCollectionStamp(collection) == null) { resp.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Requested item not a calendar collection"); return; } EntityTag etag = new EntityTag(collection.getEntityTag()); // set ETag resp.setHeader("ETag", etag.toString()); // check for If-None-Match EntityTag[] requestEtags = getIfNoneMatch(req); if (requestEtags != null && requestEtags.length != 0) { if (EntityTag.matchesAny(etag, requestEtags)) { resp.setStatus(304); return; } } // check for If-Modified-Since long since = req.getDateHeader("If-Modified-Since"); // If present and if collection's modified date not more recent, // return 304 not modified if (since != -1) { long lastModified = collection.getModifiedDate().getTime() / 1000 * 1000; if (lastModified <= since) { resp.setStatus(304); return; } } // set Last-Modified resp.setDateHeader("Last-Modified", collection.getModifiedDate().getTime()); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType(ICALENDAR_MEDIA_TYPE); resp.setCharacterEncoding("UTF-8"); // send Content-Disposition to provide another hint to clients // on how to save and name the downloaded file String filename = collection.getDisplayName() + "." + ICALENDAR_FILE_EXTENSION; resp.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); // get icalendar Calendar calendar = entityConverter.convertCollection(collection); // Filter if necessary so we play nicely with clients // that don't adhere to spec if (clientFilterManager != null) clientFilterManager.filterCalendar(calendar); // spool ICalendarOutputter.output(calendar, resp.getOutputStream()); }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w . ja v a 2s . c o m LOG.info("Doing Head "); snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); if (n == null) { response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String version = rp.getVersion(); if (version != null) { try { n = n.getVersionHistory().getVersion(version); } catch (VersionException e) { throw new SDataAccessException(HttpServletResponse.SC_NOT_FOUND, e.getMessage()); } n = n.getNode(JCRConstants.JCR_FROZENNODE); } Node resource = n.getNode(JCRConstants.JCR_CONTENT); Property lastModified = resource.getProperty(JCRConstants.JCR_LASTMODIFIED); Property mimeType = resource.getProperty(JCRConstants.JCR_MIMETYPE); Property content = resource.getProperty(JCRConstants.JCR_DATA); response.setContentType(mimeType.getString()); if (mimeType.getString().startsWith("text")) { if (resource.hasProperty(JCRConstants.JCR_ENCODING)) { Property encoding = resource.getProperty(JCRConstants.JCR_ENCODING); response.setCharacterEncoding(encoding.getString()); } } response.setDateHeader(LAST_MODIFIED, lastModified.getDate().getTimeInMillis()); // we need to do something about huge files response.setContentLength((int) content.getLength()); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { sendError(request, response, e); snoopRequest(request); LOG.error("Failed TO service Request ", e); } }
From source file:com.us.servlet.AuthCode.java
protected void service(HttpServletRequest request, HttpServletResponse response) { final CodeAuth bean = AppHelper.CODE_AUTH; int width = NumberUtils.toInt(request.getParameter("width"), bean.getWidth()); int height = NumberUtils.toInt(request.getParameter("height"), bean.getHeight()); int x = width / (bean.getLength() + 1); int codeY = height - 4; int fontHeight = height - 2; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); Graphics2D graphics = image.createGraphics(); graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); if (StringUtil.hasText(request.getParameter("bgcolor"))) { graphics.setBackground(ColorHelper.hex2RGB(request.getParameter("bgcolor"))); }//from w w w. jav a 2 s. c o m graphics.fillRect(0, 0, width, height); graphics.setFont(new Font(bean.getFont(), Font.BOLD, fontHeight)); graphics.drawRect(0, 0, width - 1, height - 1); // if (bean.isBreakLine()) { for (int i = 0; i < 15; i++) { int x1 = RandomUtils.nextInt(width); int y1 = RandomUtils.nextInt(height); int x2 = RandomUtils.nextInt(12); int y2 = RandomUtils.nextInt(12); graphics.drawLine(x1, y1, x + x2, y1 + y2); } } char[] CHARSET_AREA = null; if (bean.getType().charAt(0) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, BIG_LETTERS); } if (bean.getType().charAt(1) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, SMALL_LETTER); } if (bean.getType().charAt(2) == '1') { CHARSET_AREA = ArrayUtils.addAll(CHARSET_AREA, NUMBERS); } StringBuilder randomCode = new StringBuilder(); for (int i = 0; i < bean.getLength(); i++) { String rand = String.valueOf(CHARSET_AREA[RandomUtils.nextInt(CHARSET_AREA.length)]); graphics.setColor(ColorHelper.color(RandomUtils.nextInt(255), RandomUtils.nextInt(255), RandomUtils.nextInt(255))); graphics.drawString(rand, (i + 1) * x, codeY); randomCode.append(rand); } HttpSession session = request.getSession(); session.setAttribute(bean.getSessionKey(), randomCode.toString()); // ? response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/png"); try { // Servlet? ServletOutputStream sos = response.getOutputStream(); ImageIO.write(image, "png", sos); sos.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.openmrs.module.atomfeed.web.AtomFeedDownloadServlet.java
/** * This method is called by the servlet container to process a HEAD request made by RSS readers * against the /atomfeed URI//from ww w . j a v a 2 s. co m * * @see javax.servlet.http.HttpServlet#doHead(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) * @should send not modified error if atom feed has not changed * @should send valid headers if atom feed has changed */ public void doHead(HttpServletRequest req, HttpServletResponse resp) throws IOException { // read atomfeed header specific information from the header file String headerFileContent = AtomFeedUtil.readFeedHeaderFile(); int contentLength = 0; String etagToken = ""; Date lastModified = null; if (StringUtils.isNotBlank(headerFileContent)) { contentLength = headerFileContent.length() + Integer .valueOf(StringUtils.substringBetween(headerFileContent, "<entriesSize>", "</entriesSize>")); etagToken = StringUtils.substringBetween(headerFileContent, "<versionId>", "</versionId>"); try { lastModified = new SimpleDateFormat(AtomFeedUtil.RFC_3339_DATE_FORMAT) .parse(StringUtils.substringBetween(headerFileContent, "<updated>", "</updated>")); } catch (ParseException e) { // ignore it here } } // set the content length and type resp.setContentLength(contentLength); resp.setContentType("application/atom+xml"); resp.setCharacterEncoding("UTF-8"); // compare previous ETag token with current one String previousEtagToken = req.getHeader("If-None-Match"); Calendar ifModifiedSince = Calendar.getInstance(); long ifModifiedSinceInMillis = req.getDateHeader("If-Modified-Since"); ifModifiedSince.setTimeInMillis(ifModifiedSinceInMillis); if (((etagToken != null) && (previousEtagToken != null && previousEtagToken.equals('"' + etagToken + '"'))) || (ifModifiedSinceInMillis > 0 && ifModifiedSince.getTime().compareTo(lastModified) >= 0)) { // send 304 status code that indicates that resource has not been modified resp.sendError(HttpServletResponse.SC_NOT_MODIFIED); // re-use original last modified time-stamp resp.setHeader("Last-Modified", req.getHeader("If-Modified-Since")); // no further processing required return; } // set header for the next time the client calls if (etagToken != null) { resp.setHeader("ETag", '"' + etagToken + '"'); // set the last modified time if it's already specified if (lastModified == null) { // otherwise set the last modified time to now Calendar cal = Calendar.getInstance(); cal.set(Calendar.MILLISECOND, 0); lastModified = cal.getTime(); } resp.setDateHeader("Last-Modified", lastModified.getTime()); } }
From source file:org.apache.karaf.services.mavenproxy.internal.MavenProxyServletTest.java
private Map<String, String> testUpload(String path, final byte[] contents, String location, String profile, String version, boolean hasLocationHeader) throws Exception { final String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); FileUtils.deleteDirectory(new File("target/tmp")); Server server = new Server(0); server.setHandler(new AbstractHandler() { @Override/* ww w .j a v a2 s. c om*/ public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }); server.start(); try { int localPort = ((NetworkConnector) server.getConnectors()[0]).getLocalPort(); MavenResolver resolver = createResolver("target/tmp", "http://relevant.not/maven2@id=central", "http", "localhost", localPort, "fuse", "fuse", null); MavenProxyServlet servlet = new MavenProxyServlet(resolver, 5, null, null, null); HttpServletRequest request = EasyMock.createMock(HttpServletRequest.class); EasyMock.expect(request.getPathInfo()).andReturn(path); EasyMock.expect(request.getInputStream()).andReturn(new ServletInputStream() { private int i; @Override public int read() throws IOException { if (i >= contents.length) { return -1; } return (contents[i++] & 0xFF); } }); EasyMock.expect(request.getHeader("X-Location")).andReturn(location); final Map<String, String> headers = new HashMap<>(); HttpServletResponse rm = EasyMock.createMock(HttpServletResponse.class); HttpServletResponse response = new HttpServletResponseWrapper(rm) { @Override public void addHeader(String name, String value) { headers.put(name, value); } }; response.setStatus(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentLength(EasyMock.anyInt()); EasyMock.expectLastCall().anyTimes(); response.setContentType((String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); response.setDateHeader((String) EasyMock.anyObject(), EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); response.setHeader((String) EasyMock.anyObject(), (String) EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(request, rm); servlet.init(); servlet.doPut(request, response); EasyMock.verify(request, rm); Assert.assertEquals(hasLocationHeader, headers.containsKey("X-Location")); return headers; } finally { server.stop(); if (old != null) { System.setProperty("karaf.data", old); } } }
From source file:nl.isaac.dotcms.minify.servlet.MinifyServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Check if the "uris" parameter is valid String urisAsString = request.getParameter("uris"); ParamValidationUtil.validateParamNotNull(urisAsString, "uris"); // Define variables whos content will be determined during the for loop. StringBuilder fileContentOfUris = new StringBuilder(); boolean isContentModified = false; ContentType overAllContentType = null; // Retrieve data that is used in the for loop only once for speed boolean isDebugMode = UtilMethods.isSet(request.getParameter("debug")); boolean isLiveMode = HostTools.isLiveMode(request); Date ifModifiedSince = new Date(request.getDateHeader("If-Modified-Since")); Host defaultHost = HostTools.getCurrentHost(request); try {/*from www . j av a2s. c om*/ for (String uriAsString : StringListUtil.getCleanStringList(urisAsString)) { URI uri = new URI(uriAsString); ContentType currentContentType = ContentType.getContentType(uri); overAllContentType = overAllContentType == null ? currentContentType : overAllContentType; if (currentContentType == overAllContentType) { Host host = getHostOfUri(uri, defaultHost); if (isDebugMode) { fileContentOfUris.append(getOriginalFile(uri, host, isLiveMode)); isContentModified = true; } else { MinifyCacheKey key = new MinifyCacheKey(uri.getPath(), host.getHostname(), isLiveMode); MinifyCacheFile file = MinifyCacheHandler.INSTANCE.get(key); fileContentOfUris.append(file.getFileData()); Date modDate = file.getModDate(); isContentModified |= modDate.compareTo(ifModifiedSince) >= 0; } } else { Logger.warn(MinifyServlet.class, "Encountered uri with different contentType than the others, skipping file. Expected " + overAllContentType.extension + ", found: " + currentContentType.extension); } } response.setContentType(overAllContentType.contentTypeString); response.addHeader("Cache-Control", "public, max-age=" + BROWSER_CACHE_MAX_AGE); response.setDateHeader("Expires", new Date().getTime() + (BROWSER_CACHE_MAX_AGE * 1000)); if (isContentModified) { response.setDateHeader("Last-Modified", new Date().getTime()); response.getWriter().write(fileContentOfUris.toString()); } else { // No files are modified since the browser cached it, so send // status 304. Browser will then use the file from his cache response.setStatus(304); } } catch (DotCMSFileNotFoundException e) { Logger.error(MinifyServlet.class, "One or more files can't be found in dotCMS, sending 404 response", e); response.sendError(404); } catch (URISyntaxException e) { Logger.error(MinifyServlet.class, "Cannot parse one or more URIs", e); response.sendError(404); } }