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:com.jsmartframework.web.manager.FilterControl.java

private Script getFunctionScripts(HttpServletRequest httpRequest) {
    String requestPath = httpRequest.getServletPath();
    List<AnnotatedFunction> annotatedFunctions = HANDLER.getAnnotatedFunctions(requestPath);

    for (AnnotatedFunction annotatedFunction : annotatedFunctions) {
        try {//  w  ww .j a  v  a 2s. c o  m
            new FunctionTagHandler().executeTag(httpRequest, annotatedFunction);
        } catch (JspException | IOException e) {
            LOGGER.log(Level.SEVERE, "Annotated Function could not be generated for path [" + requestPath
                    + "]: " + e.getMessage());
        }
    }
    return (Script) httpRequest.getAttribute(REQUEST_PAGE_SCRIPT_ATTR);
}

From source file:eionet.web.action.AbstractActionBean.java

/**
 * Returns the real request path.//from   w  w  w  .  ja  v a  2 s.  c  om
 *
 * @param request http request
 * @return full urlbinding without decoding
 */
protected String getRequestedPath(HttpServletRequest request) {
    String servletPath, pathInfo;

    // Check to see if the request is processing an include, and pull the path
    // information from the appropriate source.
    servletPath = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH);
    if (servletPath != null) {
        pathInfo = (String) request.getAttribute(StripesConstants.REQ_ATTR_INCLUDE_PATH_INFO);
    } else {
        servletPath = request.getServletPath();
        pathInfo = request.getPathInfo();
    }

    String finalPath = (servletPath != null ? servletPath : "") + (pathInfo != null ? pathInfo : "");
    return finalPath;
}

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

