List of usage examples for javax.servlet.http HttpServletRequest getServletContext
public ServletContext getServletContext();
From source file:controlador.Controlador.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, JSONException { String tabla = request.getParameter("tabla");//persona, idioma, etc. String op = request.getParameter("op");//login, create, read, update, delete String accion = request.getParameter("accion");//view, do String origen = request.getParameter("origen");//android, web Destino destino = handle(request, response, tabla, op, accion, origen); if (destino == null) { destino = new Destino(Camino.forward, "/WEB-INF/index.jsp", ""); }/*from w w w. j a v a 2 s.com*/ if (destino.camino == Camino.forward) { request.getServletContext().getRequestDispatcher(destino.url).forward(request, response); } else if (destino.camino == Camino.redirect) { response.sendRedirect(destino.url); } else { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println(destino.texto); } } }
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**// w w w.jav a 2 s. c o m * Empty filter chain. Two events with same correlation ID are expected: * * action=access request_type=uri outcome=unavailable * action=access request_type=uri outcome=success message=Response status: 404 */ public void testNoFiltersAudit() throws ServletException, IOException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); GatewayFilter gateway = new GatewayFilter(); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
From source file:com.tssa.cooperationBusiness.controller.CooperationController.java
private String saveLogoFile(HttpServletRequest request) { String filePath = ""; try {//from w ww . j ava 2 s.c o m MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile multiFile = multipartRequest.getFile("logoImageURL"); String cooperationId = request.getParameter("cooperationId"); // String fileUrl =request.getServletContext().getRealPath("/") + "upload/"; String viewUrl = request.getServletContext().getContextPath() + "/upload/"; // String fileUrl = "/Users/gmc/Works/eclipse/workspace/TSSA/WebContent/upload/"; File file = new File(fileUrl); if (!file.exists()) { file.mkdirs(); } if (multiFile != null && (multiFile.getOriginalFilename() != null && !"".equals(multiFile.getOriginalFilename()))) { File uploadFile = new File(fileUrl + cooperationId + multiFile.getOriginalFilename() .substring(multiFile.getOriginalFilename().lastIndexOf("."))); multiFile.transferTo(uploadFile); filePath = viewUrl + cooperationId + multiFile.getOriginalFilename() .substring(multiFile.getOriginalFilename().lastIndexOf(".")); return filePath; } else { return null; } } catch (IOException e) { LOG.error(e.getMessage(), e); return null; } }
From source file:org.apache.hadoop.gateway.AuditLoggingTest.java
@Test /**/*from w ww .j a v a 2 s .com*/ * One NoOp filter in chain. Single audit event with same with specified request URI is expected: * * action=access request_type=uri outcome=unavailable */ public void testNoopFilter() throws ServletException, IOException, URISyntaxException { FilterConfig config = EasyMock.createNiceMock(FilterConfig.class); EasyMock.replay(config); HttpServletRequest request = EasyMock.createNiceMock(HttpServletRequest.class); ServletContext context = EasyMock.createNiceMock(ServletContext.class); GatewayConfig gatewayConfig = EasyMock.createNiceMock(GatewayConfig.class); EasyMock.expect(request.getMethod()).andReturn(METHOD).anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn(PATH).anyTimes(); EasyMock.expect(request.getContextPath()).andReturn(CONTEXT_PATH).anyTimes(); EasyMock.expect(request.getRemoteAddr()).andReturn(ADDRESS).anyTimes(); EasyMock.expect(request.getRemoteHost()).andReturn(HOST).anyTimes(); EasyMock.expect(request.getServletContext()).andReturn(context).anyTimes(); EasyMock.expect(context.getAttribute(GatewayConfig.GATEWAY_CONFIG_ATTRIBUTE)).andReturn(gatewayConfig) .anyTimes(); EasyMock.expect(gatewayConfig.getHeaderNameForRemoteAddress()).andReturn("Custom-Forwarded-For").anyTimes(); EasyMock.replay(request); EasyMock.replay(context); EasyMock.replay(gatewayConfig); HttpServletResponse response = EasyMock.createNiceMock(HttpServletResponse.class); EasyMock.replay(response); FilterChain chain = EasyMock.createNiceMock(FilterChain.class); EasyMock.replay(chain); Filter filter = EasyMock.createNiceMock(Filter.class); EasyMock.replay(filter); GatewayFilter gateway = new GatewayFilter(); gateway.addFilter("path", "filter", filter, null, null); gateway.init(config); gateway.doFilter(request, response, chain); gateway.destroy(); assertThat(CollectAppender.queue.size(), is(1)); Iterator<LoggingEvent> iterator = CollectAppender.queue.iterator(); LoggingEvent accessEvent = iterator.next(); verifyAuditEvent(accessEvent, CONTEXT_PATH + PATH, ResourceType.URI, Action.ACCESS, ActionOutcome.UNAVAILABLE, null, "Request method: GET"); }
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/*from ww w. j a v a 2s . c om*/ * * @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.apache.ranger.security.web.filter.RangerSSOAuthenticationFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; String xForwardedURL = constructForwardableURL(httpRequest); if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) { synchronized (httpRequest.getServletContext()) { if (httpRequest.getServletContext().getAttribute(httpRequest.getRequestedSessionId()) != null && "locallogin".equals(httpRequest.getServletContext() .getAttribute(httpRequest.getRequestedSessionId()).toString())) { httpRequest.getSession().setAttribute("locallogin", "true"); httpRequest.getServletContext().removeAttribute(httpRequest.getRequestedSessionId()); }//from w w w .j a v a 2 s. c o m } } RangerSecurityContext context = RangerContextHolder.getSecurityContext(); UserSessionBase session = context != null ? context.getUserSession() : null; boolean ssoEnabled = session != null ? session.isSSOEnabled() : PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false); String userAgent = httpRequest.getHeader("User-Agent"); if (httpRequest.getSession() != null) { if (httpRequest.getSession().getAttribute("locallogin") != null) { servletRequest.setAttribute("ssoEnabled", false); filterChain.doFilter(servletRequest, servletResponse); return; } } //If sso is enable and request is not for local login and is from browser then it will go inside and try for knox sso authentication if (ssoEnabled && !httpRequest.getRequestURI().contains(LOCAL_LOGIN_URL)) { //if jwt properties are loaded and is current not authenticated then it will go for sso authentication //Note : Need to remove !isAuthenticated() after knoxsso solve the bug from cross-origin script if (jwtProperties != null && !isAuthenticated()) { HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; String serializedJWT = getJWTFromCookie(httpRequest); // if we get the hadoop-jwt token from the cookies then will process it further if (serializedJWT != null) { SignedJWT jwtToken = null; try { jwtToken = SignedJWT.parse(serializedJWT); boolean valid = validateToken(jwtToken); //if the public key provide is correct and also token is not expired the process token if (valid) { String userName = jwtToken.getJWTClaimsSet().getSubject(); LOG.info("SSO login user : " + userName); String rangerLdapDefaultRole = PropertiesUtil.getProperty("ranger.ldap.default.role", "ROLE_USER"); //if we get the userName from the token then log into ranger using the same user if (userName != null && !userName.trim().isEmpty()) { final List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority(rangerLdapDefaultRole)); final UserDetails principal = new User(userName, "", grantedAuths); final Authentication finalAuthentication = new UsernamePasswordAuthenticationToken( principal, "", grantedAuths); WebAuthenticationDetails webDetails = new WebAuthenticationDetails(httpRequest); ((AbstractAuthenticationToken) finalAuthentication).setDetails(webDetails); RangerAuthenticationProvider authenticationProvider = new RangerAuthenticationProvider(); authenticationProvider.setSsoEnabled(ssoEnabled); Authentication authentication = authenticationProvider .authenticate(finalAuthentication); authentication = getGrantedAuthority(authentication); SecurityContextHolder.getContext().setAuthentication(authentication); } filterChain.doFilter(servletRequest, httpServletResponse); } // if the token is not valid then redirect to knox sso else { if (isWebUserAgent(userAgent)) { String ssourl = constructLoginURL(httpRequest, xForwardedURL); if (LOG.isDebugEnabled()) { LOG.debug("SSO URL = " + ssourl); } httpServletResponse.sendRedirect(ssourl); } else { filterChain.doFilter(servletRequest, httpServletResponse); } } } catch (ParseException e) { LOG.warn("Unable to parse the JWT token", e); } } // if the jwt token is not available then redirect it to knox sso else { if (isWebUserAgent(userAgent)) { String ssourl = constructLoginURL(httpRequest, xForwardedURL); if (LOG.isDebugEnabled()) { LOG.debug("SSO URL = " + ssourl); } httpServletResponse.sendRedirect(ssourl); } else { filterChain.doFilter(servletRequest, httpServletResponse); } } } //if property is not loaded or is already authenticated then proceed further with next filter else { filterChain.doFilter(servletRequest, servletResponse); } } else if (ssoEnabled && ((HttpServletRequest) servletRequest).getRequestURI().contains(LOCAL_LOGIN_URL) && isWebUserAgent(userAgent) && isAuthenticated()) { //If already there's an active session with sso and user want's to switch to local login(i.e without sso) then it won't be navigated to local login // In this scenario the user as to use separate browser String url = ((HttpServletRequest) servletRequest).getRequestURI().replace(LOCAL_LOGIN_URL + "/", ""); url = url.replace(LOCAL_LOGIN_URL, ""); LOG.warn( "There is an active session and if you want local login to ranger, try this on a separate browser"); ((HttpServletResponse) servletResponse).sendRedirect(url); } //if sso is not enable or the request is not from browser then proceed further with next filter else { filterChain.doFilter(servletRequest, servletResponse); } }
From source file:org.everit.osgi.authentication.cas.internal.CasAuthenticationComponent.java
/** * Processes the CAS (back channel) logout requests. It retrieves the invalidated service ticket from the logout * request and invalidates the {@link HttpSession} assigned to that service ticket. *//*w w w. jav a2 s . c o m*/ private void processBackChannelLogout(final HttpServletRequest httpServletRequest, final HttpServletResponse httpServletResponse) throws IOException { String logoutRequest = httpServletRequest.getParameter(requestParamNameLogoutRequest); String sessionIndex = getTextForElement(logoutRequest, SESSION_INDEX); ServletContext servletContext = httpServletRequest.getServletContext(); CasHttpSessionRegistry casHttpSessionRegistry = CasHttpSessionRegistry.getInstance(servicePid, servletContext); casHttpSessionRegistry.removeByServiceTicket(sessionIndex).ifPresent((httpSession) -> { try { httpSession.invalidate(); } catch (IllegalStateException e) { logService.log(LogService.LOG_DEBUG, e.getMessage(), e); } }); }
From source file:org.adeptnet.atlassian.common.Common.java
public String getKrb5UserName(final HttpServletRequest request) { if (!krb5Enabled) { if (LOG.isDebugEnabled()) { LOG.debug("!krb5Enabled"); }/*from ww w .ja v a 2 s . co m*/ return null; } final String _ticket = request.getHeader(Krb5.AUTHORIZATION); if (_ticket == null) { return null; } if (LOG.isDebugEnabled()) { LOG.debug("Found Kerberos Ticket"); } if (LOG.isTraceEnabled()) { LOG.trace(_ticket); } final String ticket = Krb5.extractTicket(_ticket); if (ticket == null) { return null; } final String serverName = Krb5.resolveServerName(request.getServerName()); krb5Cfg.init(getFileName(request.getServletContext())); final String realm = String.format("@%s", krb5Cfg.getRealm()); final String spn = String.format("HTTP/%s%s", serverName, realm); if (LOG.isDebugEnabled()) { LOG.debug(String.format("SPN: %s", spn)); } final String username = new Krb5(krb5Cfg).isTicketValid(spn, Base64.getDecoder().decode(ticket)); if (username == null || !username.endsWith(realm)) { LOG.error(String.format("Invalid username: %s", username)); return null; } return username.split("@")[0]; }
From source file:com.pdfhow.diff.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * * @param request//w w w . ja v a 2s. c o m * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (!ServletFileUpload.isMultipartContent(request)) { throw new IllegalArgumentException( "Request is not multipart, please 'multipart/form-data' enctype for your form."); } ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); PrintWriter writer = response.getWriter(); response.setContentType("application/json"); JSONArray json = new JSONArray(); try { List<FileItem> items = uploadHandler.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { File file = new File(request.getServletContext().getRealPath("/") + "imgs/", item.getName()); item.write(file); JSONObject jsono = new JSONObject(); jsono.put("name", item.getName()); jsono.put("size", item.getSize()); jsono.put("url", "UploadServlet?getfile=" + item.getName()); jsono.put("thumbnail_url", "UploadServlet?getthumb=" + item.getName()); jsono.put("delete_url", "UploadServlet?delfile=" + item.getName()); jsono.put("delete_type", "GET"); json.put(jsono); System.out.println(json.toString()); } } } catch (FileUploadException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { writer.write(json.toString()); writer.close(); } }
From source file:org.jbpm.designer.repository.VFSRepositoryGitFileSystemTest.java
@Test public void testCreateGlobalDirOnNewProject() throws Exception { ServletContext servletContext = mock(ServletContext.class); when(servletContext.getRealPath(anyString())).thenReturn(getClass().getResource("default.json").getFile()); HttpServletRequest servletRequest = mock(HttpServletRequest.class); when(servletRequest.getServletContext()).thenReturn(servletContext); VFSRepository repository = new VFSRepository(producer.getIoService()); repository.setDescriptor(descriptor); repository.setServletRequest(servletRequest); Directory testProjectDir = repository.createDirectory("/mytestproject"); final KieModule mockModule = mock(KieModule.class); when(mockModule.getRootPath()).thenReturn(Paths .convert(producer.getIoService().get(URI.create(decodeUniqueId(testProjectDir.getUniqueId()))))); final NewModuleEvent event = mock(NewModuleEvent.class); when(event.getModule()).thenReturn(mockModule); repository.createGlobalDirOnNewProject(event); boolean globalDirectoryExists = repository.directoryExists("/mytestproject/global"); assertTrue(globalDirectoryExists);/*from w w w. ja va 2s . com*/ Collection<Asset> foundFormTemplates = repository.listAssets("/mytestproject/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplates); assertEquals(0, foundFormTemplates.size()); Collection<Asset> foundJSONAssets = repository.listAssets("/mytestproject/global", new FilterByExtension("json")); assertNotNull(foundJSONAssets); assertEquals(3, foundJSONAssets.size()); Collection<Asset> foundWidAssets = repository.listAssets("/mytestproject", new FilterByExtension("wid")); assertNotNull(foundWidAssets); assertEquals(0, foundWidAssets.size()); // call again to try to trigger FileAlreadyExistsException repository.createGlobalDirOnNewProject(event); boolean globalDirectoryStillExists = repository.directoryExists("/mytestproject/global"); assertTrue(globalDirectoryStillExists); // no new files or copies were added Collection<Asset> foundFormTemplatesAfterSecondCall = repository.listAssets("/mytestproject/global", new FilterByExtension("fw")); assertNotNull(foundFormTemplatesAfterSecondCall); assertEquals(0, foundFormTemplatesAfterSecondCall.size()); Collection<Asset> foundJSONAssetsAfterSecondCall = repository.listAssets("/mytestproject/global", new FilterByExtension("json")); assertNotNull(foundJSONAssetsAfterSecondCall); assertEquals(3, foundJSONAssetsAfterSecondCall.size()); Collection<Asset> foundWidAssetsAfterSecondCall = repository.listAssets("/mytestproject", new FilterByExtension("wid")); assertNotNull(foundWidAssetsAfterSecondCall); assertEquals(0, foundWidAssetsAfterSecondCall.size()); }