List of usage examples for javax.servlet.http HttpServletResponse setDateHeader
public void setDateHeader(String name, long date);
From source file:org.restcomm.connect.http.filters.FileCacheServlet.java
/** * Process the actual request.//from w w w.jav a 2s .com * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not * (HEAD). * @throws IOException If something fails at I/O level. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException { // Validate the requested file ------------------------------------------------------------ // Get requested file by path info. String requestedFile = request.getPathInfo(); if (logger.isDebugEnabled()) { logger.debug("Requested path:" + requestedFile); } // Check if file is actually supplied to the request URL. if (requestedFile == null) { logger.debug("No file requested, return 404."); // Do your thing if the file is not supplied to the request URL. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Configuration rootConfiguration = (Configuration) request.getServletContext() .getAttribute(Configuration.class.getName()); Configuration runtimeConfiguration = rootConfiguration.subset("runtime-settings"); String basePath = runtimeConfiguration.getString("cache-path"); int bufferSize = runtimeConfiguration.getInteger("cache-buffer-size", DEFAULT_BUFFER_SIZE); long expireTime = runtimeConfiguration.getLong("cache-expire-time", DEFAULT_EXPIRE_TIME); // URL-decode the file name (might contain spaces and on) and prepare file object. String fDecodedPath = URLDecoder.decode(requestedFile, "UTF-8"); File file = new File(basePath, fDecodedPath); // Check if file actually exists in filesystem. if (!file.exists()) { logger.debug("Requested file not found, return 404."); // Do your thing if the file appears to be non-existing. // Throw an exception, or send 404, or show default/warning page, or just ignore it. response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; long expires = System.currentTimeMillis() + expireTime; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { logger.debug("IfNoneMatch/Etag not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { logger.debug("IfModifiedSince not matching, return 304."); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); response.setHeader("ETag", eTag); // Required in 304. response.setDateHeader("Expires", expires); // Postpone cache with 1 week. return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { logger.debug("ifMatch not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { logger.debug("ifUnmodifiedSince not matching, return 412."); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and content disposition. String contentType = getServletContext().getMimeType(fileName); String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, expand content type with the one and right character encoding. if (contentType.startsWith("text")) { contentType += ";charset=UTF-8"; } // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(bufferSize); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", expires); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. FileInputStream input = null; OutputStream output = null; if (content) { logger.debug("Content requested,streaming."); // Open streams. input = new FileInputStream(file); output = response.getOutputStream(); long streamed = stream(input, output, bufferSize); if (logger.isDebugEnabled()) { logger.debug("Bytes streamed:" + streamed); } } }
From source file:com.flexive.war.servlet.ThumbnailServlet.java
/** * {@inheritDoc}/*from w ww . ja v a 2 s . c om*/ */ @Override public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException { final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; final String uri = request.getRequestURI(); FxThumbnailURIConfigurator conf = new FxThumbnailURIConfigurator(URLDecoder.decode(uri, "UTF-8")); if (conf.getPK() == null && !conf.isUseType()) { if (LOG.isDebugEnabled()) { LOG.debug("Empty request for thumbnail servlet: " + uri); } response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } long binaryId; try { if (conf.isUseType()) { if (conf.getXPath().indexOf('/') == -1) { //probably a property FxProperty prop = CacheAdmin.getFilteredEnvironment().getProperty(conf.getXPath()); binaryId = getStructureBinaryId(conf, prop.getDefaultValue()); } else { FxAssignment as = CacheAdmin.getFilteredEnvironment().getAssignment(conf.getXPath()); if (as instanceof FxPropertyAssignment) { FxPropertyAssignment pa = (FxPropertyAssignment) as; binaryId = getStructureBinaryId(conf, pa.getDefaultValue()); } else binaryId = BinaryDescriptor.SYS_UNKNOWN; } } else { final String hintBinaryParam = request.getParameter("hintBinaryId"); final long hintBinaryId = StringUtils.isNumeric(hintBinaryParam) ? Long.parseLong(hintBinaryParam) : -1; if (hintBinaryId != -1) { // load the content to check if the binary belongs to that content (version) final FxContent content = EJBLookup.getContentEngine().load(conf.getPK()); final BinaryDescriptor binaryDescriptor = DownloadServlet.findBinaryDescriptor(content, hintBinaryId); if (binaryDescriptor == null) { LOG.warn("Invalid hintBinaryId for thumbnail of " + conf.getPK() + ": " + hintBinaryId); response.sendError(HttpServletResponse.SC_NOT_FOUND); } binaryId = hintBinaryId; } else { //authorization check and binary lookup binaryId = EJBLookup.getContentEngine().getBinaryId(conf.getPK(), XPathElement.stripType(conf.getXPath()), conf.getLanguage(), conf.useLangFallback()); } } } catch (FxNoAccessException na) { binaryId = BinaryDescriptor.SYS_NOACCESS; } catch (FxApplicationException e) { binaryId = BinaryDescriptor.SYS_UNKNOWN; } try { response.setDateHeader("Expires", System.currentTimeMillis() + 24L * 3600 * 1000); response.setDateHeader("Last-Modified", System.currentTimeMillis()); response.setHeader("Cache-Control", "private"); response.setHeader("Pragma", "cache"); FxStreamUtils.downloadBinary(new ThumbnailBinaryCallback(response), CacheAdmin.getStreamServers(), response.getOutputStream(), binaryId, conf); } catch (FxStreamException e) { LOG.error(e); throw new ServletException(e); } }
From source file:org.apache.karaf.cave.server.maven.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//from w ww .j a va 2 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); CaveMavenServlet servlet = new CaveMavenServlet(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); } @Override public boolean isFinished() { // TODO Auto-generated method stub return false; } @Override public boolean isReady() { // TODO Auto-generated method stub return true; } @Override public void setReadListener(ReadListener readListener) { // TODO Auto-generated method stub } }); 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:ru.org.linux.topic.TopicController.java
private ModelAndView getMessageNew(Section section, WebRequest webRequest, HttpServletRequest request, HttpServletResponse response, int page, String filter, String groupName, int msgid) throws Exception { Topic topic = messageDao.getById(msgid); Template tmpl = Template.getTemplate(request); PreparedTopic preparedMessage = messagePrepareService.prepareTopic(topic, request.isSecure(), tmpl.getCurrentUser());/* w w w . jav a 2 s . c om*/ Group group = preparedMessage.getGroup(); if (!group.getUrlName().equals(groupName) || group.getSectionId() != section.getId()) { return new ModelAndView(new RedirectView(topic.getLink())); } Map<String, Object> params = new HashMap<>(); boolean showDeleted = request.getParameter("deleted") != null; if (showDeleted) { page = -1; } boolean rss = request.getParameter("output") != null && "rss".equals(request.getParameter("output")); if (rss && topic.isExpired()) { throw new MessageNotFoundException(topic.getId(), "no more comments"); } if (!tmpl.isModeratorSession()) { if (showDeleted && !"POST".equals(request.getMethod())) { return new ModelAndView(new RedirectView(topic.getLink())); } } if (page == -1 && !tmpl.isSessionAuthorized()) { return new ModelAndView(new RedirectView(topic.getLink())); } int pages = topic.getPageCount(tmpl.getProf().getMessages()); if (page >= pages && (page > 0 || pages > 0)) { if (pages == 0) { return new ModelAndView(new RedirectView(topic.getLink())); } else { return new ModelAndView(new RedirectView(topic.getLinkPage(pages - 1))); } } if (showDeleted) { if (!tmpl.isSessionAuthorized()) { throw new BadInputException(" ??"); } } params.put("showDeleted", showDeleted); User currentUser = AuthUtil.getCurrentUser(); if (topic.isExpired() && showDeleted && !tmpl.isModeratorSession()) { throw new MessageNotFoundException(topic.getId(), "? ? ? "); } permissionService.checkView(topic, currentUser); if (group.getCommentsRestriction() == -1 && !tmpl.isSessionAuthorized()) { throw new AccessViolationException(" ? ? ?"); } params.put("message", topic); params.put("preparedMessage", preparedMessage); if (topic.isExpired()) { response.setDateHeader("Expires", System.currentTimeMillis() + 30 * 24 * 60 * 60 * 1000L); } CommentList comments = commentService.getCommentList(topic, showDeleted); if (!rss) { params.put("page", page); params.put("group", group); params.put("showAdsense", !tmpl.isSessionAuthorized() || !tmpl.getProf().isHideAdsense()); if (!tmpl.isSessionAuthorized()) { // because users have IgnoreList and memories String etag = getEtag(topic, tmpl); response.setHeader("Etag", etag); if (request.getHeader("If-None-Match") != null) { if (etag.equals(request.getHeader("If-None-Match"))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return null; } } else if (checkLastModified(webRequest, topic)) { return null; } } params.put("messageMenu", messagePrepareService.getTopicMenu(preparedMessage, currentUser, request.isSecure(), tmpl.getProf(), true)); Set<Integer> ignoreList; if (currentUser != null) { ignoreList = ignoreListDao.get(currentUser); } else { ignoreList = ImmutableSet.of(); } int defaultFilterMode = getDefaultFilter(tmpl.getProf(), ignoreList.isEmpty()); int filterMode; if (filter != null) { filterMode = CommentFilter.parseFilterChain(filter); if (!ignoreList.isEmpty() && filterMode == CommentFilter.FILTER_ANONYMOUS) { filterMode += CommentFilter.FILTER_IGNORED; } } else { filterMode = defaultFilterMode; } params.put("filterMode", CommentFilter.toString(filterMode)); params.put("defaultFilterMode", CommentFilter.toString(defaultFilterMode)); loadTopicScroller(params, topic, currentUser, !ignoreList.isEmpty()); Set<Integer> hideSet = commentService.makeHideSet(comments, filterMode, ignoreList); CommentFilter cv = new CommentFilter(comments); boolean reverse = tmpl.getProf().isShowNewFirst(); List<Comment> commentsFiltred = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(), hideSet); List<Comment> commentsFull = cv.getCommentsForPage(reverse, page, tmpl.getProf().getMessages(), ImmutableSet.<Integer>of()); params.put("unfilteredCount", commentsFull.size()); List<PreparedComment> commentsPrepared = prepareService.prepareCommentList(comments, commentsFiltred, request.isSecure(), tmpl, topic); params.put("commentsPrepared", commentsPrepared); IPBlockInfo ipBlockInfo = ipBlockDao.getBlockInfo(request.getRemoteAddr()); params.put("ipBlockInfo", ipBlockInfo); if (pages > 1 && !showDeleted) { params.put("pages", buildPages(topic, tmpl.getProf().getMessages(), filterMode, defaultFilterMode, page)); } } else { CommentFilter cv = new CommentFilter(comments); List<Comment> commentsFiltred = cv.getCommentsForPage(true, 0, RSS_DEFAULT, ImmutableSet.<Integer>of()); List<PreparedRSSComment> commentsPrepared = prepareService.prepareCommentListRSS(commentsFiltred, request.isSecure()); params.put("commentsPrepared", commentsPrepared); LorURL lorURL = new LorURL(configuration.getMainURI(), configuration.getMainUrl()); params.put("mainURL", lorURL.fixScheme(request.isSecure())); } return new ModelAndView(rss ? "view-message-rss" : "view-message", params); }
From source file:org.betaconceptframework.astroboa.resourceapi.filter.BinaryChannelLoaderFilter.java
private void loadAndReturnContentOfBinaryChannel(String fileAccessInfo, HttpServletResponse httpServletResponse) throws IOException { BinaryChannelFileAccessInfoProcessor fileAccessInfoProcessor = new BinaryChannelFileAccessInfoProcessor( fileAccessInfo);/*from w ww.j av a 2 s .c o m*/ if (!fileAccessInfoProcessor.processFileAccessInfo()) { logger.warn("Invalid file access info " + fileAccessInfo); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { String repositoryId = fileAccessInfoProcessor.getRepositoryId(); String fileName = fileAccessInfoProcessor.getFileName(); String mimeType = fileAccessInfoProcessor.getMimeType(); String width = fileAccessInfoProcessor.getWidth(); String height = fileAccessInfoProcessor.getHeight(); String contentDispositionType = fileAccessInfoProcessor.getContentDispositionType(); String relativePathToStream = fileAccessInfoProcessor.getRelativePathToStream(); //Check that repository home directory exists if (MapUtils.isEmpty(repositoryHomeDirectoriesPerRepositoryId) || StringUtils.isBlank(repositoryId) || !repositoryHomeDirectoriesPerRepositoryId.containsKey(repositoryId)) { logger.error("No available home directory exists for repository " + repositoryId); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { logger.debug("Ready to serve binary channel : path {}, mime-type: {}, filename :{}", new Object[] { relativePathToStream, mimeType, fileName }); File resource = null; try { //Load file resource = new File(repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator + relativePathToStream); if (!resource.exists()) { logger.warn("Could not locate resource " + repositoryHomeDirectoriesPerRepositoryId.get(repositoryId) + File.separator + relativePathToStream); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } else { //It may well be the case where filename and mime type are not provided //in file access info (especially if binary channel is unmanaged). //In this cases obtain filename and mime type from resource if (StringUtils.isBlank(fileName)) { fileName = resource.getName(); } if (StringUtils.isBlank(mimeType)) { mimeType = new MimetypesFileTypeMap().getContentType(resource); } ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream(); httpServletResponse.setDateHeader("Last-Modified", resource.lastModified()); httpServletResponse.setContentType(mimeType); String processedFilename = org.betaconceptframework.utility.FilenameUtils .convertFilenameGreekCharactersToEnglishAndReplaceInvalidCharacters(fileName); // byte[] resourceByteArray = FileUtils.readFileToByteArray(resource); if (StringUtils.isNotBlank(mimeType) && mimeType.startsWith("image/")) { resourceByteArray = resizeImageResource(resourceByteArray, mimeType, width, height); httpServletResponse.setHeader("Content-Disposition", contentDispositionType + ";filename=" + (width != null ? "W" + width : "") + (height != null ? "H" + height : "") + (width != null || height != null ? "-" : "") + processedFilename); } else { //Resource is not an image. Set charset encoding httpServletResponse.setCharacterEncoding("UTF-8"); } if (!httpServletResponse.containsHeader("Content-Disposition")) { httpServletResponse.setHeader("Content-Disposition", contentDispositionType + ";filename=" + processedFilename); } httpServletResponse.setHeader("ETag", ContentApiUtils.createETag(resource.lastModified(), resourceByteArray.length)); httpServletResponse.setContentLength(resourceByteArray.length); try { IOUtils.write(resourceByteArray, servletOutputStream); servletOutputStream.flush(); } catch (Exception e) { //Something went wrong while writing data to stream. //Just log to debug and not to warn logger.debug("", e); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } } catch (Exception e) { logger.error("", e); httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } } }
From source file:org.openiot.gsn.http.OneShotQueryWithAddressingHandler.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 av a2 s.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++) if (se.getFieldTypes()[i] == DataTypes.BINARY) sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\">") .append(se.getData()[i].toString()).append("</field>\n"); else sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\">") .append(StringEscapeUtils.escapeXml(se.getData()[i].toString())).append("</field>\n"); sb.append("<field name=\"timed\" >").append(sdf.format(new Date(se.getTimeStamp()))) .append("</field>\n"); VSensorConfig sensorConfig = Mappings.getVSensorConfig(vsName); if (logger.isInfoEnabled()) logger.info(new StringBuilder().append("Structure request for *").append(vsName) .append("* received.").toString()); //StringBuilder statement = 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("<field name=\"").append(StringEscapeUtils.escapeXml(df.getKey().toString())) .append("\">").append(StringEscapeUtils.escapeXml(df.getValue().toString())) .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:org.metis.pull.WdsResourceBean.java
/** * This method gets called by the WdsRdbMapper bean to handle a HTTP * request. This method must be multi-thread capable. Note that since we're * not using Views, this method must return null. * //from w w w. j a v a 2s. c om * @param request * the http request that is being serviced * @param response * the response that will be sent back to the service consumer * @return must return null since we're not using a view * @throws Exception */ @SuppressWarnings("unchecked") protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug(getBeanName() + ": handleRequestInternal - **** new request ****"); // dump the request if trace is on if (LOG.isTraceEnabled()) { LOG.trace(getBeanName() + ":handleRequestInternal - method = " + request.getMethod()); LOG.trace(getBeanName() + ":handleRequestInternal - uri = " + request.getRequestURI()); LOG.trace(getBeanName() + ":handleRequestInternal - protocol = " + request.getProtocol()); LOG.trace(getBeanName() + ":handleRequestInternal - secure = " + request.isSecure()); // dump all the http headers and their values Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); LOG.trace(getBeanName() + ":handleRequestInternal - " + headerName + " = " + request.getHeader(headerName)); } } if (request.getQueryString() != null) { LOG.trace(getBeanName() + ":handleRequestInternal - queryString = " + request.getQueryString()); } } long currentTime = System.currentTimeMillis(); // give the response a Date header with the current time response.setDateHeader(DATE_HDR, currentTime); // assign the Server header this container's info response.setHeader(SERVER_HDR, getServerInfo()); // determine the HTTP protocol version being used by the client // default version will be 0 int protocolVersion = 0; try { protocolVersion = Integer .parseInt(request.getProtocol().split(FORWARD_SLASH_STR)[1].split(ESC_DOT_STR)[1]); } catch (Exception exc) { LOG.warn(getBeanName() + ": handleRequestInternal - unable to get http protocol " + "version, stack trace follows: "); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); } LOG.trace(getBeanName() + ":handleRequestInternal - using this " + "protocol version: " + protocolVersion); /* * Ok, the request first needs to run the security gauntlet * * We do not want to send any error messages back to the client that * would give it a hint that we're invoking SQL statements. This is a * countermeasure for SQL injection probes. */ // see if this RDB is restricting user agents and if so, validate user // agent if ((getAllowedAgents() != null && !getAllowedAgents().isEmpty()) || (getNotAllowedAgents() != null && !getNotAllowedAgents().isEmpty())) { String userAgent = request.getHeader(USER_AGENT_HDR); if (userAgent != null && userAgent.length() > 0) { LOG.debug( getBeanName() + ": handleRequestInternal - validating this " + "user agent: " + userAgent); // Convert to lower case as allowed agents have been // converted to lower case as well userAgent = userAgent.toLowerCase(); boolean allow = false; if (getAllowedAgents() != null && !getAllowedAgents().isEmpty()) { for (String agent : getAllowedAgents()) { LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this " + "allowed agent : " + agent); if (userAgent.indexOf(agent) >= 0) { LOG.trace(getBeanName() + ": handleRequestInternal - this allowed agent " + "was found: " + agent); allow = true; break; } } } else { allow = true; for (String agent : getNotAllowedAgents()) { LOG.trace(getBeanName() + ": handleRequestInternal - comparing to this " + "non-allowed agent : " + agent); if (userAgent.indexOf(agent) >= 0) { LOG.trace(getBeanName() + ": handleRequestInternal - this non-allowed " + "agent was found: " + agent); allow = false; break; } } } if (!allow) { response.sendError(SC_UNAUTHORIZED, "ERROR, user agent " + "is not authorized"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent is " + "not authorized"); return null; } } else { response.sendError(SC_UNAUTHORIZED, "ERROR, user agent info " + "was not received and is required!"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user agent header " + "is required but was not provided by the client"); return null; } } // we do not support chunked transfer encoding, which is a http // 1.1 feature. if (request.getHeader(TRANSFER_ENCODING_HDR) != null && request.getHeader(TRANSFER_ENCODING_HDR).equalsIgnoreCase(CHUNKED)) { response.sendError(SC_BAD_REQUEST, "Chunked tranfer encoding is not " + "supported"); return null; } /* * isSecure returns a boolean indicating whether this request was made * using a secure channel, such as HTTPS. so, if the channel must be * secure, but it is not, then throw an exception and return an error. */ if (isSecure() && !request.isSecure()) { response.sendError(SC_UNAUTHORIZED, "ERROR, channel is not secure"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, channel is not secure"); return null; } /* * getUserPrincipal() returns a java.security.Principal containing the * name of the user making this request, else it returns null if the * user has not been authenticated. so, if it is mandated that the user * be authenticated, but has not been authenticated, then throw an * exception and return an error */ if (isAuthenticated() && request.getUserPrincipal() == null) { response.sendError(SC_UNAUTHORIZED, "ERROR, user is not authenticated"); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, user is not authenticated"); return null; } /* * Check for valid method - the only supported http methods are GET, * POST, PUT, and DELETE. Here are some good descriptions regarding the * methods and their use with respect to this servlet. * * The GET method is used for projecting data from the DB. So it maps to * a select statement. * * The PUT and POST methods are used for inserting or updating an entity * in the DB. So they map to either an update or insert. * * The DELETE is used for removing one or more entities from the DB. So * it maps to a delete. * * The bean must be assigned at least one of the methods to service */ Method method = null; try { method = Enum.valueOf(Method.class, request.getMethod().toUpperCase()); LOG.debug(getBeanName() + ": handleRequestInternal - processing this method: " + method.toString()); } catch (IllegalArgumentException e) { LOG.error(getBeanName() + ":handleRequestInternal - This method is not allowed [" + request.getMethod() + "]"); response.setHeader("Allow", allowedMethodsRsp); response.sendError(SC_METHOD_NOT_ALLOWED, "This method is not allowed [" + request.getMethod() + "]"); return null; } // do some more method validation; i.e., make sure requested method has // been assigned a SQL statement // // TODO: we may be able to remove this block of code String s1 = null; if (method.isGet() && sqlStmnts4Get == null || method.isPost() && sqlStmnts4Post == null || method.isPut() && sqlStmnts4Put == null || method.isDelete() && sqlStmnts4Delete == null) { response.setHeader("Allow", allowedMethodsRsp); s1 = "HTTP method [" + method + "] is not supported"; response.sendError(SC_METHOD_NOT_ALLOWED, s1); LOG.error(getBeanName() + ":handleRequestInternal - " + s1); return null; } // If the client has specified an 'Accept' header field, then determine // if it is willing or capable of accepting JSON or anything (*/*) // // TODO: what about the client accepting urlencoded strings?? s1 = request.getHeader(ACCEPT_HDR); if (s1 != null && s1.length() > 0) { LOG.debug(getBeanName() + ":handleRequestInternal - client-specified media " + "type in accept header = " + s1); // parse the accept header's content String[] mediaTypes = s1.trim().split(COMMA_STR); boolean match = false; for (String mediaType : mediaTypes) { mediaType = mediaType.trim().toLowerCase(); if (mediaType.startsWith(anyContentType) || mediaType.startsWith(jsonContentType)) { match = true; break; } } if (!match) { LOG.error(getBeanName() + ":handleRequestInternal - client-specified media type of '" + s1 + "' does not include '" + "'" + jsonContentType); response.sendError(SC_NOT_ACCEPTABLE, "client-specified media " + "type of '" + s1 + "' does not include '" + "'" + jsonContentType); return null; } } // pick up the corresponding list of SQL statements for this request List<SqlStmnt> sqlStmnts = null; switch (method) { case GET: sqlStmnts = getSqlStmnts4Get(); break; case DELETE: sqlStmnts = getSqlStmnts4Delete(); break; case PUT: sqlStmnts = getSqlStmnts4Put(); break; case POST: sqlStmnts = getSqlStmnts4Post(); break; default: response.sendError(SC_METHOD_NOT_ALLOWED, "ERROR, unsupported method type: " + method); LOG.error(getBeanName() + ": handleRequestInternal - ERROR, encountered unknown " + "method type: " + method); return null; } // ~~~~~~ EXTRACT PARAMERTERS, IF ANY ~~~~~~~~~~~ // GETs with entity bodies are illegal if (method.isGet() && request.getContentLength() > 0) { response.sendError(SC_BAD_REQUEST, "Client has issued a malformed or illegal request; " + "GET cannot include entity body"); return null; } // the DELETE method also cannot include an entity body; however, the // servlet containers already ignore them. so no need to check for that // see if json object arrived boolean jsonObjectPresent = (method.isPost() || method.isPut()) && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(jsonContentType)); LOG.debug(getBeanName() + ": jsonObjectPresent = " + jsonObjectPresent); // see if this is a PUT with entity. we've learned that for PUTs, // getParameterMap does not work the same across all servlet containers. // so we need take care of this ourselves boolean putWithBodyPresent = (method.isPut()) && (request.getContentLength() > 0 && request.getContentType().equalsIgnoreCase(urlEncodedContentType)); LOG.debug(getBeanName() + ": putWithBodyPresent = " + putWithBodyPresent); // collect incoming parameters and place them in a common bucket // // ~~~~ ALL PARAMETER KEY NAMES MUST BE FORCED TO LOWER CASE ~~~ // List<Map<String, String>> cParams = new ArrayList<Map<String, String>>(); // first, get the incoming query or form parameters (if any); we will // assume that each key has only one parameter. in other words, // we're not dealing with drop-down boxes or things similar if (!putWithBodyPresent && !jsonObjectPresent) { Map<String, String[]> qParams = request.getParameterMap(); if (qParams != null && !qParams.isEmpty()) { Map<String, String> qMap = new HashMap<String, String>(); for (String key : qParams.keySet()) { qMap.put(key.toLowerCase(), qParams.get(key)[0]); } if (!qMap.isEmpty()) { cParams.add(qMap); LOG.debug(getBeanName() + ": query params = " + qMap.toString()); } } } // a put with entity body arrived, so get the parameters from the // body and place them in the common bucket else if (putWithBodyPresent) { try { Map<String, String> putParams = null; // parseUrlEncoded will force keys to lower case putParams = Utils.parseUrlEncoded(request.getInputStream()); if (putParams != null && !putParams.isEmpty()) { cParams.add(putParams); } } catch (Exception exc) { LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing urlencoded string: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_BAD_REQUEST, "urlencoded string parsing error: " + exc.getMessage()); return null; } } // ok, a json object arrived, so get parameters defined in that object // and place them in the common bucket else { // its a json object, so parse it to extract params from it try { List<Map<String, String>> jParams = null; // parseJson will ensure that all passed-in JSON objects have // the same set of identical keys jParams = Utils.parseJson(request.getInputStream()); if (jParams != null && !jParams.isEmpty()) { // if we also got query params then ensure they have the // same set of keys as the json params. why anyone would // ever do this is beyond me, but I'll leave it in for now if (!cParams.isEmpty()) { Map<String, String> cMap = cParams.get(0); Map<String, String> jMap = jParams.get(0); for (String key : cMap.keySet()) { if (jMap.get(key) == null) { String eStr = getBeanName() + ": ERROR, json " + "object key set does not match query " + "param key set"; LOG.error(eStr); response.sendError(SC_BAD_REQUEST, eStr); return null; } } // place the passed in query params in the jParams // bucket jParams.add(cMap); } // assign the jParams bucket to the common bucket cParams = jParams; } } catch (Exception exc) { LOG.error(getBeanName() + ": ERROR, caught this " + "exception while parsing json object: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_BAD_REQUEST, "json parsing error: " + exc.getMessage()); return null; } } // if trace is on, dump the params (if any) to the log if (LOG.isDebugEnabled()) { if (!cParams.isEmpty()) { for (int i = 0; i < cParams.size(); i++) { LOG.debug(getBeanName() + ": handleRequestInternal - received these params: " + cParams.get(i).toString()); } } else { LOG.debug(getBeanName() + ": handleRequestInternal - did not receive any params"); } } // ensure none of the params' values have been black listed if (!cParams.isEmpty() && getBlackList().length() > 0) { char[] bl = getBlackList().toCharArray(); for (int i = 0; i < cParams.size(); i++) { for (String value : cParams.get(i).values()) { if (Utils.isOnBlackList(value, bl)) { response.sendError(SC_BAD_REQUEST, "encountered black listed character in this param " + "value: " + value); LOG.error(getBeanName() + "handleRequestInternal - encountered black listed " + "character in this param value: " + value); return null; } } } } // find the proper SQL statement based on the incoming parameters' (if // any) keys SqlStmnt sqlStmnt = null; try { // getMatch will try and find a match, even if no params were // provided. // @formatter:off sqlStmnt = (cParams.isEmpty()) ? SqlStmnt.getMatch(sqlStmnts, null) : SqlStmnt.getMatch(sqlStmnts, cParams.get(0).keySet()); // @formatter:on if (sqlStmnt == null && !cParams.isEmpty()) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this incoming param set: " + cParams.toString()); response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error"); return null; } else if (sqlStmnt == null) { LOG.warn(getBeanName() + ": warning, unable to find sql " + "statement on first pass, will use extra path info"); } else { LOG.debug(getBeanName() + ": handleRequestInternal - matching sql stmt = " + sqlStmnt.toString()); } } catch (Exception exc) { LOG.error(getBeanName() + ":ERROR, caught this exception " + "while mapping sql to params: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "mapping error"); return null; } // if getMatch could not find a match - perhaps input params were not // provided - then use the URI's 'extended path' information as an input // param if (sqlStmnt == null) { LOG.debug(getBeanName() + ": invoking getExtraPathInfo"); String[] xtraPathInfo = Utils.getExtraPathInfo(request.getPathInfo()); if (xtraPathInfo != null && xtraPathInfo.length >= 2) { LOG.debug(getBeanName() + ": extra path key:value = " + xtraPathInfo[0] + ":" + xtraPathInfo[1]); } else { LOG.error(getBeanName() + ":ERROR, getExtraPathInfo failed to find info"); response.sendError(SC_INTERNAL_SERVER_ERROR, "internal server error: mapping error"); return null; } // put the xtra path info in the common param bucket and try again cParams.clear(); Map<String, String> xMap = new HashMap<String, String>(); xMap.put(xtraPathInfo[0], xtraPathInfo[1]); cParams.add(xMap); // try again with the extra path info sqlStmnt = SqlStmnt.getMatch(sqlStmnts, xMap.keySet()); if (sqlStmnt == null) { LOG.error(getBeanName() + ":ERROR, unable to find sql " + "statement with this xtra path info: " + cParams.toString()); response.sendError(SC_NOT_FOUND, "internal server error: mapping error"); return null; } } // if we've gotten this far, we've gotten past the security gauntlet and // we have a SQL statement to work with. SqlResult sqlResult = null; try { // get the output stream OutputStream os = response.getOutputStream(); // FIRE IN THE DB HOLE :) if ((sqlResult = sqlStmnt.execute(cParams)) == null) { // execute will have logged the necessary debug/error info response.sendError(SC_INTERNAL_SERVER_ERROR); return null; } // execute went through ok, lets see how to respond switch (method) { case GET: // if a resultset was returned, then set the content type, // convert it to json, and write it out List<Map<String, Object>> listMap = sqlResult.getResultSet(); if (listMap != null) { // tell the client the content type response.setContentType(rspJsonContentType); String jsonOutput = Utils.generateJson(sqlResult.getResultSet()); LOG.trace(getBeanName() + ": returning this payload - " + jsonOutput); os.write(jsonOutput.getBytes()); // ensure that only the client can cache the data and tell // the client how long the data can remain active response.setHeader(CACHE_CNTRL_HDR, (getCacheControl() != null) ? getCacheControl() : DFLT_CACHE_CNTRL_STR); response.setHeader(PRAGMA_HDR, PRAGMA_NO_CACHE_STR); response.setDateHeader(EXPIRES_HDR, currentTime + (getExpires() * 1000)); } else { LOG.debug(getBeanName() + ": NOT returning json message"); } response.setStatus(SC_OK); break; case DELETE: // a DELETE should not send back an entity body response.setStatus(SC_NO_CONTENT); break; case PUT: /* * PUTs are idempotent; therefore, they must provide ALL the * properties that pertain to the resource/entity that they are * creating or updating. Updates cannot be partial updates; they * must be full updates. A PUT is issued by a client that knows * the identifier (in our case, primary key) of the * resource/entity. Therefore, we do not have to send back a * Location header in response to a PUT that has created a * resource. */ if (sqlStmnt.isInsert()) { response.setStatus(SC_CREATED); } else { response.setStatus(SC_OK); } break; case POST: /* * A POST is not idempotent; therefore, it can be used to * perform a 'partial' update, as well as a full create. When * creating a resource via POST, the client does not know the * primary key, and it assumes it will be auto-generated; * therefore, a Location header with auto-generated key must be * returned to client. */ if (sqlStmnt.isInsert()) { response.setStatus(SC_CREATED); // we need to return the new key, but only if it was not a // batch insert. the new key should be returned via the // location header // check if a key holder exists; if not, then table was not // configured with auto-generated key. String locationPath = request.getRequestURL().toString(); if (sqlResult.getKeyHolder() != null) { // key holder exists, check and see if a key is // present if (sqlResult.getKeyHolder().getKey() != null) { String id = sqlResult.getKeyHolder().getKey().toString(); LOG.debug(getBeanName() + ": getKey() returns " + id); locationPath += ("/" + id); LOG.debug(getBeanName() + ": locationPath = " + locationPath); response.setHeader(LOCATION_HDR, locationPath); } // no key, check for multiple keys // TODO: should we send back all keys? else if (sqlResult.getKeyHolder().getKeys() != null) { Map<String, Object> keyMap = sqlResult.getKeyHolder().getKeys(); LOG.debug(getBeanName() + ": getKeys() returns " + keyMap); } // maybe map of keys? // TODO: should we send back all keys? else if (sqlResult.getKeyHolder().getKeyList() != null) { for (Map<String, Object> map : sqlResult.getKeyHolder().getKeyList()) { LOG.debug(getBeanName() + ": Map from getKeyList(): " + map); } } } else { // if it was not an insert, then it was an update. LOG.debug(getBeanName() + ": key holder was not returned for the insert"); } } else { // it was not an insert, so just send back an OK for the // update response.setStatus(SC_OK); } break; default: response.setStatus(SC_OK); break; } } catch (JsonProcessingException exc) { LOG.error(getBeanName() + ":ERROR, caught this " + "JsonProcessingException while trying to gen json " + "message: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error"); return null; } catch (Exception exc) { LOG.error(getBeanName() + ":ERROR, caught this " + "Exception while trying to gen json " + "message: " + exc.toString()); LOG.error(getBeanName() + ": exception stack trace follows:"); dumpStackTrace(exc.getStackTrace()); if (exc.getCause() != null) { LOG.error(getBeanName() + ": Caused by " + exc.getCause().toString()); LOG.error(getBeanName() + ": causing exception stack trace follows:"); dumpStackTrace(exc.getCause().getStackTrace()); } response.sendError(SC_INTERNAL_SERVER_ERROR, "parsing error"); return null; } finally { if (sqlResult != null) { SqlResult.enqueue(sqlResult); } } // must return null, because we're not using views! return null; }
From source file:org.ejbca.ui.web.protocol.OCSPServletBase.java
/** * RFC 2560 does not specify how cache headers should be used, but RFC 5019 does. Therefore we will only * add the headers if the requirements of RFC 5019 is fulfilled: A GET-request, a single embedded reponse, * the response contains a nextUpdate and no nonce is present. * @param maxAge is the margin to Expire when using max-age in milliseconds *//* w ww. j a va2 s . c om*/ private void addRfc5019CacheHeaders(HttpServletRequest request, HttpServletResponse response, OCSPResp ocspresp, long maxAge) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, OCSPException { if (maxAge <= 0) { m_log.debug( "Will not add RFC 5019 cache headers: RFC 5019 6.2: max-age should be 'later than thisUpdate but earlier than nextUpdate'."); return; } if (!"GET".equalsIgnoreCase(request.getMethod())) { m_log.debug( "Will not add RFC 5019 cache headers: \"clients MUST use the GET method (to enable OCSP response caching)\""); return; } if (ocspresp.getResponseObject() == null) { m_log.debug("Will not add cache headers for response to bad request."); return; } SingleResp[] singleRespones = ((BasicOCSPResp) ocspresp.getResponseObject()).getResponses(); if (singleRespones.length != 1) { m_log.debug("Will not add RFC 5019 cache headers: reponse contains multiple embedded responses."); return; } if (singleRespones[0].getNextUpdate() == null) { m_log.debug("Will not add RFC 5019 cache headers: nextUpdate isn't set."); return; } if (singleRespones[0].getSingleExtensions() != null && singleRespones[0].getSingleExtensions() .getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce) == null) { m_log.debug("Will not add RFC 5019 cache headers: response contains a nonce."); return; } long now = new Date().getTime(); //long producedAt = ((BasicOCSPResp) ocspresp.getResponseObject()).getProducedAt().getTime(); long nextUpdate = singleRespones[0].getNextUpdate().getTime(); long thisUpdate = singleRespones[0].getThisUpdate().getTime(); if (maxAge >= (nextUpdate - thisUpdate)) { maxAge = nextUpdate - thisUpdate - 1; m_log.warn(intres.getLocalizedMessage("ocsp.shrinkmaxage", maxAge)); } // RFC 5019 6.2: Date: The date and time at which the OCSP server generated the HTTP response. // On JBoss AS the "Date"-header is cached for 1 second, so this value will be overwritten and off by up to a second response.setDateHeader("Date", now); // RFC 5019 6.2: Last-Modified: date and time at which the OCSP responder last modified the response. == thisUpdate response.setDateHeader("Last-Modified", thisUpdate); // RFC 5019 6.2: Expires: This date and time will be the same as the nextUpdate timestamp in the OCSP response itself. response.setDateHeader("Expires", nextUpdate); // This is overridden by max-age on HTTP/1.1 compatible components // RFC 5019 6.2: This profile RECOMMENDS that the ETag value be the ASCII HEX representation of the SHA1 hash of the OCSPResponse structure. response.setHeader("ETag", "\"" + new String(Hex.encode(MessageDigest.getInstance("SHA-1", "BC").digest(ocspresp.getEncoded()))) + "\""); response.setHeader("Cache-Control", "max-age=" + (maxAge / 1000) + ",public,no-transform,must-revalidate"); }
From source file:org.sakaiproject.sdata.tool.JCRHandler.java
@Override public void doGet(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { OutputStream out = null;/* w ww . jav a 2s .c om*/ InputStream in = null; try { snoopRequest(request); ResourceDefinition rp = resourceDefinitionFactory.getSpec(request); SDataFunction m = resourceFunctionFactory.get(rp.getFunctionDefinition()); if (describe(request, response, m)) { return; } Node n = jcrNodeFactory.getNode(rp.getRepositoryPath()); if (n == null) { response.reset(); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } String primaryNodeType = n.getPrimaryNodeType().getName(); 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); if (n.hasProperty(JCRConstants.JCR_FROZENPRIMARYTYPE)) { primaryNodeType = n.getProperty(JCRConstants.JCR_FROZENPRIMARYTYPE).getString(); } } if (m != null) { m.call(this, request, response, n, rp); } else { if (JCRConstants.NT_FILE.equals(primaryNodeType)) { 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()); setGetCacheControl(response, rp.isPrivate()); String currentEtag = String.valueOf(lastModified.getDate().getTimeInMillis()); response.setHeader("ETag", currentEtag); long lastModifiedTime = lastModified.getDate().getTimeInMillis(); if (!checkPreconditions(request, response, lastModifiedTime, currentEtag)) { return; } long totallength = content.getLength(); long[] ranges = new long[2]; ranges[0] = 0; ranges[1] = totallength; if (!checkRanges(request, response, lastModifiedTime, currentEtag, ranges)) { return; } long length = ranges[1] - ranges[0]; if (totallength != length) { response.setHeader("Accept-Ranges", "bytes"); response.setDateHeader("Last-Modified", lastModifiedTime); response.setHeader("Content-Range", "bytes " + ranges[0] + "-" + (ranges[1] - 1) + "/" + totallength); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); LOG.info("Partial Content Sent " + HttpServletResponse.SC_PARTIAL_CONTENT); } else { response.setStatus(HttpServletResponse.SC_OK); } response.setContentLength((int) length); out = response.getOutputStream(); in = content.getStream(); long loc = in.skip(ranges[0]); if (loc != ranges[0]) { throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST, "Range specified is invalid asked for " + ranges[0] + " got " + loc); } byte[] b = new byte[10240]; int nbytes = 0; while ((nbytes = in.read(b)) > 0 && length > 0) { if (nbytes < length) { out.write(b, 0, nbytes); length = length - nbytes; } else { out.write(b, 0, (int) length); length = 0; } } } else { boolean handled = handleSmartNode(request, response, rp, n); if (!handled) { doDefaultGet(request, response, rp, n); } } } } catch (UnauthorizedException ape) { // catch any Unauthorized exceptions and send a 401 response.reset(); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage()); } catch (PermissionDeniedException pde) { // catch any permission denied exceptions, and send a 403 response.reset(); response.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage()); } catch (SDataException e) { LOG.error("Failed To service Request " + e.getMessage()); e.printStackTrace(); sendError(request, response, e); } catch (Exception e) { LOG.error("Failed TO service Request ", e); sendError(request, response, e); snoopRequest(request); } finally { try { out.close(); } catch (Exception ex) { } try { in.close(); } catch (Exception ex) { } } }
From source file: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//w w w . j a va 2s. 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 + " from " + request.getRemoteAddr() + "- " + request.getRemoteHost() + ": " + e.getMessage()); return; } Iterator<VSensorConfig> vsIterator = Mappings.getAllVSensorConfigs(); HashMap<String, String> fieldToUnitMap = new HashMap<String, String>(); while (vsIterator.hasNext()) { VSensorConfig sensorConfig = vsIterator.next(); if (vsName.equalsIgnoreCase(sensorConfig.getName())) { DataField[] dataFieldArray = sensorConfig.getOutputStructure(); for (DataField df : dataFieldArray) { String unit = df.getUnit(); if (unit == null || unit.trim().length() == 0) unit = ""; fieldToUnitMap.put(df.getName().toLowerCase(), unit); } break; } } StringBuilder sb = new StringBuilder("<result>\n"); while (result.hasMoreElements()) { StreamElement se = result.nextElement(); sb.append("<stream-element>\n"); sb.append("<field name=\"time\" unit=\"\">").append(sdf.format(new Date(se.getTimeStamp()))) .append("</field>\n"); for (int i = 0; i < se.getFieldNames().length; i++) { sb.append("<field name=\"").append(se.getFieldNames()[i]).append("\""); sb.append(" unit=\"").append(fieldToUnitMap.get(se.getFieldNames()[i].toLowerCase())) .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("</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()); }