Example usage for javax.servlet.http HttpServletRequest getServletPath

List of usage examples for javax.servlet.http HttpServletRequest getServletPath

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getServletPath.

Prototype

public String getServletPath();

Source Link

Document

Returns the part of this request's URL that calls the servlet.

Usage

From source file:net.maritimecloud.identityregistry.controllers.UserController.java

/**
 * Updates a User//from   ww w . ja v  a2  s .co  m
 * 
 * @return a reply...
 * @throws McBasicRestException 
 */
@RequestMapping(value = "/api/org/{orgMrn}/user/{userMrn}", method = RequestMethod.PUT)
@ResponseBody
@PreAuthorize("hasRole('USER_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn)")
public ResponseEntity<?> updateUser(HttpServletRequest request, @PathVariable String orgMrn,
        @PathVariable String userMrn, @Valid @RequestBody User input, BindingResult bindingResult)
        throws McBasicRestException {
    ValidateUtil.hasErrors(bindingResult, request);
    if (!userMrn.equals(input.getMrn())) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                request.getServletPath());
    }
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being updated belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(input.getMrn()))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        User user = this.entityService.getByMrn(userMrn);
        if (user == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.USER_NOT_FOUND,
                    request.getServletPath());
        }
        if (!user.getMrn().equals(input.getMrn()) || user.getIdOrganization().compareTo(org.getId()) != 0) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.URL_DATA_MISMATCH,
                    request.getServletPath());
        }
        // Update user in keycloak if created there.
        if ("test-idp".equals(org.getFederationType()) && (org.getIdentityProviderAttributes() == null
                || org.getIdentityProviderAttributes().isEmpty())) {
            keycloakAU.init(KeycloakAdminUtil.USER_INSTANCE);
            try {
                keycloakAU.updateUser(input.getMrn(), input.getFirstName(), input.getLastName(),
                        input.getEmail(), input.getPermissions(), true);
            } catch (IOException e) {
                throw new McBasicRestException(HttpStatus.INTERNAL_SERVER_ERROR,
                        MCIdRegConstants.ERROR_UPDATING_KC_USER, request.getServletPath());
            }
        }
        input.selectiveCopyTo(user);
        this.entityService.save(user);
        return new ResponseEntity<>(HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:net.maritimecloud.identityregistry.controllers.EntityController.java

/**
 * Returns new certificate for the entity identified by the given ID
 *
 * @return a reply...//from   w  w w.  j a va  2  s.  c o  m
 * @throws McBasicRestException
 */
protected ResponseEntity<PemCertificate> newEntityCert(HttpServletRequest request, String orgMrn,
        String entityMrn, String type) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        // Check that the entity being queried belongs to the organization
        if (!MrnUtil.getOrgShortNameFromOrgMrn(orgMrn)
                .equals(MrnUtil.getOrgShortNameFromEntityMrn(entityMrn))) {
            throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.MISSING_RIGHTS,
                    request.getServletPath());
        }
        T entity = this.entityService.getByMrn(entityMrn);
        if (entity == null) {
            throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ENTITY_NOT_FOUND,
                    request.getServletPath());
        }
        if (entity.getIdOrganization().compareTo(org.getId()) == 0) {
            PemCertificate ret = this.issueCertificate(entity, org, type, request);
            return new ResponseEntity<>(ret, 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.semispace.semimeter.controller.CounterController.java

@RequestMapping("/**/json.html")
public String showData(Model model, HttpServletRequest request, @RequestParam String resolution) {
    /*log.debug("--------------- *-PathTranslated: "+request.getPathTranslated()+
        "\nContextPath: "+request.getContextPath()+
        "\nPathInfo: "+request.getPathInfo()+
        "\nRequestURI: "+request.getRequestURI()+
        "\nServletPath(): "+request.getServletPath()+
        "\nRequestURL(): "+request.getRequestURL()
    );*/// w ww  .  jav a2s .c  o  m
    //Seems like ServletPath() is the way to go.
    // http://localhost:9013/semimeter/semimeter/a/json.html
    // ServletPath(): /semimeter/a/json.html
    if (!isSane(request.getServletPath())) {
        throw new RuntimeException("Disallowed character found in query.");
    }

    long endAt = semimeterService.getCurrentEndTime();
    long startAt = semimeterService.calculateStartTimeFromResolution(resolution, endAt);

    JsonResults[] jrs = semimeterService.getJsonResults(trimPath("/json.html", request.getServletPath()), endAt,
            startAt, resolution);
    String str = jsonService.createJsonStringFromArray(jrs);

    model.addAttribute("numberOfItems", str);

    return "showcount";
}

From source file:de.zib.vold.userInterface.RESTController.java

/**
 * Handles Delete requests.// w w w.j  a  v  a2 s.  c  o  m
 *
 * This method is used by clients to delete keys.
 *
 * @param clientIpAddress The ip of the sending client, it's extracted from the request itself.
 * @param args The URL arguments of the request.
 * @param request Request informations
 * @return A map of keys with its lifetime, whereas the livetime is zero if an error for that key occured.
 */
@RequestMapping(method = RequestMethod.DELETE)
public ResponseEntity<Map<String, String>> delete(@ModelAttribute("clientIpAddress") String clientIpAddress,
        @RequestParam MultiValueMap<String, String> args, HttpServletRequest request) {

    // guard
    {
        logger.debug("DELETE: " + args.toString());

        checkState();
    }

    Map<String, String> invalidKeys = new HashMap<String, String>();

    // get actual scope
    String scope;
    {
        scope = request.getRequestURI();
        String removepath = removePrefix + request.getContextPath() + request.getServletPath();

        scope = scope.substring(removepath.length(), scope.length());
    }

    // process each key
    {
        for (Map.Entry<String, List<String>> entry : args.entrySet()) {
            URIKey urikey;
            String source;
            Key k;

            // build key
            {
                urikey = URIKey.fromURIString(entry.getKey(), enc);

                File path_correction = new File(scope + "/" + urikey.getKey().get_scope());

                k = new Key(path_correction.getPath(), urikey.getKey().get_type(),
                        urikey.getKey().get_keyname());

                if (null == urikey.getSource()) {
                    source = clientIpAddress;
                } else {
                    source = urikey.getSource();
                }
            }

            // handle write request for that key
            {
                try {
                    frontend.delete(source, k);
                } catch (VoldException e) {
                    logger.error("Could not handle write request for key " + entry.getKey() + ". ", e);
                    invalidKeys.put(entry.getKey(), "ERROR: " + e.getMessage());
                }
            }
        }
    }

    return new ResponseEntity<Map<String, String>>(invalidKeys, HttpStatus.OK);
}

From source file:co.id.app.sys.util.StringUtils.java

/**
 * Return the page resource path from the request. For example:
 * <pre class="codeHtml">/*from w w  w  .  java 2 s . c  o  m*/
 * <span class="blue">http://www.mycorp.com/banking/secure/login.htm</span>  ->  <span class="red">/secure/login.htm</span> </pre>
 *
 * @param request the page servlet request
 * @return the page resource path from the request
 */
public static String getResourcePath(HttpServletRequest request) {
    // Adapted from VelocityViewServlet.handleRequest() method:

    // If we get here from RequestDispatcher.include(), getServletPath()
    // will return the original (wrong) URI requested.  The following
    // special attribute holds the correct path.  See section 8.3 of the
    // Servlet 2.3 specification.

    String path = (String) request.getAttribute("javax.servlet.include.servlet_path");

    // Also take into account the PathInfo stated on
    // SRV.4.4 Request Path Elements.
    String info = (String) request.getAttribute("javax.servlet.include.path_info");

    if (path == null) {
        path = request.getServletPath();
        info = request.getPathInfo();
    }

    if (info != null) {
        path += info;
    }

    return path;
}

From source file:br.com.sg.security.SgLoginUrlAuthenticationEntryPoint.java

/**
 * Builds a URL to redirect the supplied request to HTTPS. Used to redirect
 * the current request to HTTPS, before doing a forward to the login page.
 *///from   w  w w.  j  a  va2  s .  c o  m
protected String buildHttpsRedirectUrlForRequest(HttpServletRequest request)
        throws IOException, ServletException {

    Integer serverPort = portResolver.getServerPort(request);
    Integer httpsPort = portMapper.lookupHttpsPort(new Integer(serverPort));

    if (httpsPort != null) {
        RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder();
        urlBuilder.setScheme("https");
        urlBuilder.setServerName(request.getServerName());
        urlBuilder.setPort(httpsPort.intValue());
        urlBuilder.setContextPath(request.getContextPath());
        urlBuilder.setServletPath(request.getServletPath());
        urlBuilder.setPathInfo(request.getPathInfo());
        urlBuilder.setQuery(request.getQueryString());

        return urlBuilder.getUrl();
    }

    // Fall through to server-side forward with warning message
    logger.warn("Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort);

    return null;
}

From source file:de.zib.vold.userInterface.RESTController.java

/**
 * Handles Get requests.//from w w w  . j ava  2s.  c  o  m
 *
 * This method is used by clients to lookup some keys.
 *
 * @param keys The URL arguments of the request.
 * @param request Request informations
 * @return A map of found keys with its associated values.
 */
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<Map<Key, Set<String>>> lookup(@RequestParam Map<String, String> keys,
        HttpServletRequest request) {
    // guard
    {
        logger.debug("GET: " + keys.toString());

        checkState();
    }

    Map<Key, Set<String>> merged_result = new HashMap<Key, Set<String>>();

    // get actual scope
    String scope;
    {
        scope = request.getRequestURI();
        String removepath = removePrefix + request.getContextPath() + request.getServletPath();

        scope = scope.substring(removepath.length(), scope.length());
    }

    // process each key
    for (Map.Entry<String, String> entry : keys.entrySet()) {
        URIKey urikey;
        Key k;

        // build key
        {
            urikey = URIKey.fromURIString(entry.getKey(), enc);

            File path_correction = new File(scope + "/" + urikey.getKey().get_scope());

            k = new Key(path_correction.getPath(), urikey.getKey().get_type(), urikey.getKey().get_keyname());
        }

        // lookup and remember result
        {
            Map<Key, Set<String>> _result;

            try {
                _result = frontend.lookup(k);
            } catch (VoldException e) {
                logger.error("Error on lookup for key " + k + " (" + entry.getKey() + "): ", e);
                continue;
                /*
                                Set< String > s = new HashSet< String >();
                                s.add( e.getMessage() );
                        
                                merged_result.clear();
                                merged_result.put( k, s );
                        
                                return new ResponseEntity< Map< Key, Set< String > > >(
                                                merged_result,
                                                HttpStatus.INTERNAL_SERVER_ERROR );
                */
            }

            // found something
            if (null != _result) {
                merged_result.putAll(_result);
            }
        }
    }

    return new ResponseEntity<Map<Key, Set<String>>>(merged_result, HttpStatus.OK);
}

From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java

protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    LOGGER.debug(">>>>>>>>>>>> start request");

    // read destination and relative service path from URL
    String queryString = request.getQueryString();
    String destinationName = getDestinationFromUrl(request.getServletPath());
    String pathInfo = null;//w w  w .j av a2  s.co  m

    int contextPathLength = request.getContextPath().length();
    int servletPathLength = request.getServletPath().length();

    if (request.getRequestURI().endsWith(destinationName)) {
        pathInfo = "";
    } else {
        pathInfo = request.getRequestURI().substring(servletPathLength + contextPathLength);

    }
    String urlToService = getRelativePathFromUrl(pathInfo, queryString);

    // get the http client for the destination
    HttpDestination dest = getDestination(destinationName);
    HttpClient httpClient = null;
    try {
        httpClient = dest.createHttpClient();

        // create request to targeted backend service
        HttpRequestBase backendRequest = getBackendRequest(request, urlToService);

        // execute the backend request
        HttpResponse backendResponse = httpClient.execute(backendRequest);

        String rewriteUrl = getDestinationUrl(dest);
        String proxyUrl = getProxyUrl(request);

        // process response from backend request and pipe it to origin response of client
        processBackendResponse(request, response, backendResponse, proxyUrl, rewriteUrl);
    } catch (DestinationException e) {
        throw new ServletException(e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }

        LOGGER.debug(">>>>>>>>>>>> end request");
    }
}

From source file:nc.noumea.mairie.organigramme.core.authentification.AuthentificationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    /* Cast des objets request et response */
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    HttpSession hSess = ((HttpServletRequest) request).getSession();

    // Hack pour pouvoir rcuprer les images sur la page de connexion
    if (request.getRequestURI().contains("imgs")) {
        chain.doFilter(request, response);
        return;/*from   ww w. j  a  va2  s . c  o m*/
    }

    // on laisse passer pour le rproxy et ainsi permettre de deployer l
    // application sur le 2e noeud tomcat
    if (PAGES_STATIQUES.contains(request.getServletPath())) {
        chain.doFilter(request, response);
        return;
    }

    if (null != hSess.getAttribute("logout")) {
        if (!request.getRequestURI().contains("zkau") && !request.getRequestURI().contains("login.zul")
                && !request.getRequestURI().contains("css")) {

            // dans le cas ou la personne a clique sur ce deconnecte et ne
            // ferme pas le navigateur
            LOGGER.debug("User disconnect");
            hSess.setAttribute("logout", "logout");
            request.getRequestDispatcher("login.zul").forward(request, response);
            return;
        }
        chain.doFilter(request, response);
        return;
    }

    if (null != hSess.getAttribute("currentUser")) {
        chain.doFilter(request, response);
        return;
    }

    if ((null == request.getHeader("x-krb_remote_user")
            || "".equals(request.getHeader("x-krb_remote_user").trim()))) {
        LOGGER.debug("x-krb_remote_user is NULL");
        // hSess.invalidate();
        // request.logout();
        // response.sendError(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED,
        // "You are logged out.");
        // #15803
        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    String remoteUser = request.getHeader("x-krb_remote_user");

    remoteUser = convertRemoteUser(remoteUser);

    LightUserDto userDto = radiWSConsumer.getAgentCompteADByLogin(remoteUser);
    if (null == userDto) {
        LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser);
        // request.logout();

        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    if (0 == userDto.getEmployeeNumber()) {
        LOGGER.debug("User not exist in Radi WS with RemoteUser : " + remoteUser);

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                "Vous n'tes pas un agent de la mairie, vous n'tes pas autoris  accder  cette application.");
        return;
    }

    ProfilAgentDto profilAgent = recupereProfilAgent(request, userDto.getEmployeeNumber());
    if (profilAgent == null) {
        return;
    }

    AccessRightOrganigrammeDto accessRightOrganigrammeDto = recupereAccessRightOrganigramme(request,
            userDto.getEmployeeNumber());
    if (accessRightOrganigrammeDto == null || accessRightOrganigrammeDto.isAucunRole()) {
        hSess.setAttribute("logout", "logout");
        request.getRequestDispatcher("login.zul").forward(request, response);
        return;
    }

    renseigneAccessRightOnUser(profilAgent, accessRightOrganigrammeDto);

    hSess.setAttribute("currentUser", profilAgent);
    LOGGER.debug("Authentification du user ok : " + remoteUser);
    LOGGER.debug("Droits du user ok : " + accessRightOrganigrammeDto);

    chain.doFilter(request, response);
}