List of usage examples for javax.servlet.http HttpServletRequest getServletPath
public String getServletPath();
From source file:com.kesdip.license.web.servlet.UpdateServlet.java
/** * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *//*from ww w . j av a2 s.c o m*/ @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // make sure this is not a browser String userAgent = req.getHeader("user-agent"); if (!userAgent.startsWith("Java")) { if (logger.isDebugEnabled()) { logger.debug("'" + userAgent + "' forbidden"); } res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE); return; } // get the customer UUID String uuid = req.getRemoteUser(); if (StringUtils.isEmpty(uuid)) { logger.debug("Empty customer uuid"); res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE); return; } // if requesting site.xml or the root (Eclipse does both), check the DB String uri = req.getRequestURI(); String servletPath = req.getServletPath(); if (uri.endsWith(servletPath) || uri.endsWith(SITE_XML)) { if (!supportEnabled(uuid)) { logger.warn("Update denied for '" + uuid + "'"); res.sendError(HttpServletResponse.SC_FORBIDDEN, FORBIDDEN_MESSAGE); return; } } // if requesting site.xml, log the request if (uri.endsWith(SITE_XML)) { logUpdateRequest(uuid, req.getRemoteAddr(), userAgent); } // all OK, forward to the actual file String translatedUri = uri.substring(req.getContextPath().length()).replace(servletPath, actualUpdateRoot); if (logger.isTraceEnabled()) { logger.trace("Forwarding to '" + translatedUri + "'"); } RequestDispatcher rd = servletContext.getRequestDispatcher(translatedUri); rd.forward(req, res); }
From source file:net.maritimecloud.identityregistry.controllers.UserController.java
/** * Creates a new User//www .j a va2 s.c om * * @return a reply... * @throws McBasicRestException */ @RequestMapping(value = "/api/org/{orgMrn}/user", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)") public ResponseEntity<User> createUser(HttpServletRequest request, @PathVariable String orgMrn, @Valid @RequestBody User input, BindingResult bindingResult) throws McBasicRestException { ValidateUtil.hasErrors(bindingResult, request); Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being created belongs to the organization if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn) .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } // If the organization doesn't have its own Identity Provider we create the user in a special keycloak instance if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null || org.getIdentityProviderAttributes().isEmpty())) { String password = PasswordUtil.generatePassword(); keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE); try { keycloakAU.createUser(input.getMrn(), password, input.getFirstName(), input.getLastName(), input.getEmail(), orgMrn, input.getPermissions(), true); } catch (DuplicatedKeycloakEntry dke) { throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(), request.getServletPath()); } catch (IOException e) { throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR, MCIdRegConstants.ERROR_CREATING_KC_USER, request.getServletPath()); } // Send email to user with credentials emailUtil.sendUserCreatedEmail(input.getEmail(), input.getFirstName() + " " + input.getLastName(), input.getEmail(), password); } input.setIdOrganization(org.getId()); try { User newUser = this.entityService.save(input); return new ResponseEntity<>(newUser, HttpStatus.OK); } catch (DataIntegrityViolationException e) { // If save to DB failed, remove the user from keycloak if it was created. if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null || org.getIdentityProviderAttributes().isEmpty())) { keycloakAU.deleteUser(input.getEmail()); } throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(), request.getServletPath()); } } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }
From source file:lux.solr.XQueryComponent.java
private XdmValue buildEXPathRequest(Compiler compiler, Evaluator evaluator, SolrQueryRequest req) throws XPathException { LinkedTreeBuilder builder = new LinkedTreeBuilder( compiler.getProcessor().getUnderlyingConfiguration().makePipelineConfiguration()); builder.startDocument(0);//from w ww.ja va2s. c om builder.startElement(fQNameFor("http", EXPATH_HTTP_NS, "request"), AnyType.getInstance(), 0, 0); builder.namespace(new NamespaceBinding("http", EXPATH_HTTP_NS), 0); Request requestWrapper = (Request) req.getContext().get(SolrQueryContext.LUX_HTTP_SERVLET_REQUEST); addAttribute(builder, "method", requestWrapper.getMethod()); addAttribute(builder, "servlet", requestWrapper.getServletPath()); HttpServletRequest httpReq = (HttpServletRequest) requestWrapper.getRequest(); addAttribute(builder, "path", httpReq.getServletPath()); String pathInfo = requestWrapper.getPathInfo(); if (pathInfo != null) { addAttribute(builder, "path-info", pathInfo); } builder.startContent(); // child elements StringBuilder buf = new StringBuilder(); // authority buf.append(requestWrapper.getScheme()).append("://").append(requestWrapper.getServerName()).append(':') .append(requestWrapper.getServerPort()); String authority = buf.toString(); addSimpleElement(builder, "authority", authority); // url buf.append(httpReq.getServletPath()); if (httpReq.getQueryString() != null) { buf.append('?').append(httpReq.getQueryString()); } String url = buf.toString(); addSimpleElement(builder, "url", url); // context-root addSimpleElement(builder, "context-root", httpReq.getContextPath()); // path - just one part: we don't do any parsing of the path builder.startElement(fQNameFor("http", EXPATH_HTTP_NS, "path"), BuiltInAtomicType.UNTYPED_ATOMIC, 0, 0); builder.startContent(); addSimpleElement(builder, "part", httpReq.getServletPath()); builder.endElement(); // params Iterator<String> paramNames = req.getParams().getParameterNamesIterator(); while (paramNames.hasNext()) { String param = paramNames.next(); String[] values = req.getParams().getParams(param); for (String value : values) { builder.startElement(fQNameFor("http", EXPATH_HTTP_NS, "param"), BuiltInAtomicType.UNTYPED_ATOMIC, 0, 0); addAttribute(builder, "name", param); addAttribute(builder, "value", value); builder.startContent(); builder.endElement(); } } // headers Enumeration<String> headerNames = httpReq.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> headerValues = httpReq.getHeaders(headerName); while (headerValues.hasMoreElements()) { String value = headerValues.nextElement(); builder.startElement(fQNameFor("http", EXPATH_HTTP_NS, "header"), BuiltInAtomicType.UNTYPED_ATOMIC, 0, 0); addAttribute(builder, "name", headerName); addAttribute(builder, "value", value); builder.startContent(); builder.endElement(); } } ArrayList<XdmItem> resultSequence = null; if (req.getContentStreams() != null) { resultSequence = new ArrayList<XdmItem>(); handleContentStreams(builder, req, resultSequence, evaluator); } builder.endElement(); // end request builder.endDocument(); XdmNode expathReq = new XdmNode(builder.getCurrentRoot()); if (resultSequence == null) { return expathReq; } resultSequence.add(0, expathReq); return new XdmValue(resultSequence); }
From source file:org.jtwig.util.render.RenderHttpServletRequest.java
public RenderHttpServletRequest(HttpServletRequest initialRequest) { initialValues = snapshot(initialRequest, HttpServletRequest.class); Enumeration attributeNames = initialRequest.getAttributeNames(); if (attributeNames != null) { while (attributeNames.hasMoreElements()) { String name = (String) attributeNames.nextElement(); attributes.put(name, initialRequest.getAttribute(name)); }/* ww w. ja v a 2 s. c o m*/ } realPath = initialRequest.getRealPath(""); requestDispatcher = initialRequest.getRequestDispatcher(initialRequest.getServletPath()); }
From source file:net.maritimecloud.identityregistry.controllers.OrganizationController.java
/** * Revokes certificate for the user identified by the given ID * * @return a reply.../* w w w.jav a 2 s . co m*/ * @throws McBasicRestException */ @RequestMapping(value = "/api/org/{orgMrn}/certificate/{certId}/revoke", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @PreAuthorize("hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)") public ResponseEntity<?> revokeOrgCert(HttpServletRequest request, @PathVariable String orgMrn, @PathVariable Long certId, @Valid @RequestBody CertificateRevocation input) throws McBasicRestException { Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { Certificate cert = this.certificateService.getCertificateById(certId); Organization certOrg = cert.getOrganization(); if (certOrg != null && certOrg.getId().compareTo(org.getId()) == 0) { this.revokeCertificate(certId, input, request); return new ResponseEntity<>(HttpStatus.OK); } throw new McBasicRestException(HttpStatus.FORBIDDEN, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }
From source file:org.wrml.server.WrmlServlet.java
/** * Get the requested resource's id from the the {@link HttpServletRequest}. * * @param request The {@link HttpServletRequest} that holds the {@link URI}. * @return The requested resource's id from the the {@link HttpServletRequest}. * @throws URISyntaxException Thrown if there is a syntax problem when constructing the {@link URI}. *//*from w w w. j a va 2 s . c o m*/ URI getRequestUri(final HttpServletRequest request) throws URISyntaxException { // Due to the quirky nature of a servlet container, we're after the entire path. // This seems to work with servlet 3.0 and Tomcat 7.X String path = request.getServletPath(); String extra = request.getPathInfo(); if (path != null && extra != null) { path += request.getPathInfo(); } else if (path == null) { path = extra; } if (path.endsWith("/")) { path = path.substring(0, path.length() - 1); } final String host = StringUtils.defaultIfEmpty(request.getHeader(WRML_HOST_HEADER_NAME), request.getRemoteHost()); final String portString = StringUtils.defaultIfEmpty(request.getHeader(WRML_PORT_HEADER_NAME), Integer.toString(request.getRemotePort())); final String scheme = StringUtils.defaultIfEmpty(request.getHeader(WRML_SCHEME_HEADER_NAME), request.getScheme()); int port = -1; port = Integer.parseInt(portString); if (port == 80) { port = -1; } final URI requestUri = new URI(scheme, null, host, port, path, null, null); LOGGER.debug("Determined request URI: {}", requestUri); return requestUri; }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
private String getProxyURL(HttpServletRequest httpServletRequest) { // Set the protocol to HTTP String protocol = (httpServletRequest.isSecure()) ? "https://" : "http://"; String stringProxyURL = protocol + this.getProxyHostAndPort(); // simply use whatever servlet path that was part of the request as opposed to getting a preset/configurable proxy path if (!removePrefix) { stringProxyURL += httpServletRequest.getServletPath(); }/*from ww w .j a v a2 s. c o m*/ stringProxyURL += "/"; // Handle the path given to the servlet String pathInfo = httpServletRequest.getPathInfo(); if (pathInfo != null && pathInfo.startsWith("/")) { if (stringProxyURL != null && stringProxyURL.endsWith("/")) { // avoid double '/' stringProxyURL += pathInfo.substring(1); } } else { stringProxyURL += httpServletRequest.getPathInfo(); } // Handle the query string if (httpServletRequest.getQueryString() != null) { stringProxyURL += "?" + httpServletRequest.getQueryString(); } return stringProxyURL; }
From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java
/** {@inheritDoc} */ public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if (log.isDebugEnabled()) { // handle request HttpServletRequest request = (HttpServletRequest) req; log.debug("Entered doFilter() ==================================="); log.debug("AuthType: " + request.getAuthType()); log.debug("Method: " + request.getMethod()); log.debug("PathInfo: " + request.getPathInfo()); log.debug("Translated path: " + request.getPathTranslated()); log.debug("ContextPath: " + request.getContextPath()); log.debug("Query String: " + request.getQueryString()); log.debug("Remote User: " + request.getRemoteUser()); log.debug("Remote Host: " + request.getRemoteHost()); log.debug("Remote Addr: " + request.getRemoteAddr()); log.debug("SessionId: " + request.getRequestedSessionId()); log.debug("uri: " + request.getRequestURI()); log.debug("url: " + request.getRequestURL().toString()); log.debug("Servlet path: " + request.getServletPath()); log.debug("Server Name: " + request.getServerName()); log.debug("Server Port: " + request.getServerPort()); log.debug("RESPONSE encoding: " + resp.getCharacterEncoding()); log.debug("REQUEST encoding: " + request.getCharacterEncoding()); log.debug("JVM encoding: " + System.getProperty("file.encoding")); logSession(request.getSession()); logHeaders(request);/*from w ww .j a v a 2 s .c o m*/ logCookies(request.getCookies()); logParameters(request); logAttributes(request); log.debug("Calling chain.doFilter() -----------------------------"); } chain.doFilter(req, resp); if (log.isDebugEnabled()) { log.debug("Returned from chain.doFilter() -----------------------"); log.debug("Handle Response, not much to print"); log.debug("Response: " + resp.toString()); log.debug("Leaving doFilter() ==================================="); } }
From source file:org.slc.sli.dashboard.security.SLIAuthenticationEntryPoint.java
private void completeAuthentication(HttpServletRequest request, HttpServletResponse response, HttpSession session, Object token, boolean cookieFound) throws ServletException, IOException { // Complete Spring security integration SLIPrincipal principal = completeSpringAuthentication((String) token); LOG.info(LOG_MESSAGE_AUTH_COMPLETED, new Object[] { principal.getName(), request.getRemoteAddr() }); // Save the cookie to support sessions across multiple dashboard servers saveCookieWithToken(request, response, (String) token); // AJAX calls OR cookie sessions should not redirect if (isAjaxRequest(request) || cookieFound) { RequestDispatcher dispatcher = request.getRequestDispatcher(request.getServletPath()); dispatcher.forward(request, response); } else {/*from ww w . j ava2s . c o m*/ LOG.info(LOG_MESSAGE_AUTH_REDIRECTING, new Object[] { principal.getName(), request.getRemoteAddr() }); response.sendRedirect(request.getRequestURI()); } }
From source file:net.maritimecloud.identityregistry.controllers.ServiceController.java
/** * Creates a new Service/* ww w .ja v a2s . c o m*/ * * @return a reply... * @throws McBasicRestException */ @RequestMapping(value = "/api/org/{orgMrn}/service", method = RequestMethod.POST, produces = "application/json;charset=UTF-8") @ResponseBody @PreAuthorize("hasRole('SERVICE_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)") public ResponseEntity<Service> createService(HttpServletRequest request, @PathVariable String orgMrn, @Valid @RequestBody Service input, BindingResult bindingResult) throws McBasicRestException { ValidateUtil.hasErrors(bindingResult, request); Organization org = this.organizationService.getOrganizationByMrn(orgMrn); if (org != null) { // Check that the entity being created belongs to the organization if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn) .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS, request.getServletPath()); } input.setIdOrganization(org.getId()); // Setup a keycloak client for the service if needed if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) { // Check if the redirect uri is set if access type is "bearer-only" if (!"bearer-only".equals(input.getOidcAccessType()) && (input.getOidcRedirectUri() == null || input.getOidcRedirectUri().trim().isEmpty())) { throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.OIDC_MISSING_REDIRECT_URL, request.getServletPath()); } keycloakAU.init(KeycloakAdminUtil.BROKER_INSTANCE); input.setOidcClientId(input.getMrn()); try { String clientSecret = keycloakAU.createClient(input.getMrn(), input.getOidcAccessType(), input.getOidcRedirectUri()); if ("confidential".equals(input.getOidcAccessType())) { input.setOidcClientSecret(clientSecret); } else { input.setOidcClientSecret(null); } } catch (IOException e) { throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR, MCIdRegConstants.ERROR_CREATING_KC_CLIENT, request.getServletPath()); } catch (DuplicatedKeycloakEntry dke) { throw new McBasicRestException(HttpStatus.CONFLICT, dke.getErrorMessage(), request.getServletPath()); } } else { input.setOidcAccessType(null); input.setOidcClientId(null); input.setOidcClientSecret(null); input.setOidcRedirectUri(null); } try { Service newService = this.entityService.save(input); return new ResponseEntity<>(newService, HttpStatus.OK); } catch (DataIntegrityViolationException e) { // If save to DB failed, remove the client from keycloak if it was created. if (input.getOidcAccessType() != null && !input.getOidcAccessType().trim().isEmpty()) { keycloakAU.deleteClient(input.getMrn()); } throw new McBasicRestException(HttpStatus.CONFLICT, e.getRootCause().getMessage(), request.getServletPath()); } } else { throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND, request.getServletPath()); } }