List of usage examples for javax.servlet.http HttpServletRequest getHeader
public String getHeader(String name);
String
. From source file:httpUtils.HttpUtils.java
/** * Parse the request headers, build the response, stream back file * @param request//w w w .j a v a 2s .c o m * @param response * @param dataStream * @param fileLength * @param fileName * @param fileLastModified * @param contentType * @return */ private static HttpServletResponse getFileAsStream(HttpServletRequest request, HttpServletResponse response, InputStream dataStream, long fileLength, String fileName, long fileLastModified, String contentType) { if (dataStream == null) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); return response; } if (StringUtils.isEmpty(fileName) || fileLastModified == 0L) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return response; } String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return response; } long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > fileLastModified) { response.setHeader("ETag", fileName); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return response; } String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, fileName)) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return response; } long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= fileLastModified) { response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED); return response; } Range full = new Range(0, fileLength - 1, fileLength); List<Range> ranges = new ArrayList<Range>(); String range = request.getHeader("Range"); if (range != null) { if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + fileLength); response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return response; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following // examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 // (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = fileLength - end; end = fileLength - 1; } else if (end == -1 || end > fileLength - 1) { end = fileLength - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + fileLength); // Required // in // 416. response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return response; } // Add range. ranges.add(new Range(start, end, fileLength)); } } } // Get content type by file name and set content disposition. 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"; } else if (!contentType.startsWith("image")) { // 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. String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(HttpUtils.DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", fileLastModified); response.setDateHeader("Expires", System.currentTimeMillis() + HttpUtils.DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, fileLength, r.start, r.length); } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Copy single part range. copy(input, output, fileLength, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + HttpUtils.MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Cast back to ServletOutputStream to get the easy println // methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + HttpUtils.MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, fileLength, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + HttpUtils.MULTIPART_BOUNDARY + "--"); } } catch (Exception e) { log.error("get file as stream failed", e); } finally { // Gently close streams. close(output); close(input); close(dataStream); } return response; }
From source file:net.javacrumbs.test.AbstractServlet.java
protected int getCurrentNumber(HttpServletRequest req) { int number;/*from w w w.jav a2s . c om*/ String header = req.getHeader("number"); if (header != null) { number = Integer.valueOf(header); } else { number = 1; } return number; }
From source file:br.interactive.ecm.gerais.service.UsuarioService.java
public LoginDTO isGetUser(HttpServletRequest request) { String token = request.getHeader("Authorization"); UserSession userSession = userSessionDAO.getUserSessionByToken(token); if (userSession != null) { LoginDTO loginDTO = usuarioDAO.getUsuarioByLoginDTO(userSession.getTxLogin()); loginDTO.setToken(userSession.getTxToken()); return loginDTO; }// w w w. j a v a 2 s . c o m return null; }
From source file:it.geosolutions.httpproxy.callback.HostChecker.java
/** * @param req/*w w w . j a va2s .c o m*/ * @return String */ private String getRemoteAddr(HttpServletRequest req) { String forwardedFor = req.getHeader("X-Forwarded-For"); if (forwardedFor != null) { String[] ips = forwardedFor.split(", "); return ips[0]; } else { return req.getRemoteAddr(); } }
From source file:org.lecture.controller.TestCaseController.java
/** * Creates a new TestCaseContainer. This method should get called before the * code submission gets send.// w w w . j a v a2 s . c o m * * @param entity the test from the post-request. This test is deserialized by * jackson. * @return A respoonse containing a compilation-report. */ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<?> create(@RequestBody SourceContainer entity, HttpServletRequest request) { String userId = request.getHeader("User-Id"); entity.setUserId(userId); entity.setTests(true); entity = testRepository.save(entity); return super.createEntity(entity, "Accept-FilePatch", "application/json;charset=UTF-8"); }
From source file:com.javiermoreno.springboot.rest.AuthenticationTokenProcessingFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; String encryptedToken = request.getHeader("X-Auth-Token"); if (SecurityContextHolder.getContext().getAuthentication() == null && encryptedToken != null) { Token token = new Token(cryptoService, encryptedToken); String ip = request.getHeader("X-Forwarded-For"); if (ip == null) { ip = request.getRemoteAddr(); }/*w w w . j a v a2 s.c o m*/ if (ip.equals(token.getIp()) == true && token.isExpired() == false) { UserDetails userDetails = userDetailsService.loadUserByUsername(token.getUsername()); UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( userDetails.getUsername(), userDetails.getPassword()); authentication.setDetails( new WebAuthenticationDetailsSource().buildDetails((HttpServletRequest) request)); SecurityContextHolder.getContext() .setAuthentication(authenticationManager.authenticate(authentication)); } } chain.doFilter(req, res); }
From source file:cec.easyshop.storefront.filters.btg.RefererHeaderBtgFilter.java
@Override protected AbstractBTGRuleDataEvent getEvent(final HttpServletRequest request) { RefererHeaderUsedBTGRuleDataEvent result = null; final String referrer = request.getHeader(REFERER_HEADER_NAME); if (!StringUtils.isBlank(referrer)) { result = new RefererHeaderUsedBTGRuleDataEvent(referrer); }//from w w w . java 2 s. c om return result; }
From source file:com.rockagen.gnext.controller.ApplicationController.java
/** * Get uid// w ww. j a v a2 s . c om * * @return uid */ public String uid(HttpServletRequest request) { String token = request.getHeader(AUTH_HEADER_NAME); return Token.getUidFromToken(token); }
From source file:org.energyos.espi.datacustodian.web.api.ServiceStatusRESTController.java
private String getApplicationStatus(HttpServletRequest request) { String token = request.getHeader("authorization"); String applicationStatus = "0"; if (token != null) { token = token.replace("Bearer ", ""); Authorization authorization = authorizationService.findByAccessToken(token); if (authorization != null) { ApplicationInformation applicationinformation = authorization.getApplicationInformation(); if (applicationinformation != null) { applicationStatus = applicationinformation.getDataCustodianApplicationStatus(); }//from w w w . j a v a 2 s . com } } return applicationStatus; }
From source file:com.googlesource.gerrit.plugins.github.oauth.OAuthFilter.java
private boolean isAuthenticatedRestCall(HttpServletRequest httpRequest) { return !StringUtils.isEmpty(httpRequest.getHeader(XGerritAuth.X_GERRIT_AUTH)); }