List of usage examples for javax.servlet.http HttpServletRequest getPathInfo
public String getPathInfo();
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN" }) @RequestMapping(method = RequestMethod.PUT, produces = "text/html") public String update(@RequestParam(value = "_proceed", required = false) String proceed, @Valid DataSet dataSet, BindingResult bindingResult, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { log.info("update(): handles PUT"); try {//from ww w . j a va 2 s . com User user = userService.user_findByLogin(principal.getName()); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { if (bindingResult.hasErrors()) { populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } if (surveySettingsService.dataset_findByName(dataSet.getName()) != null && !surveySettingsService .dataset_findByName(dataSet.getName()).getId().equals(dataSet.getId())) { bindingResult.rejectValue("name", "field_unique"); populateEditForm(uiModel, dataSet, user); return "settings/datasets/update"; } uiModel.asMap().clear(); dataSet = surveySettingsService.dataSet_merge(dataSet); return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSet.getId().toString(), httpServletRequest); } else { return "redirect:/settings/datasets"; } } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.versatus.jwebshield.filter.SecurityFilter.java
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Assume its HTTP HttpServletRequest httpReq = (HttpServletRequest) request; String reqInfo = "J-WebShield Alert: CSRF attack detected! request URL=" + httpReq.getRequestURL().toString() + "| from IP address=" + httpReq.getRemoteAddr(); logger.debug("doFilter: IP address=" + httpReq.getRemoteAddr()); logger.debug("doFilter: pathInfo=" + httpReq.getPathInfo()); logger.debug("doFilter: queryString=" + httpReq.getQueryString()); logger.debug("doFilter: requestURL=" + httpReq.getRequestURL().toString()); logger.debug("doFilter: method=" + httpReq.getMethod()); logger.debug("doFilter: Origin=" + httpReq.getHeader("Origin")); logger.info("doFilter: Referer=" + httpReq.getHeader("Referer")); logger.info("doFilter: " + csrfHeaderName + "=" + httpReq.getHeader(csrfHeaderName)); UrlExclusionList exclList = (UrlExclusionList) request.getServletContext() .getAttribute(SecurityConstant.CSRF_CHECK_URL_EXCL_LIST_ATTR_NAME); HttpSession session = httpReq.getSession(false); if (session == null) { chain.doFilter(request, response); return;/*from w ww . j av a 2 s.c o m*/ } logger.debug("doFilter: matching " + httpReq.getRequestURI() + " to exclusions list " + exclList.getExclusionMap()); try { if (!exclList.isEmpty() && exclList.isMatch(httpReq.getRequestURI())) { chain.doFilter(request, response); return; } } catch (Exception e) { logger.error("doFilter", e); } // check CSRF cookie/header boolean csrfHeaderPassed = false; String rawCsrfHeaderVal = httpReq.getHeader(csrfHeaderName); if (useCsrfToken && StringUtils.isNotBlank(rawCsrfHeaderVal)) { String csrfHeader = StringUtils.strip(httpReq.getHeader(csrfHeaderName), "\""); logger.debug("doFilter: csrfHeader after decoding" + csrfHeader); Cookie[] cookies = httpReq.getCookies(); for (Cookie c : cookies) { String name = c.getName(); if (StringUtils.isNotBlank(csrfCookieName) && csrfCookieName.equals(name)) { logger.debug("doFilter: cookie domain=" + c.getDomain() + "|name=" + name + "|value=" + c.getValue() + "|path=" + c.getPath() + "|maxage=" + c.getMaxAge() + "|httpOnly=" + c.isHttpOnly()); logger.debug("doFilter: string comp:" + StringUtils.difference(csrfHeader, c.getValue())); if (StringUtils.isNotBlank(csrfHeader) && csrfHeader.equals(c.getValue())) { csrfHeaderPassed = true; logger.info("Header " + csrfHeaderName + " value matches the cookie " + csrfCookieName); break; } else { logger.info( "Header " + csrfHeaderName + " value does not match the cookie " + csrfCookieName); } } } // String csrfCookieVal = (String) session // .getAttribute(SecurityConstant.CSRFCOOKIE_VALUE_PARAM); // if (csrfCookieVal != null && csrfCookieVal.equals(csrfHeader)) { // // chain.doFilter(request, response); // // return; // csrfHeaderPassed = true; // } else { // // logger.info(reqInfo); // // sendSecurityReject(response); // } } if (useCsrfToken && csrfHeaderPassed) { chain.doFilter(request, response); return; } // Validate that the salt is in the cache Cache<SecurityInfo, SecurityInfo> csrfPreventionSaltCache = (Cache<SecurityInfo, SecurityInfo>) httpReq .getSession().getAttribute(SecurityConstant.SALT_CACHE_ATTR_NAME); if (csrfPreventionSaltCache != null) { // Get the salt sent with the request String saltName = (String) httpReq.getSession().getAttribute(SecurityConstant.SALT_PARAM_NAME); logger.debug("doFilter: csrf saltName=" + saltName); if (saltName != null) { String salt = httpReq.getParameter(saltName); logger.debug("doFilter: csrf salt=" + salt); if (salt != null) { SecurityInfo si = new SecurityInfo(saltName, salt); logger.debug("doFilter: csrf token=" + csrfPreventionSaltCache.getIfPresent(si)); SecurityInfo cachedSi = csrfPreventionSaltCache.getIfPresent(si); if (cachedSi != null) { // csrfPreventionSaltCache.invalidate(si); if (SecurityTokenFilter.checkReferer) { String refHeader = StringUtils.defaultString(httpReq.getHeader("Referer")); logger.debug("doFilter: refHeader=" + refHeader); if (StringUtils.isNotBlank(refHeader)) { try { URL refUrl = new URL(refHeader); refHeader = refUrl.getHost(); } catch (MalformedURLException mex) { logger.debug("doFilter: parsing referer header failed", mex); } } if (!cachedSi.getRefererHost().isEmpty() && !refHeader.equalsIgnoreCase(cachedSi.getRefererHost())) { logger.info("Potential CSRF detected - Referer host does not match orignal! " + refHeader + " != " + cachedSi.getRefererHost()); sendSecurityReject(response); } } chain.doFilter(request, response); } else { logger.info(reqInfo); sendSecurityReject(response); } } else if (httpMethodMatch(httpReq.getMethod())) { // let flow through chain.doFilter(request, response); } else { logger.info(reqInfo); sendSecurityReject(response); } } } else { chain.doFilter(request, response); } }
From source file:fll.web.api.TournamentsServlet.java
@Override protected final void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { final ServletContext application = getServletContext(); final DataSource datasource = ApplicationAttributes.getDataSource(application); Connection connection = null; try {//ww w .j a v a 2s. co m connection = datasource.getConnection(); final ObjectMapper jsonMapper = new ObjectMapper(); response.reset(); response.setContentType("application/json"); final PrintWriter writer = response.getWriter(); final String pathInfo = request.getPathInfo(); if (null != pathInfo && pathInfo.length() > 1) { final String tournamentStr = pathInfo.substring(1); int id; if ("current".equals(tournamentStr)) { id = Queries.getCurrentTournament(connection); } else { try { id = Integer.parseInt(tournamentStr); } catch (final NumberFormatException e) { throw new RuntimeException("Error parsing tournament id " + tournamentStr, e); } } final Tournament tournament = Tournament.findTournamentByID(connection, id); if (null != tournament) { jsonMapper.writeValue(writer, tournament); return; } else { throw new RuntimeException("No tournament found with id " + id); } } final Collection<Tournament> tournaments = Tournament.getTournaments(connection); jsonMapper.writeValue(writer, tournaments); } catch (final SQLException e) { throw new RuntimeException(e); } finally { SQLFunctions.close(connection); } }
From source file:com.jd.survey.web.settings.DataSetController.java
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" }) @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "text/html") public String importDatasetItems(@RequestParam("file") MultipartFile file, @RequestParam("id") Long dataSetId, @RequestParam("ignoreFirstRow") Boolean ignoreFirstRow, @RequestParam(value = "_proceed", required = false) String proceed, Principal principal, Model uiModel, HttpServletRequest httpServletRequest) { try {// www .j ava 2 s .com String login = principal.getName(); User user = userService.user_findByLogin(login); if (!user.isAdmin()) { log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo() + " attempted by user login:" + principal.getName() + "from IP:" + httpServletRequest.getLocalAddr()); return "accessDenied"; } if (proceed != null) { log.info(file.getContentType()); //if file is empty OR the file type is incorrect the upload page is returned with an error message. if (file.isEmpty() || !((file.getContentType().equalsIgnoreCase("text/csv")) || (file.getContentType().equals("application/vnd.ms-excel")) || (file.getContentType().equals("text/plain")))) { uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } try { CSVReader csvReader; csvReader = new CSVReader(new InputStreamReader(file.getInputStream())); surveySettingsService.importDatasetItems(csvReader, dataSetId, ignoreFirstRow); //done Redirect to the set view page return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest) + "?page=1&size=15"; } catch (Exception e) { log.error(e.getMessage(), e); uiModel.addAttribute("dataSet", surveySettingsService.dataSet_findById(dataSetId)); uiModel.addAttribute("emptyFileError", true); return "settings/datasets/upload"; } } else { return "redirect:/settings/datasets/" + encodeUrlPathSegment(dataSetId.toString(), httpServletRequest); } } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:org.attribyte.api.pubsub.impl.server.BroadcastServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { long startNanos = System.nanoTime(); byte[] broadcastContent = ByteStreams.toByteArray(request.getInputStream()); long endNanos = System.nanoTime(); String topicURL = request.getPathInfo(); if (maxBodyBytes > 0 && broadcastContent.length > maxBodyBytes) { logNotification(request, topicURL, NOTIFICATION_TOO_LARGE.statusCode, null); Bridge.sendServletResponse(NOTIFICATION_TOO_LARGE, response); return;/*from ww w . j a v a 2s . c om*/ } Response endpointResponse; if (topicURL != null) { if (filters.size() > 0) { String checkHeader = request.getHeader(BasicAuthScheme.AUTH_HEADER); for (BasicAuthFilter filter : filters) { if (filter.reject(topicURL, checkHeader)) { logNotification(request, topicURL, Response.Code.UNAUTHORIZED, broadcastContent); response.sendError(Response.Code.UNAUTHORIZED, "Unauthorized"); return; } } } try { Topic topic = topicCache != null ? topicCache.getIfPresent(topicURL) : null; if (topic == null) { topic = datastore.getTopic(topicURL, autocreateTopics); if (topicCache != null && topic != null) { topicCache.put(topicURL, topic); } } if (topic != null) { NotificationMetrics globalMetrics = endpoint.getGlobalNotificationMetrics(); NotificationMetrics metrics = endpoint.getNotificationMetrics(topic.getId()); metrics.notificationSize.update(broadcastContent.length); globalMetrics.notificationSize.update(broadcastContent.length); long acceptTimeNanos = endNanos - startNanos; metrics.notifications.update(acceptTimeNanos, TimeUnit.NANOSECONDS); globalMetrics.notifications.update(acceptTimeNanos, TimeUnit.NANOSECONDS); Notification notification = new Notification(topic, null, broadcastContent); //No custom headers... final boolean queued = endpoint.enqueueNotification(notification); if (queued) { if (replicationTopic != null) { final boolean replicationQueued = endpoint .enqueueNotification(new Notification(replicationTopic, Collections.singleton( new Header(REPLICATION_TOPIC_HEADER, topic.getURL())), broadcastContent)); if (!replicationQueued) { //What to do? logger.error("Replication failure due to notification capacity limits!"); } } if (!jsonEnabled) { endpointResponse = ACCEPTED_RESPONSE; } else { ResponseBuilder builder = new ResponseBuilder(); builder.setStatusCode(ACCEPTED_RESPONSE.statusCode); builder.addHeader("Content-Type", ServerUtil.JSON_CONTENT_TYPE); ObjectNode responseNode = JsonNodeFactory.instance.objectNode(); ArrayNode idsNode = responseNode.putArray("messageIds"); idsNode.add(Long.toString(notification.getCreateTimestampMicros())); builder.setBody(responseNode.toString().getBytes(Charsets.UTF_8)); endpointResponse = builder.create(); } } else { endpointResponse = CAPACITY_ERROR_RESPONSE; } } else { endpointResponse = UNKNOWN_TOPIC_RESPONSE; } } catch (DatastoreException de) { logger.error("Problem selecting topic", de); endpointResponse = INTERNAL_ERROR_RESPONSE; } } else { endpointResponse = NO_TOPIC_RESPONSE; } logNotification(request, topicURL, endpointResponse.statusCode, broadcastContent); Bridge.sendServletResponse(endpointResponse, response); }
From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
/** * Reads the request URI from {@code servletRequest} and rewrites it, considering targetUri. * It's used to make the new request.//from ww w .j a v a 2 s. co m */ protected String rewriteUrlFromRequest(HttpServletRequest servletRequest, String location) { StringBuilder uri = new StringBuilder(500); uri.append(location); // Handle the path given to the servlet if (servletRequest.getPathInfo() != null) {//ex: /my/path.html uri.append(encodeUriQuery(servletRequest.getPathInfo())); } // Handle the query string & fragment String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment String fragment = null; //split off fragment from queryString, updating queryString if found if (queryString != null) { int fragIdx = queryString.indexOf('#'); if (fragIdx >= 0) { fragment = queryString.substring(fragIdx + 1); queryString = queryString.substring(0, fragIdx); } } queryString = rewriteQueryStringFromRequest(servletRequest, queryString); if (queryString != null && queryString.length() > 0) { uri.append('?'); uri.append(encodeUriQuery(queryString)); } if (doSendUrlFragment && fragment != null) { uri.append('#'); uri.append(encodeUriQuery(fragment)); } return uri.toString(); }
From source file:net.lightbody.bmp.proxy.jetty.servlet.AdminServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getQueryString() != null && request.getQueryString().length() > 0) { String target = doAction(request); response.sendRedirect(request.getContextPath() + request.getServletPath() + (request.getPathInfo() != null ? request.getPathInfo() : "") + (target != null ? ("#" + target) : "")); return;//w ww . ja v a 2 s .co m } Page page = new Page(); page.title(getServletInfo()); page.addHeader(""); page.attribute("text", "#000000"); page.attribute(Page.BGCOLOR, "#FFFFFF"); page.attribute("link", "#606CC0"); page.attribute("vlink", "#606CC0"); page.attribute("alink", "#606CC0"); page.add(new Block(Block.Bold).add(new Font(3, true).add(getServletInfo()))); page.add(Break.rule); Form form = new Form(request.getContextPath() + request.getServletPath() + "?A=exit"); form.method("GET"); form.add(new Input(Input.Submit, "A", "Exit All Servers")); page.add(form); page.add(Break.rule); page.add(new Heading(3, "Components:")); List sList = new List(List.Ordered); page.add(sList); String id1; int i1 = 0; Iterator s = _servers.iterator(); while (s.hasNext()) { id1 = "" + i1++; HttpServer server = (HttpServer) s.next(); Composite sItem = sList.newItem(); sItem.add("<B>HttpServer "); sItem.add(lifeCycle(request, id1, server)); sItem.add("</B>"); sItem.add(Break.line); sItem.add("<B>Listeners:</B>"); List lList = new List(List.Unordered); sItem.add(lList); HttpListener[] listeners = server.getListeners(); for (int i2 = 0; i2 < listeners.length; i2++) { HttpListener listener = listeners[i2]; String id2 = id1 + ":" + listener; lList.add(lifeCycle(request, id2, listener)); } Map hostMap = server.getHostMap(); sItem.add("<B>Contexts:</B>"); List hcList = new List(List.Unordered); sItem.add(hcList); Iterator i2 = hostMap.entrySet().iterator(); while (i2.hasNext()) { Map.Entry hEntry = (Map.Entry) (i2.next()); String host = (String) hEntry.getKey(); PathMap contexts = (PathMap) hEntry.getValue(); Iterator i3 = contexts.entrySet().iterator(); while (i3.hasNext()) { Map.Entry cEntry = (Map.Entry) (i3.next()); String contextPath = (String) cEntry.getKey(); java.util.List contextList = (java.util.List) cEntry.getValue(); Composite hcItem = hcList.newItem(); if (host != null) hcItem.add("Host=" + host + ":"); hcItem.add("ContextPath=" + contextPath); String id3 = id1 + ":" + host + ":" + (contextPath.length() > 2 ? contextPath.substring(0, contextPath.length() - 2) : contextPath); List cList = new List(List.Ordered); hcItem.add(cList); for (int i4 = 0; i4 < contextList.size(); i4++) { String id4 = id3 + ":" + i4; Composite cItem = cList.newItem(); HttpContext hc = (HttpContext) contextList.get(i4); cItem.add(lifeCycle(request, id4, hc)); cItem.add("<BR>ResourceBase=" + hc.getResourceBase()); cItem.add("<BR>ClassPath=" + hc.getClassPath()); List hList = new List(List.Ordered); cItem.add(hList); int handlers = hc.getHandlers().length; for (int i5 = 0; i5 < handlers; i5++) { String id5 = id4 + ":" + i5; HttpHandler handler = hc.getHandlers()[i5]; Composite hItem = hList.newItem(); hItem.add(lifeCycle(request, id5, handler, handler.getName())); if (handler instanceof ServletHandler) { hItem.add("<BR>" + ((ServletHandler) handler).getServletMap()); } } } } } sItem.add("<P>"); } response.setContentType("text/html"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache,no-store"); Writer writer = response.getWriter(); page.write(writer); writer.flush(); }
From source file:seava.j4e.web.controller.ui.extjs.AbstractUiExtjsController.java
protected void _prepare(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=UTF-8"); if (logger.isInfoEnabled()) { logger.info("Handling request for ui.extjs: ", request.getPathInfo()); }/*from w w w. j a v a2 s . c o m*/ String server = request.getServerName(); int port = request.getServerPort(); String userRolesStr = null; this.prepareRequest(request, response); try { ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); IUser user = su.getUser(); IUserSettings prefs = user.getSettings(); Session.user.set(user); model.put("statics", BeansWrapper.getDefaultInstance().getStaticModels()); model.put("constantsJsFragment", this.getConstantsJsFragment()); model.put("user", user); DateFormatAttribute[] masks = DateFormatAttribute.values(); Map<String, String> dateFormatMasks = new HashMap<String, String>(); for (int i = 0, len = masks.length; i < len; i++) { DateFormatAttribute mask = masks[i]; if (mask.isForJs()) { dateFormatMasks.put(mask.name().replace("EXTJS_", ""), prefs.getDateFormatMask(mask.name())); } } model.put("dateFormatMasks", dateFormatMasks); model.put("modelDateFormat", this.getSettings().get(Constants.PROP_EXTJS_MODEL_DATE_FORMAT)); model.put("decimalSeparator", prefs.getDecimalSeparator()); model.put("thousandSeparator", prefs.getThousandSeparator()); StringBuffer sb = new StringBuffer(); int i = 0; for (String role : user.getProfile().getRoles()) { if (i > 0) { sb.append(","); } sb.append("\"" + role + "\""); i++; } userRolesStr = sb.toString(); } catch (ClassCastException e) { // not authenticated } String hostUrl = ((request.isSecure()) ? "https" : "http") + "://" + server + ((port != 80) ? (":" + port) : "");// + contextPath; model.put("productName", StringEscapeUtils.escapeJavaScript(this.getSettings().getProductName())); model.put("productDescription", this.getSettings().getProductDescription()); model.put("productVersion", this.getSettings().getProductVersion()); model.put("productVendor", this.getSettings().getProductVendor()); model.put("productUrl", this.getSettings().getProductUrl()); model.put("hostUrl", hostUrl); model.put("ctxpath", this.getSettings().get(Constants.PROP_CTXPATH)); // themes model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes()); // DNet extjs components in core and modules model.put("urlUiExtjsLib", getUiExtjsSettings().getUrlLib()); model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore()); model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n()); model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules()); model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSubpath()); model.put("urlUiExtjsModuleUseBundle", getUiExtjsSettings().isModuleUseBundle()); String lang = this.resolveLang(request, response); model.put("shortLanguage", StringEscapeUtils.escapeJavaScript(lang)); String theme = this.resolveTheme(request, response); model.put("theme", StringEscapeUtils.escapeJavaScript(theme)); model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE)); model.put("userRolesStr", userRolesStr); }
From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilter.java
/** * (non-Javadoc) @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, * javax.servlet.FilterChain).//w w w. j a v a 2 s . c o m */ public final void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain) throws IOException, ServletException { final boolean debug = logger.isDebugEnabled(); final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; String headerToken = request.getHeader(OPENSTACK_HEADER_TOKEN); String pathInfo = request.getPathInfo(); logger.debug(headerToken); logger.debug(pathInfo); // first of all, check HTTP if exists accept header if (!validateAcceptHeader(request, response)) { return; } MDC.put("txId", ((HttpServletRequest) req).getSession().getId()); if (pathInfo != null && (pathInfo.equals("/") || pathInfo.equals("/extensions"))) { /** * It is not needed to authenticate these operations */ logger.debug("Operation does not need to Authenticate"); } else { if (headerToken == null) { headerToken = ""; } try { String token = headerToken; if ("".equals(token)) { String str = "Missing token header"; logger.info(str); throw new BadCredentialsException(str); } String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID); logger.debug(tenantId); logger.debug(token); // String tenantId = request.getPathInfo().split("/")[3]; if (debug) { logger.debug("OpenStack Authentication Authorization header " + "found for user '" + token + "' and tenant " + tenantId); } UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(token, tenantId); authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); Authentication authResult = authenticationManager.authenticate(authRequest); if (debug) { logger.debug("Authentication success: " + authResult); } // check AUTH-TOKEN and VDC are the same String uri = request.getRequestURI(); logger.debug("URI: " + uri); if (uri.contains("vdc") && !uri.contains(tenantId)) { String str = "Bad credentials for requested VDC"; logger.info(str); throw new AccessDeniedException(str); } UserDetails user = (UserDetails) authResult.getPrincipal(); logger.debug("User: " + user.getUsername()); logger.debug("Token: " + user.getPassword()); if (authResult.isAuthenticated()) { SecurityContextHolder.getContext().setAuthentication(authRequest); } // SecurityContextHolder.setStrategyName("MODE_INHERITABLETHREADLOCAL"); rememberMeServices.loginSuccess(request, response, authResult); onSuccessfulAuthentication(request, response, authResult); } catch (AuthenticationException failed) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication request for failed: " + failed); } rememberMeServices.loginFail(request, response); onUnsuccessfulAuthentication(request, response, failed); if (ignoreFailure) { chain.doFilter(request, response); } else { authenticationEntryPoint.commence(request, response, failed); } return; } catch (AccessDeniedException ex) { throw ex; } catch (Exception ex) { SecurityContextHolder.clearContext(); if (debug) { logger.debug("Authentication exception: " + ex); } rememberMeServices.loginFail(request, response); if (ignoreFailure) { chain.doFilter(request, response); } else { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); } return; } String keystoneURL = systemPropertiesProvider.getProperty(SystemPropertiesProvider.KEYSTONE_URL); response.addHeader("Www-Authenticate", "Keystone uri='" + keystoneURL + "'"); } // TODO jesuspg: question:add APIException chain.doFilter(request, response); }
From source file:com.aliasi.demo.framework.DemoServlet.java
/** * Handles <code>POST</code> requests. First it determines what * type of demo is involved by looking at the path information. * If the extension is <code>/textInput.html</code>, it generates * the input form for the text input demo. If the extension is * <code>/fileInput.html</code>, it generates the input form for * file upload. If neither extension is present, it generates * the output for the demo, based on the properties determined * from the input./*from w w w .ja v a2 s . c om*/ * * @param request Servlet equest. * @param response Servlet response. * @throws IOException If there is an underlying I/O error. * @throws ServletException If there is an underlying servlet * error. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String pathInfo = request.getPathInfo(); if (pathInfo.equals("/response.xml")) { generateOutput(request, response); } else if (pathInfo.equals("/textInput.html")) { generateInputForm(request, response, true); } else if (pathInfo.equals("/fileInput.html")) { generateInputForm(request, response, false); } }