@RequestMapping(value = "/api/org/{orgMrn}/role", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody// www . j a va 2 s .  c om
@PreAuthorize("(hasRole('ORG_ADMIN') and @accessControlUtil.hasAccessToOrg(#orgMrn) and #input.roleName != 'ROLE_SITE_ADMIN') or hasRole('SITE_ADMIN')")
public ResponseEntity<Role> createRole(HttpServletRequest request, @PathVariable String orgMrn,
        @Valid @RequestBody Role input, BindingResult bindingResult) throws McBasicRestException {
    Organization org = this.organizationService.getOrganizationByMrn(orgMrn);
    if (org != null) {
        input.setIdOrganization(org.getId());
        Role newRole = this.roleService.save(input);
        return new ResponseEntity<>(newRole, HttpStatus.OK);
    } else {
        throw new McBasicRestException(HttpStatus.NOT_FOUND, MCIdRegConstants.ORG_NOT_FOUND,
                request.getServletPath());
    }
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.java

/** Copy cookie from the proxy to the servlet client.
 *  Replaces cookie path to local path and renames cookie to avoid collisions.
 */// w  w  w .  j  a va2  s . c o  m
protected void copyProxyCookie(HttpServletRequest servletRequest, HttpServletResponse servletResponse,
        Header header) {
    List<HttpCookie> cookies = HttpCookie.parse(header.getValue());
    String path = servletRequest.getContextPath(); // path starts with / or is empty string
    path += servletRequest.getServletPath(); // servlet path starts with / or is empty string

    for (HttpCookie cookie : cookies) {
        //set cookie name prefixed w/ a proxy value so it won't collide w/ other cookies
        String proxyCookieName = getCookieNamePrefix() + cookie.getName();
        Cookie servletCookie = new Cookie(proxyCookieName, cookie.getValue());
        servletCookie.setComment(cookie.getComment());
        servletCookie.setMaxAge((int) cookie.getMaxAge());
        servletCookie.setPath(path); //set to the path of the proxy servlet
        // don't set cookie domain
        servletCookie.setSecure(cookie.getSecure());
        servletCookie.setVersion(cookie.getVersion());
        servletResponse.addCookie(servletCookie);
    }
}

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

protected PemCertificate issueCertificate(CertificateModel certOwner, Organization org, String type,
        HttpServletRequest request) throws McBasicRestException {
    // Generate keypair for user
    KeyPair userKeyPair = CertificateUtil.generateKeyPair();
    // Find special MC attributes to put in the certificate
    HashMap<String, String> attrs = getAttr(certOwner);

    String o = org.getMrn();// w w w  .  j a  v a2s.  c o m
    String name = getName(certOwner);
    String email = getEmail(certOwner);
    String uid = getUid(certOwner);
    if (uid == null || uid.trim().isEmpty()) {
        throw new McBasicRestException(HttpStatus.BAD_REQUEST, MCIdRegConstants.ENTITY_ORG_ID_MISSING,
                request.getServletPath());
    }
    BigInteger serialNumber = certUtil.generateSerialNumber();
    X509Certificate userCert = certUtil.generateCertForEntity(serialNumber, org.getCountry(), o, type, name,
            email, uid, userKeyPair.getPublic(), attrs);
    String pemCertificate;
    try {
        pemCertificate = CertificateUtil.getPemFromEncoded("CERTIFICATE", userCert.getEncoded()).replace("\n",
                "\\n");
    } catch (CertificateEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String pemPublicKey = CertificateUtil.getPemFromEncoded("PUBLIC KEY", userKeyPair.getPublic().getEncoded())
            .replace("\n", "\\n");
    String pemPrivateKey = CertificateUtil
            .getPemFromEncoded("PRIVATE KEY", userKeyPair.getPrivate().getEncoded()).replace("\n", "\\n");
    PemCertificate ret = new PemCertificate(pemPrivateKey, pemPublicKey, pemCertificate);

    // Create the certificate
    Certificate newMCCert = new Certificate();
    certOwner.assignToCert(newMCCert);
    newMCCert.setCertificate(pemCertificate);
    newMCCert.setSerialNumber(serialNumber);
    // The dates we extract from the cert is in localtime, so they are converted to UTC before saving into the DB
    Calendar cal = Calendar.getInstance();
    long offset = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET);
    newMCCert.setStart(new Date(userCert.getNotBefore().getTime() - offset));
    newMCCert.setEnd(new Date(userCert.getNotAfter().getTime() - offset));
    this.certificateService.saveCertificate(newMCCert);
    return ret;
}

From source file:com.frameworkset.platform.cms.driver.url.impl.CMSURLParserImpl.java

/**
 * Parse a servlet request to a portal URL.
 * @param request  the servlet request to parse.
 * @return the portal URL./*from  w w  w.j  a v a2  s.  c  om*/
 */
public CMSURL parse(HttpServletRequest request) {

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing URL: " + request.getRequestURI());
    }

    String protocol = request.isSecure() ? "https://" : "http://";
    String server = request.getServerName();
    int port = request.getServerPort();
    String contextPath = request.getContextPath();
    String servletName = request.getServletPath();

    // Construct portal URL using info retrieved from servlet request.
    CMSURL portalURL = null;
    if ((request.isSecure() && port != 443) || (!request.isSecure() && port != 80)) {
        portalURL = new CMSURLImpl(protocol, server, port, contextPath, servletName);
    } else {
        portalURL = new CMSURLImpl(protocol, server, contextPath, servletName);
    }

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        return portalURL;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Parsing request pathInfo: " + pathInfo);
    }
    StringBuffer renderPath = new StringBuffer();
    StringTokenizer st = new StringTokenizer(pathInfo, "/", false);
    while (st.hasMoreTokens()) {

        String token = st.nextToken();

        // Part of the render path: append to renderPath.
        if (!token.startsWith(PREFIX)) {
            //              renderPath.append(token);
            //Fix for PLUTO-243
            renderPath.append('/').append(token);
        }
        // Action window definition: portalURL.setActionWindow().
        else if (token.startsWith(PREFIX + ACTION)) {
            portalURL.setActionWindow(decodeControlParameter(token)[0]);
        }
        // Window state definition: portalURL.setWindowState().
        else if (token.startsWith(PREFIX + WINDOW_STATE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setWindowState(decoded[0], new WindowState(decoded[1]));
        }
        // Portlet mode definition: portalURL.setPortletMode().
        else if (token.startsWith(PREFIX + PORTLET_MODE)) {
            String[] decoded = decodeControlParameter(token);
            //              portalURL.setPortletMode(decoded[0], new PortletMode(decoded[1]));
        }
        // Portal URL parameter: portalURL.addParameter().
        else {
            String value = null;
            if (st.hasMoreTokens()) {
                value = st.nextToken();
            }
            portalURL.addParameter(decodeParameter(token, value));
        }
    }
    if (renderPath.length() > 0) {
        portalURL.setRenderPath(renderPath.toString());
    }

    // Return the portal URL.
    return portalURL;
}

From source file:com.nirima.jenkins.webdav.impl.methods.MethodBase.java

public void init(HttpServletRequest request, HttpServletResponse response, IDavContext ctx, IDavRepo repo,
        String root) {/*from   w  w  w.j a va2  s  . c  o  m*/
    m_request = request;
    m_response = response;
    m_ctx = ctx;
    m_repo = repo;

    // TODO : what if it is https
    m_baseUrl = "http://" + request.getServerName();
    if (request.getServerPort() != 80)
        m_baseUrl += ":" + request.getServerPort();

    m_baseUrl += request.getContextPath() + request.getServletPath();

    // Path is the path into the repo we have requested

    // Root will be something like /config, so add to the base url
    m_baseUrl += root;

    // PathInfo will also be /config/woo, but we ignore the 1st part

    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = request.getServletPath();
    }

    m_path = request.getContextPath() + pathInfo;
    if (m_path == null) {
        m_path = "/";
    } else {
        m_path = m_path.substring(root.length());
    }

    s_logger.info(request.getMethod() + " " + m_baseUrl + " Called with path " + m_path);
}

