List of usage examples for javax.servlet ServletRequest getRequestDispatcher
public RequestDispatcher getRequestDispatcher(String path);
From source file:de.uni_koeln.spinfo.maalr.webapp.i18n.InternationalUrlFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //long start = System.nanoTime(); HttpServletRequest h = (HttpServletRequest) request; String uri = h.getRequestURI(); String path = h.getContextPath(); Locale userLocale = request.getLocale(); h.getSession().setAttribute("lang", userLocale.getLanguage()); String url = uri.substring(path.length()); /*/* w w w. ja v a 2 s . c o m*/ * Idee: die URL in ihre Bestandteile zerlegen und die einzelnen Teile * in einem Keyword-Tree matchen. Auf jeder Stufe wird dabei die eigentliche * URL um ein neues Element ergnzt. * * Funktioniert auf diese Weise gut fr statische URLs, aufbau eines Baums * fr URLs mit fest definierten Klassen (z.B. bersetzungsrichtung) ist ebenfalls mglich. * * Funktioniert aber nicht fr dynamische Bestandteile - da muss eine Wildcard * rein. * * :wrterbuch:deutsch-rumantsch:nase.html oder .json oder .xml * * Baum: * wrterbuch -> dictionary * deutsch-rumantsch -> tudesg->rumantsch * * -> * * ending * * Filter-Funktionalitt: * * a) Prfen, ob die URL schon in die Zielsprache bersetzt wurde. Falls ja: * doFilter() aufrufen, sonst bersetzen (andernfalls Endlos-Schleife). * * b) die gewhlte Sprache irgendwo in der Session hinterlegen, damit der * Rest des Programms (GUI) entsprechend der URL auch die richtigen Elemente * darstellt. * * c) Hilfsklasse notwendig, die URLs entsprechend der Sprache generiert, * z.B. fr dictionary (s.o.), aber auch fr "translate", einschlielich der * Durchblttern-Funktion. HTTP-GET sollte auch bersetzt werden (also Parameter-Namen), * POST nicht. * * d) Die Generierung des Baums darf lange dauern, die Abfrage muss aber * schnell sein - also z.B. Pattern.compile() beim Aufbau des Baums, nicht * beim Abfragen. * */ if ("/hilfe.html".equals(url) || "/help.html".equals(url)) { // change url and forward RequestDispatcher dispatcher = request.getRequestDispatcher("/agid.html"); // long end = System.nanoTime(); dispatcher.forward(request, response); } else { // long end = System.nanoTime(); chain.doFilter(request, response); } }
From source file:com.pliu.azuremgmtsdk.BasicFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; try {/*from w ww.j a v a2s .c o m*/ String subscriptionId = httpRequest.getParameter("subscriptionId"); if (subscriptionId != null) httpRequest.getSession().setAttribute("subscriptionId", subscriptionId); String currentUri = httpRequest.getRequestURL().toString(); String queryStr = httpRequest.getQueryString(); String fullUrl = currentUri + (queryStr != null ? "?" + queryStr : ""); // check if user has a AuthData in the session if (!AuthHelper.isAuthenticated(httpRequest)) { if (AuthHelper.containsAuthenticationData(httpRequest)) { processAuthenticationData(httpRequest, currentUri, fullUrl); } else { // not authenticated // we can get the tenant id for the subscription first getTenantIdForSubscription(httpRequest); // then authenticate sendAuthRedirect(httpRequest, httpResponse); return; } } if (isAuthDataExpired(httpRequest)) { updateAuthDataUsingRefreshToken(httpRequest); } } catch (AuthenticationException authException) { // something went wrong (like expiration or revocation of token) // we should invalidate AuthData stored in session and redirect to Authorization server removePrincipalFromSession(httpRequest); sendAuthRedirect(httpRequest, httpResponse); return; } catch (Throwable exc) { httpResponse.setStatus(500); request.setAttribute("error", exc.getMessage()); request.getRequestDispatcher("/error.jsp").forward(request, response); } } chain.doFilter(request, response); }
From source file:at.gv.egovernment.moa.id.configuration.filter.AuthenticationFilter.java
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterchain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) req; HttpServletResponse httpServletResponse = (HttpServletResponse) resp; HttpSession session = httpServletRequest.getSession(); Object authuserobj = session.getAttribute(Constants.SESSION_AUTH); AuthenticatedUser authuser = (AuthenticatedUser) authuserobj; String requestURL = WebAppUtil.getRequestURLWithParameters(httpServletRequest, true); log.trace("Request URL: " + requestURL); AuthenticationManager authManager = AuthenticationManager.getInstance(); if (!authManager.isActiveUser(authuser)) { //user is not active anymore. Invalidate session and reauthenticate user String authID = (String) session.getAttribute(Constants.SESSION_PVP2REQUESTID); session.invalidate();//from www. j a va2 s. co m authuser = null; //TODO: set infotext session = httpServletRequest.getSession(true); session.setAttribute(Constants.SESSION_PVP2REQUESTID, authID); } if (authuser == null && !this.isExcluded(requestURL)) { if (config.isLoginDeaktivated()) { //add dummy Daten log.warn("Authentication is deaktivated. Dummy authentication-information are used!"); if (authuser == null) { int sessionTimeOut = session.getMaxInactiveInterval(); Date sessionExpired = new Date( new Date().getTime() + (sessionTimeOut * Constants.ONE_MINUTE_IN_MILLIS)); authuser = AuthenticatedUser.generateDefaultUser(sessionExpired); authManager.setActiveUser(authuser); //authuser = new AuthenticatedUser(1, "Max", "TestUser", true, false); httpServletRequest.getSession().setAttribute(Constants.SESSION_AUTH, authuser); } if (MiscUtil.isNotEmpty(getAuthenticatedPage())) { if (loginPageForward) { log.debug("Authenticated page is set. Forwarding to \"" + getAuthenticatedPage() + "\"."); RequestDispatcher dispatcher = req.getRequestDispatcher(getAuthenticatedPage()); dispatcher.forward(httpServletRequest, httpServletResponse); } else { log.debug("Authenticated page is set. Redirecting to \"" + getAuthenticatedPage() + "\"."); httpServletResponse .sendRedirect(httpServletResponse.encodeRedirectURL(getAuthenticatedPage())); } return; } } else { if (MiscUtil.isNotEmpty(getAuthenticatedPage())) { log.debug( "Unable to find authentication data. Authenticated page is given so there is no need to save original request url. " + (loginPageForward ? "Forwarding" : "Redirecting") + " to login page \"" + loginPage + "\"."); } else { log.debug("Unable to find authentication data. Storing request url and " + (loginPageForward ? "forwarding" : "redirecting") + " to login page \"" + loginPage + "\"."); session.setAttribute(STORED_REQUEST_URL_ID, requestURL); } if (loginPageForward) { RequestDispatcher dispatcher = req.getRequestDispatcher(loginPage); dispatcher.forward(httpServletRequest, httpServletResponse); return; } else { httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(loginPage)); return; } } } else { try { filterchain.doFilter(req, resp); } catch (Exception e) { //String redirectURL = "./index.action"; //HttpServletResponse httpResp = (HttpServletResponse) resp; //redirectURL = httpResp.encodeRedirectURL(redirectURL); //resp.setContentType("text/html"); //((HttpServletResponse) resp).setStatus(302); //httpResp.addHeader("Location", redirectURL); //log.warn("A Filter Error occurs -> Redirect to Login-Form"); } } }
From source file:org.wso2.carbon.identity.application.authentication.endpoint.AuthenticationEndpointFilter.java
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String redirectUrl = null;/*w w w.j a v a 2 s .c o m*/ String appSpecificCustomPageConfigKey = null; String serviceProviderName = servletRequest.getParameter(REQUEST_PARAM_SP) != null ? servletRequest.getParameter(REQUEST_PARAM_SP) : servletRequest.getParameter(REQUEST_PARAM_APPLICATION) != null ? servletRequest.getParameter(REQUEST_PARAM_APPLICATION) : null; String relativePath = ((HttpServletRequest) servletRequest).getRequestURI() .substring(((HttpServletRequest) servletRequest).getContextPath().length()); if (StringUtils.isNotBlank(serviceProviderName)) { appSpecificCustomPageConfigKey = AuthenticationEndpointUtil.getApplicationSpecificCustomPageConfigKey( CharacterEncoder.getSafeText(serviceProviderName), relativePath); } if (appSpecificCustomPageConfigKey != null) { // Check for application specific custom page mappings matching the request uri. redirectUrl = AuthenticationEndpointUtil.getCustomPageRedirectUrl( context.getInitParameter(appSpecificCustomPageConfigKey), ((HttpServletRequest) servletRequest).getQueryString()); } if (redirectUrl == null) { // No application specific custom page mappings. // Check for global custom page mappings matching the request uri. redirectUrl = AuthenticationEndpointUtil.getCustomPageRedirectUrl( context.getInitParameter(relativePath), ((HttpServletRequest) servletRequest).getQueryString()); } if (redirectUrl != null) { // There is a custom configuration matching the request uri. Redirect. if (log.isDebugEnabled()) { log.debug("There is a custom configuration matching the request uri. Redirecting to : " + redirectUrl); } ((HttpServletResponse) servletResponse).sendRedirect(redirectUrl); return; } if (((HttpServletRequest) servletRequest).getRequestURI().contains(URI_LOGIN)) { String hrdParam = CharacterEncoder.getSafeText(servletRequest.getParameter(REQUEST_PARAM_HRD)); if (hrdParam != null && "true".equalsIgnoreCase(hrdParam)) { servletRequest.getRequestDispatcher("domain.jsp").forward(servletRequest, servletResponse); return; } Map<String, String> idpAuthenticatorMapping = new HashMap<String, String>(); String authenticators = CharacterEncoder .getSafeText(servletRequest.getParameter(REQUEST_PARAM_AUTHENTICATORS)); if (authenticators != null) { String[] authenticatorIdPMappings = authenticators.split(";"); for (String authenticatorIdPMapping : authenticatorIdPMappings) { String[] authenticatorIdPMapArr = authenticatorIdPMapping.split(":"); for (int i = 1; i < authenticatorIdPMapArr.length; i++) { if (idpAuthenticatorMapping.containsKey(authenticatorIdPMapArr[i])) { idpAuthenticatorMapping.put(authenticatorIdPMapArr[i], idpAuthenticatorMapping.get(authenticatorIdPMapArr[i]) + "," + authenticatorIdPMapArr[0]); } else { idpAuthenticatorMapping.put(authenticatorIdPMapArr[i], authenticatorIdPMapArr[0]); } } } } if (!idpAuthenticatorMapping.isEmpty()) { servletRequest.setAttribute(Constants.IDP_AUTHENTICATOR_MAP, idpAuthenticatorMapping); } String loadPage; String protocolType = CharacterEncoder.getSafeText(servletRequest.getParameter(REQUEST_PARAM_TYPE)); if (SAMLSSO.equals(protocolType)) { loadPage = URI_SAMLSSO_LOGIN; } else if (OPENID.equals(protocolType)) { loadPage = URI_OPENID_LOGIN; } else if (PASSIVESTS.equals(protocolType)) { loadPage = URI_PASSIVESTS_LOGIN; } else if (OAUTH2.equals(protocolType) || OIDC.equals(protocolType)) { loadPage = URI_OAUTH2_LOGIN; } else if (FIDO.equals(protocolType)) { loadPage = "authentication.jsp"; } else { loadPage = "login.jsp"; } servletRequest.getRequestDispatcher(loadPage).forward(servletRequest, servletResponse); } else { filterChain.doFilter(servletRequest, servletResponse); } }
From source file:com.google.zxing.web.DecodeServlet.java
private static void processImage(BufferedImage image, ServletRequest request, HttpServletResponse response) throws IOException, ServletException { LuminanceSource source = new BufferedImageLuminanceSource(image); BinaryBitmap bitmap = new BinaryBitmap(new GlobalHistogramBinarizer(source)); Collection<Result> results = Lists.newArrayListWithCapacity(1); try {/*from w w w . j av a2 s . c o m*/ Reader reader = new MultiFormatReader(); ReaderException savedException = null; try { // Look for multiple barcodes MultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader); Result[] theResults = multiReader.decodeMultiple(bitmap, HINTS); if (theResults != null) { results.addAll(Arrays.asList(theResults)); } } catch (ReaderException re) { savedException = re; } if (results.isEmpty()) { try { // Look for pure barcode Result theResult = reader.decode(bitmap, HINTS_PURE); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Look for normal barcode in photo Result theResult = reader.decode(bitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { try { // Try again with other binarizer BinaryBitmap hybridBitmap = new BinaryBitmap(new HybridBinarizer(source)); Result theResult = reader.decode(hybridBitmap, HINTS); if (theResult != null) { results.add(theResult); } } catch (ReaderException re) { savedException = re; } } if (results.isEmpty()) { handleException(savedException, response); return; } } catch (RuntimeException re) { // Call out unexpected errors in the log clearly log.log(Level.WARNING, "Unexpected exception from library", re); throw new ServletException(re); } String fullParameter = request.getParameter("full"); boolean minimalOutput = fullParameter != null && !Boolean.parseBoolean(fullParameter); if (minimalOutput) { response.setContentType(MediaType.PLAIN_TEXT_UTF_8.toString()); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); try (Writer out = new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) { for (Result result : results) { out.write(result.getText()); out.write('\n'); } } } else { request.setAttribute("results", results); request.getRequestDispatcher("decoderesult.jspx").forward(request, response); } }
From source file:org.eclipse.skalli.view.internal.filter.AbstractSearchFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // retrieve the logged-in user String userId = (String) request.getAttribute(Consts.ATTRIBUTE_USERID); User user = (User) request.getAttribute(Consts.ATTRIBUTE_USER); // calculate start param int start = toInt(request.getParameter(Consts.PARAM_START), 0, -1); // calculate count size param int count = toInt(request.getParameter(Consts.PARAM_COUNT), 10, 50); // retrieve search hits and based on that parent projects and subprojects SearchResult<Project> searchResult = getSearchHits(user, request, response, start, count); List<SearchHit<Project>> searchHits = searchResult.getResult(); Map<String, String> natures = getProjectNatures(searchHits); Map<String, Project> parents = getParents(searchHits); Map<String, List<Project>> parentChains = getParentChains(searchHits); Map<String, List<SearchHit<Project>>> subprojects = getSubprojects(searchHits); Map<String, List<String>> sourceLinks = getSourceLinks(userId, searchHits); // retrieve the favorites of the user Favorites favorites = getFavorites(user); // calculate params for pager int resultSize = searchResult.getResultCount(); int pages = (int) Math.ceil((double) resultSize / (double) count); int currentPage = (int) Math.floor((double) start / (double) count) + 1; long duration = searchResult.getDuration(); // set the request attributes request.setAttribute(ATTRIBUTE_TITLE, getTitle(user)); request.setAttribute(ATTRIBUTE_PROJECTS, searchHits); request.setAttribute(ATTRIBUTE_NATURES, natures); request.setAttribute(ATTRIBUTE_PARENTS, parents); request.setAttribute(ATTRIBUTE_PARENTCHAINS, parentChains); request.setAttribute(ATTRIBUTE_SUBPROJETS, subprojects); request.setAttribute(ATTRIBUTE_SOURCELINKS, sourceLinks); request.setAttribute(Consts.ATTRIBUTE_FAVORITES, favorites.asMap()); request.setAttribute(ATTRIBUTE_DURATION, duration); request.setAttribute(ATTRIBUTE_START, start); request.setAttribute(ATTRIBUTE_VIEWSIZE, count); request.setAttribute(ATTRIBUTE_RESULTSIZE, resultSize); request.setAttribute(ATTRIBUTE_CURRENTPAGE, currentPage); request.setAttribute(ATTRIBUTE_PAGES, pages); request.setAttribute(Consts.ATTRIBUTE_USER, user); if (((HttpServletRequest) request).getPathInfo() == null) { request.getRequestDispatcher(Consts.JSP_SEARCHRESULT).forward(request, response); return;// www .j av a 2 s .com } // proceed along the chain chain.doFilter(request, response); }
From source file:org.apache.solr.servlet.SolrDispatchFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain, boolean retry) throws IOException, ServletException { if (!(request instanceof HttpServletRequest)) return;/*from w ww . j a va 2 s . c o m*/ try { if (cores == null || cores.isShutDown()) { log.error( "Error processing the request. CoreContainer is either not initialized or shutting down."); throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Error processing the request. CoreContainer is either not initialized or shutting down."); } AtomicReference<ServletRequest> wrappedRequest = new AtomicReference<>(); if (!authenticateRequest(request, response, wrappedRequest)) { // the response and status code have already been // sent return; } if (wrappedRequest.get() != null) { request = wrappedRequest.get(); } request = closeShield(request, retry); response = closeShield(response, retry); if (cores.getAuthenticationPlugin() != null) { log.debug("User principal: {}", ((HttpServletRequest) request).getUserPrincipal()); } // No need to even create the HttpSolrCall object if this path is excluded. if (excludePatterns != null) { String requestPath = ((HttpServletRequest) request).getServletPath(); String extraPath = ((HttpServletRequest) request).getPathInfo(); if (extraPath != null) { // In embedded mode, servlet path is empty - include all post-context path here for // testing requestPath += extraPath; } for (Pattern p : excludePatterns) { Matcher matcher = p.matcher(requestPath); if (matcher.lookingAt()) { chain.doFilter(request, response); return; } } } HttpSolrCall call = getHttpSolrCall((HttpServletRequest) request, (HttpServletResponse) response, retry); ExecutorUtil.setServerThreadFlag(Boolean.TRUE); try { Action result = call.call(); switch (result) { case PASSTHROUGH: chain.doFilter(request, response); break; case RETRY: doFilter(request, response, chain, true); break; case FORWARD: request.getRequestDispatcher(call.getPath()).forward(request, response); break; } } finally { call.destroy(); ExecutorUtil.setServerThreadFlag(null); } } finally { consumeInputFully((HttpServletRequest) request); } }
From source file:org.shareok.data.webserv.filters.UserSessionFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try {//from w ww.j a v a 2 s .c om HttpServletRequest httpRequest = (HttpServletRequest) request; String contextPath = httpRequest.getServletPath(); if (contextPath.contains("/")) { contextPath = contextPath.split("/")[1]; } //.getContextPath(); if (null != contextPath && !"".equals(contextPath) && ShareokdataManager.requiredUserAuthentication(contextPath)) { SessionRepository<Session> repo = (SessionRepository<Session>) httpRequest .getAttribute(SessionRepository.class.getName()); if (contextPath.equals("register")) { String email = (String) httpRequest.getParameter("email"); String password = (String) httpRequest.getParameter("password"); String userName = (String) httpRequest.getParameter("nickname"); if (null == email || "".equals(email)) { throw new UserRegisterInfoNotFoundException( "Valid email register information is required!"); } if (null == password || "".equals(password)) { throw new UserRegisterInfoNotFoundException("Valid password is required for registration!"); } /***************** * Some password validation logic here: */ ExpiringSession session = (ExpiringSession) repo.createSession(); session.setMaxInactiveIntervalInSeconds(600); String sessionId = session.getId(); RedisUser user = redisUserService.findUserByUserEmail(email); if (null != user && password.equals(user.getPassword())) { session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user); user.setSessionKey(sessionId); user.setUserName(userName); redisUserService.updateUser(user); } else if (null == user) { ApplicationContext context = new ClassPathXmlApplicationContext("redisContext.xml"); user = (RedisUser) context.getBean("redisUser"); user.setEmail(email); user.setPassword(password); user.setSessionKey(sessionId); redisUserService.addUser(user); } else if (null != user && !password.equals(user.getPassword())) { throw new UserRegisterInfoNotFoundException( "Your login information does not match our records!`"); } session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), user); repo.save(session); chain.doFilter(request, response); // HttpServletResponse httpReponse = (HttpServletResponse)response; // httpReponse.sendRedirect("/webserv/home"); } else { boolean sessionValidated = false; HttpSession session = (HttpSession) httpRequest.getSession(false); if (null != session) { ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId()); if (null != exSession) { RedisUser user = (RedisUser) session .getAttribute(ShareokdataManager.getSessionRedisUserAttributeName()); if (null != user) { RedisUser userPersisted = redisUserService.findAuthenticatedUser(user.getEmail(), session.getId()); if (null != userPersisted) { sessionValidated = true; } } } } if (!sessionValidated) { if (null != session) { repo.delete(session.getId()); session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null); session.invalidate(); } httpRequest.logout(); //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response); HttpServletResponse httpReponse = (HttpServletResponse) response; httpReponse.sendRedirect("/webserv/login"); } else { chain.doFilter(request, response); } } } else { chain.doFilter(request, response); } } catch (IOException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (ServletException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } catch (UserRegisterInfoNotFoundException ex) { request.setAttribute("errorMessage", ex); request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response); } }