Example usage for javax.servlet.http HttpServletRequest getContextPath

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

Introduction

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

Prototype

public String getContextPath();

Source Link

Document

Returns the portion of the request URI that indicates the context of the request.

Usage

From source file:org.brutusin.rpc.websocket.WebsocketFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (isDisabled || httpRequest.getRequestURI() == null
            || !(httpRequest.getRequestURI().substring(httpRequest.getContextPath().length())
                    .startsWith(RpcConfig.getInstance().getPath() + "/wskt"))) {
        chain.doFilter(request, response);
        return;/* w  ww  .  ja va  2s  . c  o  m*/
    }
    final Map<String, String[]> fakedParams = Collections.singletonMap("requestId",
            new String[] { String.valueOf(counter.getAndIncrement()) });
    HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public Map<String, String[]> getParameterMap() {
            return fakedParams;
        }
    };
    /*
     * current request is needed for getEndpointInstance(). In glassfish getEndpointInstance() is executed out this filter chain, 
     * but inside whole request-response cycle (controlled by the overall listener that sets and removes GlobalThreadLocal)
     */
    if (GlobalThreadLocal.get() == null) {
        throw new AssertionError();
    }
    Object securityContext;
    if (ClassUtils.isPresent("org.springframework.security.core.context.SecurityContextHolder",
            RpcWebInitializer.class.getClassLoader())) {
        securityContext = SecurityContextHolder.getContext();
    } else {
        securityContext = null;
    }
    GlobalThreadLocal.set(new GlobalThreadLocal(wrappedRequest, securityContext)); // override current request with the one with faked params and security context
    chain.doFilter(wrappedRequest, response);
}

From source file:be.fedict.eid.idp.protocol.saml2.artifact.AbstractSAML2ArtifactMetadataHttpServlet.java

@Override
public EntityDescriptor getEntityDescriptor(HttpServletRequest request,
        IdentityProviderConfiguration configuration) {

    String artifactResolutionLocation = "https://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + IdentityProviderProtocolService.WS_ENDPOINT_CONTEXT_PATH
            + "/saml2/artifact";
    LOG.debug("Artifact resolution location: " + artifactResolutionLocation);

    EntityDescriptor entityDescriptor = super.getEntityDescriptor(request, configuration);

    // add ArtifactResolutionService
    ArtifactResolutionService artifactResolutionService = Saml2Util
            .buildXMLObject(ArtifactResolutionService.class, ArtifactResolutionService.DEFAULT_ELEMENT_NAME);
    artifactResolutionService.setLocation(artifactResolutionLocation);
    artifactResolutionService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
    artifactResolutionService.setIndex(0);
    artifactResolutionService.setIsDefault(true);

    IDPSSODescriptor idpssoDescriptor = (IDPSSODescriptor) entityDescriptor.getRoleDescriptors().get(0);
    idpssoDescriptor.getArtifactResolutionServices().add(artifactResolutionService);

    return entityDescriptor;
}

From source file:controller.FAQManagerController.java

@RequestMapping(value = "/process")
public String processFAQ(HttpServletRequest req, @ModelAttribute(value = "FAQ") Faq f,
        @RequestParam(value = "action") String action, ModelMap mm) {
    try {//  w  ww  .  ja v a2 s.  c  o  m
        String contextPath = req.getContextPath();
        if (action.equalsIgnoreCase("update")) {
            mm.put("check", faqModel.addOrUpdate(f));
            mm.put("alert", "FAQ Updated");
        }
        if (action.equalsIgnoreCase("Add")) {
            f.setFaqId(0);
            mm.put("check", faqModel.addOrUpdate(f));
            mm.put("alert", "FAQ Added");
        }
        if (action.equalsIgnoreCase("delete")) {
            mm.put("check", faqModel.delete(f));
            mm.put("alert", "FAQ Deleted");
        }
        mm.put("link", contextPath + "/admin/FAQManager.html");
    } catch (Exception ex) {
        ex.printStackTrace();
        mm.put("err", ex.getMessage());
    }
    return "processFAQ";
}

From source file:com.google.code.lightssh.project.security.shiro.MySecondaryLicensePermissionsAuthorizationFilter.java

/**
 * ??/* w w w .ja  v a 2 s.  c  o m*/
 */
@Override
public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
        throws IOException {

    Subject subject = getSubject(request, response);
    String[] perms = (String[]) mappedValue;

    boolean isPermitted = true;
    String targetUrl = request.getParameter("targetUrl");
    if (targetUrl == null) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        targetUrl = httpServletRequest.getRequestURI().substring(httpServletRequest.getContextPath().length());
    }
    AuthorizedResource authResource = authorizedResourceManager.getWithRegexp("/" + targetUrl);
    if (authResource != null) {
        isPermitted = checkTempAuth((HttpServletRequest) request, perms);
    } else {
        if (perms != null && perms.length > 0) {
            //               boolean tempAuthed = tempAuthService.authorize(perms,request);
            if (perms.length == 1) {
                if (!subject.isPermitted(perms[0])) {
                    isPermitted = false;
                }
            } else {
                if (!subject.isPermittedAll(perms)) {
                    isPermitted = false;
                }
            }
        }
    }
    return isPermitted;
}

