List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED
int SC_NOT_MODIFIED
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.
Click Source Link
From source file:com.groupon.odo.Proxy.java
/** * @param httpServletResponse/*from www. jav a 2 s .c o m*/ * @param outStream * @param jsonpCallback * @throws IOException */ private void writeResponseOutput(HttpServletResponse httpServletResponse, OutputStream outStream, String jsonpCallback) throws IOException { RequestInformation requestInfo = requestInformation.get(); // check to see if this is chunked boolean chunked = false; if (httpServletResponse.containsHeader(HttpUtilities.STRING_TRANSFER_ENCODING) && httpServletResponse .getHeader(HttpUtilities.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) { httpServletResponse.setHeader(HttpUtilities.STRING_CONNECTION, HttpUtilities.STRING_CHUNKED); chunked = true; } // reattach JSONP if needed if (requestInfo.outputString != null && jsonpCallback != null) { requestInfo.outputString = jsonpCallback + "(" + requestInfo.outputString + ");"; } // don't do this if we got a HTTP 304 since there is no data to send back if (httpServletResponse.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) { logger.info("Chunked: {}, {}", chunked, httpServletResponse.getBufferSize()); if (!chunked) { // change the content length header to the new length if (requestInfo.outputString != null) { httpServletResponse.setContentLength(requestInfo.outputString.getBytes().length); } else { httpServletResponse.setContentLength(((ByteArrayOutputStream) outStream).toByteArray().length); } } OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); if (requestInfo.outputString != null) { outputStreamClientResponse.write(requestInfo.outputString.getBytes()); } else { outputStreamClientResponse.write(((ByteArrayOutputStream) outStream).toByteArray()); } httpServletResponse.flushBuffer(); logger.info("Done writing"); } // outstr might still be null.. let's try to set it from outStream if (requestInfo.outputString == null) { try { requestInfo.outputString = outStream.toString(); } catch (Exception e) { // can ignore any issues.. worst case outstr is still null } } }
From source file:org.opencastproject.scheduler.endpoint.SchedulerRestService.java
/** * Gets the iCalendar with all (even old) events for the specified filter. * //from ww w . jav a2 s.c o m * @param captureAgentID * The ID that specifies the capture agent. * @param seriesId * The ID that specifies series. * * @return an iCalendar */ @GET @Produces("text/calendar") // NOTE: charset not supported by current jaxrs impl (is ignored), set explicitly in response @Path("calendars") @RestQuery(name = "getcalendar", description = "Returns iCalendar for specified set of events", returnDescription = "ICalendar for events", restParameters = { @RestParameter(name = "agentid", description = "Filter events by capture agent", isRequired = false, type = Type.STRING), @RestParameter(name = "seriesid", description = "Filter events by series", isRequired = false, type = Type.STRING), @RestParameter(name = "cutoff", description = "A cutoff date at which the number of events returned in the calendar are limited.", isRequired = false, type = Type.STRING) }, reponses = { @RestResponse(responseCode = HttpServletResponse.SC_NOT_MODIFIED, description = "Events were not modified since last request"), @RestResponse(responseCode = HttpServletResponse.SC_OK, description = "Events were modified, new calendar is in the body") }) public Response getCalendar(@QueryParam("agentid") String captureAgentId, @QueryParam("seriesid") String seriesId, @QueryParam("cutoff") String cutoff, @Context HttpServletRequest request) { SchedulerQuery filter = new SchedulerQuery().setSpatial(captureAgentId).setSeriesId(seriesId); if (StringUtils.isNotEmpty(cutoff)) { try { Date endDate = new Date(Long.valueOf(cutoff)); filter = new SchedulerQuery().setSpatial(captureAgentId).setSeriesId(seriesId) .setEndsFrom(new Date(System.currentTimeMillis())).setStartsTo(endDate); } catch (NumberFormatException e) { return Response.status(Status.BAD_REQUEST).build(); } } try { // If the etag matches the if-not-modified header,return a 304 Date lastModified = service.getScheduleLastModified(filter); if (lastModified == null) { lastModified = new Date(); } String ifNoneMatch = request.getHeader(HttpHeaders.IF_NONE_MATCH); if (StringUtils.isNotBlank(ifNoneMatch) && ifNoneMatch.equals("mod" + Long.toString(lastModified.getTime()))) { return Response.notModified("mod" + Long.toString(lastModified.getTime())).expires(null).build(); } String result = service.getCalendar(filter); if (!result.isEmpty()) { return Response.ok(result).header(HttpHeaders.ETAG, "mod" + Long.toString(lastModified.getTime())) .header(HttpHeaders.CONTENT_TYPE, "text/calendar; charset=UTF-8").build(); } else { throw new NotFoundException(); } } catch (Exception e) { logger.error("Unable to get calendar for capture agent '{}': {}", captureAgentId, e.getMessage()); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } }
From source file:org.structr.web.servlet.HtmlServlet.java
private void streamFile(SecurityContext securityContext, final File file, HttpServletRequest request, HttpServletResponse response, final EditMode edit) throws IOException { if (!securityContext.isVisible(file)) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from w ww . j a v a 2 s . com } final ServletOutputStream out = response.getOutputStream(); final String downloadAsFilename = request.getParameter(DOWNLOAD_AS_FILENAME_KEY); final Map<String, Object> callbackMap = new LinkedHashMap<>(); // make edit mode available in callback method callbackMap.put("editMode", edit); if (downloadAsFilename != null) { // Set Content-Disposition header to suggest a default filename and force a "save-as" dialog // See: // http://en.wikipedia.org/wiki/MIME#Content-Disposition, // http://tools.ietf.org/html/rfc2183 // http://tools.ietf.org/html/rfc1806 // http://tools.ietf.org/html/rfc2616#section-15.5 and http://tools.ietf.org/html/rfc2616#section-19.5.1 response.addHeader("Content-Disposition", "attachment; filename=\"" + downloadAsFilename + "\""); callbackMap.put("requestedFileName", downloadAsFilename); } if (!EditMode.WIDGET.equals(edit) && notModifiedSince(request, response, file, false)) { out.flush(); out.close(); callbackMap.put("statusCode", HttpServletResponse.SC_NOT_MODIFIED); } else { final String downloadAsDataUrl = request.getParameter(DOWNLOAD_AS_DATA_URL_KEY); if (downloadAsDataUrl != null) { IOUtils.write(FileHelper.getBase64String(file), out); response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); out.flush(); out.close(); callbackMap.put("statusCode", HttpServletResponse.SC_OK); } else { // 2b: stream file to response final InputStream in = file.getInputStream(); final String contentType = file.getContentType(); if (contentType != null) { response.setContentType(contentType); } else { // Default response.setContentType("application/octet-stream"); } final String range = request.getHeader("Range"); try { if (StringUtils.isNotEmpty(range)) { final long len = file.getSize(); long start = 0; long end = len - 1; final Matcher matcher = Pattern.compile("bytes=(?<start>\\d*)-(?<end>\\d*)").matcher(range); if (matcher.matches()) { String startGroup = matcher.group("start"); start = startGroup.isEmpty() ? start : Long.valueOf(startGroup); start = Math.max(0, start); String endGroup = matcher.group("end"); end = endGroup.isEmpty() ? end : Long.valueOf(endGroup); end = end > len - 1 ? len - 1 : end; } long contentLength = end - start + 1; // Tell the client that we support byte ranges response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, len)); response.setHeader("Content-Length", String.format("%s", contentLength)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); callbackMap.put("statusCode", HttpServletResponse.SC_PARTIAL_CONTENT); IOUtils.copyLarge(in, out, start, contentLength); } else { response.setStatus(HttpServletResponse.SC_OK); callbackMap.put("statusCode", HttpServletResponse.SC_OK); IOUtils.copyLarge(in, out); } } catch (Throwable t) { } finally { if (out != null) { try { // 3: output content out.flush(); out.close(); } catch (Throwable t) { } } if (in != null) { in.close(); } response.setStatus(HttpServletResponse.SC_OK); } } } // WIDGET mode means "opened in frontend", which we don't want to count as an external download if (!EditMode.WIDGET.equals(edit)) { // call onDownload callback try { file.invokeMethod("onDownload", Collections.EMPTY_MAP, false); } catch (FrameworkException fex) { fex.printStackTrace(); } } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static void handleBlobMetadata(HttpServletRequest request, HttpServletResponse response, BlobStore blobStore, String containerName, String blobName) throws IOException, S3Exception { BlobMetadata metadata = blobStore.blobMetadata(containerName, blobName); if (metadata == null) { throw new S3Exception(S3ErrorCode.NO_SUCH_KEY); }/*from ww w .j av a2 s . c o m*/ // BlobStore.blobMetadata does not support GetOptions so we emulate // conditional requests. String ifMatch = request.getHeader(HttpHeaders.IF_MATCH); String ifNoneMatch = request.getHeader(HttpHeaders.IF_NONE_MATCH); long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); long ifUnmodifiedSince = request.getDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE); String eTag = metadata.getETag(); if (eTag != null) { eTag = maybeQuoteETag(eTag); if (ifMatch != null && !ifMatch.equals(eTag)) { throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED); } if (ifNoneMatch != null && ifNoneMatch.equals(eTag)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } Date lastModified = metadata.getLastModified(); if (lastModified != null) { if (ifModifiedSince != -1 && lastModified.compareTo(new Date(ifModifiedSince)) <= 0) { throw new S3Exception(S3ErrorCode.PRECONDITION_FAILED); } if (ifUnmodifiedSince != -1 && lastModified.compareTo(new Date(ifUnmodifiedSince)) >= 0) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } response.setStatus(HttpServletResponse.SC_OK); addMetadataToResponse(request, response, metadata); }
From source file:net.sourceforge.subsonic.controller.RESTController.java
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception { request = wrapRequest(request);/*from w w w . ja v a 2 s . c o m*/ User user = securityService.getCurrentUser(request); if (!user.isDownloadRole()) { error(request, response, ErrorCode.NOT_AUTHORIZED, user.getUsername() + " is not authorized to download files."); return null; } long ifModifiedSince = request.getDateHeader("If-Modified-Since"); long lastModified = downloadController.getLastModified(request); if (ifModifiedSince != -1 && lastModified != -1 && lastModified <= ifModifiedSince) { response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return null; } if (lastModified != -1) { response.setDateHeader("Last-Modified", lastModified); } return downloadController.handleRequest(request, response); }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Check if the if-modified-since condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceInfo File object/* w w w.ja va2s .c o m*/ * @return boolean true if the resource meets the specified condition, * and false if the condition is not satisfied, in which case request * processing is stopped * @throws IOException Description of the Exception */ private boolean checkIfModifiedSince(HttpServletRequest request, HttpServletResponse response, ResourceInfo resourceInfo) throws IOException { try { long headerValue = request.getDateHeader("If-Modified-Since"); long lastModified = resourceInfo.date; if (headerValue != -1) { // If an If-None-Match header has been specified, if modified since // is ignored. if ((request.getHeader("If-None-Match") == null) && (lastModified <= headerValue + 1000)) { // The entity has not been modified since the date // specified by the client. This is not an error case. response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return false; } } } catch (IllegalArgumentException illegalArgument) { return true; } return true; }
From source file:org.apache.catalina.servlets.DefaultServlet.java
/** * Check if the if-none-match condition is satisfied. * * @param request The servlet request we are processing * @param response The servlet response we are creating * @param resourceInfo File object/* w w w. j a v a2 s.co m*/ * @return boolean true if the resource meets the specified condition, * and false if the condition is not satisfied, in which case request * processing is stopped * @throws IOException Description of the Exception */ private boolean checkIfNoneMatch(HttpServletRequest request, HttpServletResponse response, ResourceInfo resourceInfo) throws IOException { String eTag = getETag(resourceInfo); String headerValue = request.getHeader("If-None-Match"); if (headerValue != null) { boolean conditionSatisfied = false; if (!headerValue.equals("*")) { StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ","); while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) { String currentToken = commaTokenizer.nextToken(); if (currentToken.trim().equals(eTag)) { conditionSatisfied = true; } } } else { conditionSatisfied = true; } if (conditionSatisfied) { // For GET and HEAD, we should respond with // 304 Not Modified. // For every other method, 412 Precondition Failed is sent // back. if (("GET".equals(request.getMethod())) || ("HEAD".equals(request.getMethod()))) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return false; } else { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return false; } } } return true; }
From source file:org.apache.ranger.rest.ServiceREST.java
@GET @Path("/policies/download/{serviceName}") @Produces({ "application/json", "application/xml" }) public ServicePolicies getServicePoliciesIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam("lastKnownVersion") Long lastKnownVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @Context HttpServletRequest request) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ")"); }// w ww. j a va 2s .co m ServicePolicies ret = null; int httpCode = HttpServletResponse.SC_OK; String logMsg = null; RangerPerfTracer perf = null; if (serviceUtil.isValidateHttpsAuthentication(serviceName, request)) { if (lastKnownVersion == null) { lastKnownVersion = Long.valueOf(-1); } try { if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); } ServicePolicies servicePolicies = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion); Long downloadedVersion; if (servicePolicies == null) { downloadedVersion = lastKnownVersion; httpCode = HttpServletResponse.SC_NOT_MODIFIED; logMsg = "No change since last update"; } else { downloadedVersion = servicePolicies.getPolicyVersion(); ret = filterServicePolicies(servicePolicies); httpCode = HttpServletResponse.SC_OK; logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : 0) + " policies. Policy version=" + ret.getPolicyVersion(); } assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode); } catch (Throwable excp) { LOG.error("getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp); httpCode = HttpServletResponse.SC_BAD_REQUEST; logMsg = excp.getMessage(); } finally { createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, request); RangerPerfTracer.log(perf); } if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } } if (LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.getServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); } return ret; }
From source file:org.apache.ranger.rest.ServiceREST.java
@GET @Path("/secure/policies/download/{serviceName}") @Produces({ "application/json", "application/xml" }) public ServicePolicies getSecureServicePoliciesIfUpdated(@PathParam("serviceName") String serviceName, @QueryParam("lastKnownVersion") Long lastKnownVersion, @DefaultValue("0") @QueryParam("lastActivationTime") Long lastActivationTime, @QueryParam("pluginId") String pluginId, @Context HttpServletRequest request) throws Exception { if (LOG.isDebugEnabled()) { LOG.debug("==> ServiceREST.getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ")"); }/*from w w w . j a v a 2 s . c om*/ ServicePolicies ret = null; int httpCode = HttpServletResponse.SC_OK; String logMsg = null; RangerPerfTracer perf = null; boolean isAllowed = false; boolean isAdmin = bizUtil.isAdmin(); boolean isKeyAdmin = bizUtil.isKeyAdmin(); request.setAttribute("downloadPolicy", "secure"); if (serviceUtil.isValidService(serviceName, request)) { if (lastKnownVersion == null) { lastKnownVersion = Long.valueOf(-1); } try { if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) { perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.getSecureServicePoliciesIfUpdated(serviceName=" + serviceName + ",lastKnownVersion=" + lastKnownVersion + ",lastActivationTime=" + lastActivationTime + ")"); } XXService xService = daoManager.getXXService().findByName(serviceName); XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType()); RangerService rangerService = null; if (StringUtils.equals(xServiceDef.getImplclassname(), EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME)) { rangerService = svcStore.getServiceByNameForDP(serviceName); if (isKeyAdmin) { isAllowed = true; } else { if (rangerService != null) { isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); if (!isAllowed) { isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); } } } } else { rangerService = svcStore.getServiceByName(serviceName); if (isAdmin) { isAllowed = true; } else { if (rangerService != null) { isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Download); if (!isAllowed) { isAllowed = bizUtil.isUserAllowed(rangerService, Allowed_User_List_For_Grant_Revoke); } } } } if (isAllowed) { ServicePolicies servicePolicies = svcStore.getServicePoliciesIfUpdated(serviceName, lastKnownVersion); Long downloadedVersion; if (servicePolicies == null) { downloadedVersion = lastKnownVersion; httpCode = HttpServletResponse.SC_NOT_MODIFIED; logMsg = "No change since last update"; } else { downloadedVersion = servicePolicies.getPolicyVersion(); ret = filterServicePolicies(servicePolicies); httpCode = HttpServletResponse.SC_OK; logMsg = "Returning " + (ret.getPolicies() != null ? ret.getPolicies().size() : 0) + " policies. Policy version=" + ret.getPolicyVersion(); } assetMgr.createPluginInfo(serviceName, pluginId, request, RangerPluginInfo.ENTITY_TYPE_POLICIES, downloadedVersion, lastKnownVersion, lastActivationTime, httpCode); } else { LOG.error("getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ") failed as User doesn't have permission to download Policy"); httpCode = HttpServletResponse.SC_UNAUTHORIZED; logMsg = "User doesn't have permission to download policy"; } } catch (Throwable excp) { LOG.error("getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + ") failed", excp); httpCode = HttpServletResponse.SC_BAD_REQUEST; logMsg = excp.getMessage(); } finally { createPolicyDownloadAudit(serviceName, lastKnownVersion, pluginId, httpCode, request); RangerPerfTracer.log(perf); } if (httpCode != HttpServletResponse.SC_OK) { boolean logError = httpCode != HttpServletResponse.SC_NOT_MODIFIED; throw restErrorUtil.createRESTException(httpCode, logMsg, logError); } } if (LOG.isDebugEnabled()) { LOG.debug("<== ServiceREST.getSecureServicePoliciesIfUpdated(" + serviceName + ", " + lastKnownVersion + ", " + lastActivationTime + "): count=" + ((ret == null || ret.getPolicies() == null) ? 0 : ret.getPolicies().size())); } return ret; }