From source file:edu.stanford.muse.webapp.JSPHelper.java

/** also sets current thread name to the path of the request */
private static String getRequestDescription(HttpServletRequest request, boolean includingParams) {
    HttpSession session = request.getSession();
    String page = request.getServletPath();
    Thread.currentThread().setName(page);
    String userKey = (String) session.getAttribute("userKey");
    StringBuilder sb = new StringBuilder(
            "Request[" + userKey + "@" + request.getRemoteAddr().toString() + "]: " + request.getRequestURL());
    // return here if params are not to be included
    if (!includingParams)
        return sb.toString();

    String link = request.getRequestURL() + "?";

    Map<String, String[]> rpMap = request.getParameterMap();
    if (rpMap.size() > 0)
        sb.append(" params: ");
    for (Object o : rpMap.keySet()) {
        String str1 = (String) o;
        sb.append(str1 + " -> ");
        if (str1.startsWith("password")) {
            sb.append("*** ");
            continue;
        }//from   w  ww.j  av  a  2s. com

        String[] vals = rpMap.get(str1);
        if (vals.length == 1)
            sb.append(Util.ellipsize(vals[0], 100));
        else {
            sb.append("{");
            for (String x : vals)
                sb.append(Util.ellipsize(x, 100) + ",");
            sb.append("}");
        }
        sb.append(" ");

        for (String val : vals)
            link += (str1 + "=" + vals[0] + "&");
    }

    sb.append(" link: " + link);
    return sb.toString();
}

From source file:com.xpn.xwiki.web.ActionFilter.java

/**
 * Compose a new URL path based on the original request and the specified action. The result is relative to the
 * application context, so that it can be used with {@link HttpServletRequest#getRequestDispatcher(String)}. For
 * example, calling this method with a request for <tt>/xwiki/bin/edit/Some/Document</tt> and <tt>action_save</tt>,
 * the result is <tt>/bin/save/Some/Document</tt>.
 * /*from w ww. j a  va 2 s. co  m*/
 * @param request the original request
 * @param action the action parameter, starting with <tt>action_</tt>
 * @return The rebuilt URL path, with the specified action in place of the original Struts action. Note that unlike
 *         the HTTP path, this does not contain the application context part.
 */
private String getTargetURL(HttpServletRequest request, String action) {
    String newAction = PATH_SEPARATOR + action.substring(ACTION_PREFIX.length());

    // Extract the document name from the requested path. We don't use getPathInfo() since it is decoded
    // by the container, thus it will not work when XWiki uses a non-UTF-8 encoding.
    String path = request.getRequestURI();

    // First step, remove the context path, if any.
    path = XWiki.stripSegmentFromPath(path, request.getContextPath());

    // Second step, remove the servlet path, if any.
    String servletPath = request.getServletPath();
    path = XWiki.stripSegmentFromPath(path, servletPath);

    // Third step, remove the struts mapping. This step is mandatory, so this filter will fail if the
    // requested action was a hidden (default) 'view', like in '/bin/Main/'. This is OK, since forms
    // don't use 'view' as a target.
    int index = path.indexOf(PATH_SEPARATOR, 1);

    // We need to also get rid of the wiki name in case of a XEM in usepath mode
    if ("1".equals(XWikiConfigurationService.getProperty("xwiki.virtual.usepath", "0", this.servletContext))) {
        if (servletPath.equals(PATH_SEPARATOR + XWikiConfigurationService
                .getProperty("xwiki.virtual.usepath.servletpath", "wiki", this.servletContext))) {
            // Move the wiki name together with the servlet path
            servletPath += path.substring(0, index);
            index = path.indexOf(PATH_SEPARATOR, index + 1);
        }
    }

    String document = path.substring(index);

    // Compose the target URL starting with the servlet path.
    return servletPath + newAction + document;
}

From source file:com.bodybuilding.turbine.servlet.ClusterListServlet.java

/**
 * Returns Hystrix Dashboard URL//from   w w  w  . j  av a  2s . com
 * @param sc ServletContext
 * @param request HttpServletRequest for building full URL
 * @return
 */
private Optional<String> getDashboardUrl(ServletContext sc, HttpServletRequest request) {
    String dashboardUrl = DASHBOARD_URL.get();
    if (dashboardUrl == null) {
        dashboardUrl = sc.getInitParameter("hystrix.dashboard.url");
    }

    if (dashboardUrl == null) {
        dashboardUrl = "/monitor/monitor.html?stream=";
    }

    if (!dashboardUrl.startsWith("http://") && !dashboardUrl.startsWith("https://")) {
        if (!dashboardUrl.startsWith("/")) {
            dashboardUrl = "/" + dashboardUrl;
        }
        dashboardUrl = request.getRequestURL().toString().replaceFirst(Pattern.quote(request.getServletPath()),
                dashboardUrl);
    }
    return Optional.ofNullable(dashboardUrl);
}