From source file:com.cpjit.swagger4j.DefaultConfigResolver.java

private Properties loadConfig(HttpServletRequest request) throws IOException {
    Properties props = new Properties();
    InputStream is = ResourceUtil.getResourceAsStream(configFile);
    props.load(is);//from   w w w. j a va 2  s. co  m
    String path = request.getContextPath();
    String host = request.getServerName() + ":" + request.getServerPort() + path;
    props.setProperty("apiHost", host);
    String apiFile = props.getProperty("apiFile");
    if (StringUtils.isBlank(apiFile)) {
        apiFile = Constants.DEFAULT_API_FILE;
    }
    String apiFilePath = request.getServletContext().getRealPath(apiFile);
    props.setProperty("apiFile", apiFilePath);
    String suffix = props.getProperty("suffix");
    if (StringUtils.isBlank(suffix)) {
        suffix = "";
    }
    props.put("suffix", suffix);
    return props;
}

From source file:com.galeoconsulting.leonardinius.servlet.ScriptRunnerSessionServlet.java

private String getTemplateKey(HttpServletRequest request) throws URISyntaxException {
    String leadingTrimPath = new StringBuilder().append(request.getContextPath())
            .append(request.getServletPath()).toString();
    return new URI(leadingTrimPath).relativize(URI.create(new URI(request.getRequestURI()).getPath()))
            .toASCIIString();//from ww w  . j  a  v  a  2s  . co  m
}

From source file:com.companyname.services.OnLoginSuccessHandler.java

/**
 * protected void setRedirectPerUserPreference(HttpServletRequest request ,
 * Authentication authentication) { Assert.notNull(request, "Request passed
 * as null into setRedirectPerUserPreference(...)");
 *
 * logger.info("Getting the preferred app ") ;      *
 * // get username String userName = (authentication.getPrincipal() == null)
 * ? "NONE_PROVIDED" : authentication.getName();      *
 * String userRefPage = userPrefs.getPreferredURL(request.getServerName(),
 * userName);/*from ww w.j a  v a 2 s  . c  o  m*/
 *
 * logger.info("User will be redirected to a prefered application at " +
 * userRefPage);      *
 * if (StringUtils.hasText(userRefPage)) { logger.info("User should be
 * redirected to " + userRefPage); this.setAlwaysUseDefaultTargetUrl(true);
 * this.setDefaultTargetUrl(userRefPage); } }
* *
 */
public String getCookiePath(HttpServletRequest request) {
    if (cookiePath == null) {
        String contextPath = request.getContextPath();
        return contextPath.length() > 0 ? contextPath : "/";
    } else {
        return cookiePath;
    }
}

From source file:org.n52.tamis.rest.forward.processes.jobs.StatusRequestForwarder.java

private String constructTamisBaseUrl(HttpServletRequest request) {
    String target_baseUrl = request.getScheme() + "://" + request.getServerName() + ":"
            + request.getServerPort() + request.getContextPath();
    return target_baseUrl;
}

From source file:org.reallysqs.server.views.CreateQueueResponseView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    Queue queue = (Queue) model.get("queue");
    String location = "http://" + request.getLocalName() + ":" + request.getLocalPort()
            + request.getContextPath() + request.getServletPath() + "/queues/" + queue.getName();

    response.addHeader("Location", location);
}

From source file:org.xine.marketplace.frontend.views.security.JsfRedirectStrategy.java

/**
 * Redirects the response to the supplied URL.
 * <p>//from   w  w  w  .ja  va  2s .c  om
 * If <tt>contextRelative</tt> is set, the redirect value will be the value after the request
 * context path. Note that this will result in the loss of protocol information (HTTP or
 * HTTPS), so will cause problems if a redirect is being performed to change to HTTPS, for
 * example.
 */
@Override
public void sendRedirect(final HttpServletRequest request, final HttpServletResponse response, final String url)
        throws IOException {
    String redirectUrl = calculateRedirectUrl(request.getContextPath(), url);
    redirectUrl = response.encodeRedirectURL(redirectUrl);

    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Redirecting to '" + redirectUrl + "'");
    }

    // we should redirect using ajax response if the case warrants
    final boolean ajaxRedirect = request.getHeader("faces-request") != null
            && request.getHeader("faces-request").toLowerCase().indexOf("ajax") > -1;

    if (ajaxRedirect) {
        // javax.faces.context.FacesContext ctxt =
        // javax.faces.context.FacesContext.getCurrentInstance();
        // ctxt.getExternalContext().redirect(redirectUrl);

        final String ajaxRedirectXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<partial-response><redirect url=\"" + redirectUrl + "\"></redirect></partial-response>";
        response.setContentType("text/xml");
        response.getWriter().write(ajaxRedirectXml);
    } else {
        response.sendRedirect(redirectUrl);
    }

}