Example usage for javax.servlet.http HttpServletRequest getPathInfo

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

Introduction

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

Prototype

public String getPathInfo();

Source Link

Document

Returns any extra path information associated with the URL the client sent when it made this request.

Usage

From source file:kornell.server.ProxyServlet.java

/** For a redirect response from the target server, this translates {@code theUrl} to redirect to
 * and translates it to one the original client can use. */
protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) {
    //TODO document example paths
    if (theUrl.startsWith(targetUri)) {
        String curUrl = servletRequest.getRequestURL().toString();//no query
        String pathInfo = servletRequest.getPathInfo();
        if (pathInfo != null) {
            assert curUrl.endsWith(pathInfo);
            curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off
        }// w  w  w . j  a  v a  2 s  .co m
        theUrl = curUrl + theUrl.substring(targetUri.length());
    }
    return theUrl;
}

From source file:com.jd.survey.web.settings.InvitationController.java

/**
 * Shows the list of Survey Invitations for a Survey Definition, Supports Paging 
 * @param surveyId//from www . j  a  va2s  .co  m
 * @param principal
 * @param uiModel
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/list", produces = "text/html", method = RequestMethod.GET)
public String listSurveyInvitations(@RequestParam(value = "id", required = true) Long surveyDefinitionId,
        @RequestParam(value = "page", required = false) Integer page,
        @RequestParam(value = "size", required = false) Integer size,
        @RequestParam(value = "fileContentError", required = false) boolean contentError, Model uiModel,
        Principal principal, HttpServletRequest httpServletRequest) {

    try {
        User user = userService.user_findByLogin(principal.getName());

        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            return "accessDenied";
        }
        Set<SurveyDefinition> surveyDefinitions = surveySettingsService
                .surveyDefinition_findAllCompletedInternal(user);
        uiModel.addAttribute("surveyDefinitions", surveyDefinitions);
        uiModel.addAttribute("surveyDefinition",
                surveySettingsService.surveyDefinition_findById(surveyDefinitionId));
        Long surveyInvitationsCount = surveySettingsService.invitation_getSurveyCount(surveyDefinitionId);
        uiModel.addAttribute("surveyInvitationsCount", surveyInvitationsCount);
        uiModel.addAttribute("surveyInvitationsOpenedCount",
                surveySettingsService.invitation_getSurveyOpenedCount(surveyDefinitionId));

        int sizeNo = size == null ? 25 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        Set<Invitation> invitations = surveySettingsService.invitation_findSurveyAll(surveyDefinitionId,
                firstResult, sizeNo);
        float nrOfPages = (float) surveyInvitationsCount / sizeNo;
        int maxPages = (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages);
        uiModel.addAttribute("maxPages", maxPages);
        uiModel.addAttribute("invitations", invitations);
        uiModel.addAttribute("fileContentError", contentError);// Used to carry error from file upload over and make it available to the view
        return "settings/invitations/invitations";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.jd.survey.web.settings.DataSetController.java

@Secured({ "ROLE_ADMIN" })
@RequestMapping(params = "create", produces = "text/html")
public String createDataSet(Principal principal, Model uiModel, HttpServletRequest httpServletRequest) {
    log.info("createForm(): handles param form");
    try {// www. j  a v a 2  s  .  c  o m
        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";
        }
        DataSet dataSet = new DataSet();
        populateEditForm(uiModel, dataSet, user);
        return "settings/datasets/create";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}

From source file:com.telefonica.euro_iaas.sdc.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 2s .c  om
 */
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 header = request.getHeader(OPENSTACK_HEADER_TOKEN);
    String pathInfo = request.getPathInfo();
    logger.debug(header);
    logger.debug(pathInfo);

    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 (header == null) {
            header = "";
        }

        try {
            String token = header;
            if ("".equals(token)) {
                String str = "Missing token header";
                logger.info(str);
                throw new BadCredentialsException(str);
            }
            String tenantId = request.getHeader(OPENSTACK_HEADER_TENANTID);
            String txId = request.getHeader("txId");
            if (txId != null) {
                MDC.put("txId", txId);

            }

            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:net.nan21.dnet.core.web.controller.ui.extjs.AbstractUiExtjsController.java

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

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");

    if (logger.isInfoEnabled()) {
        logger.info("Handling request for ui.extjs: ", request.getPathInfo());
    }/* ww  w  .  ja v a 2 s.c o  m*/

    String server = request.getServerName();
    int port = request.getServerPort();
    // String contextPath = request.getContextPath();
    // String path = request.getServletPath();

    String userRolesStr = null;

    try {
        ISessionUser su = (ISessionUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        IUser user = su.getUser();

        IUserSettings prefs = user.getSettings();

        Session.user.set(user);

        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.getDateFormat(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", this.getSettings().getProductName());
    model.put("productVersion", this.getSettings().getProductVersion());
    model.put("hostUrl", hostUrl);

    // themes
    model.put("urlUiExtjsThemes", getUiExtjsSettings().getUrlThemes());

    // DNet extjs components in core and modules
    model.put("urlUiExtjsCore", getUiExtjsSettings().getUrlCore());
    model.put("urlUiExtjsModules", getUiExtjsSettings().getUrlModules());
    model.put("urlUiExtjsModuleSubpath", getUiExtjsSettings().getModuleSupath());

    // translations for core and modules
    model.put("urlUiExtjsCoreI18n", getUiExtjsSettings().getUrlCoreI18n());
    model.put("urlUiExtjsModulesI18n", getUiExtjsSettings().getUrlModulesI18n());

    model.put("shortLanguage", this.resolveLang(request, response));
    model.put("theme", this.resolveTheme(request, response));
    model.put("sysCfg_workingMode", this.getSettings().get(Constants.PROP_WORKING_MODE));

    model.put("userRolesStr", userRolesStr);

}

From source file:org.iff.infra.util.servlet.ProxyServlet.java

/** Reads the request URI from {@code servletRequest} and rewrites it, considering {@link
 * #targetUriObj}. It's used to make the new request.
 */// w  w w.ja v  a2 s .c  o  m
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    uri.append(targetUri);
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(encodeUriQuery(servletRequest.getPathInfo()));
    }
    // Handle the query string
    String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment
    if (queryString != null && queryString.length() > 0) {
        uri.append('?');
        int fragIdx = queryString.indexOf('#');
        String queryNoFrag = (fragIdx < 0 ? queryString : queryString.substring(0, fragIdx));
        uri.append(encodeUriQuery(queryNoFrag));
        if (doSendUrlFragment && fragIdx >= 0) {
            uri.append('#');
            uri.append(encodeUriQuery(queryString.substring(fragIdx + 1)));
        }
    }
    return uri.toString();
}

From source file:com.codeabovelab.dm.gateway.proxy.common.HttpProxy.java

/**
 * For a redirect response from the target server, this translates {@code theUrl} to redirect to
 * and translates it to one the original client can use.
 *///from   w  w w  .j a v a 2 s .  c  o m
private String rewriteUrlFromResponse(HttpProxyContext proxyContext, String theUrl) {
    HttpServletRequest servletRequest = proxyContext.getRequest();
    //TODO document example paths
    final String targetUri = proxyContext.getTargetPath();
    if (theUrl.startsWith(targetUri)) {
        String curUrl = servletRequest.getRequestURL().toString();//no query
        String pathInfo = servletRequest.getPathInfo();
        if (pathInfo != null) {
            assert curUrl.endsWith(pathInfo);
            curUrl = curUrl.substring(0, curUrl.length() - pathInfo.length());//take pathInfo off
        }
        theUrl = curUrl + theUrl.substring(targetUri.length());
    }
    return theUrl;
}

From source file:ch.entwine.weblounge.security.sql.endpoint.SQLDirectoryProviderEndpoint.java

/**
 * Returns the endpoint documentation.//from   w  w w. j  a  va  2s. com
 * 
 * @return the endpoint documentation
 */
@GET
@Path("/docs")
@Produces(MediaType.TEXT_HTML)
public String getDocumentation(@Context HttpServletRequest request) {
    if (docs == null) {
        String docsPath = request.getRequestURI();
        String docsPathExtension = request.getPathInfo();
        String servicePath = request.getRequestURI().substring(0,
                docsPath.length() - docsPathExtension.length());
        docs = SQLDirectoryProviderEndpointDocs.createDocumentation(servicePath);
    }
    return docs;
}

From source file:com.jd.survey.web.reports.ReportController.java

/**
 * Exports survey data to a comma delimited values file
 * @param surveyDefinitionId//from   w  w  w  . j  a  va  2  s  . c o  m
 * @param principal
 * @param response
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "csv", produces = "text/html")
public void surveyCSVExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {

        User user = userService.user_findByLogin(principal.getName());
        if (!securityService.userIsAuthorizedToManageSurvey(surveyDefinitionId, user)) {
            log.warn("Unauthorized access to url path " + httpServletRequest.getPathInfo()
                    + " attempted by user login:" + principal.getName() + "from IP:"
                    + httpServletRequest.getLocalAddr());
            response.sendRedirect("../accessDenied");
            //throw new AccessDeniedException("Unauthorized access attempt");
        }

        String columnName;
        SurveyDefinition surveyDefinition = surveySettingsService.surveyDefinition_findById(surveyDefinitionId);
        List<Map<String, Object>> surveys = reportDAO.getSurveyData(surveyDefinitionId);

        StringBuilder stringBuilder = new StringBuilder();

        stringBuilder.append(
                "\"id\",\"Survey Name\",\"User Login\",\"Submission Date\",\"Creation Date\",\"Last Update Date\",");
        for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
            for (Question question : page.getQuestions()) {
                if (question.getType().getIsMatrix()) {
                    for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                        for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                            stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "r"
                                    + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder()
                                    + "\",");
                        }
                    }
                    continue;
                }

                if (question.getType().getIsMultipleValue()) {
                    for (QuestionOption questionOption : question.getOptions()) {
                        stringBuilder.append("\" p" + page.getOrder() + "q" + question.getOrder() + "o"
                                + questionOption.getOrder() + "\",");

                    }
                    continue;
                }
                stringBuilder.append("\"p" + page.getOrder() + "q" + question.getOrder() + "\",");
            }
        }

        stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
        stringBuilder.append("\n");

        for (Map<String, Object> record : surveys) {
            stringBuilder.append(record.get("survey_id") == null ? ""
                    : "\"" + record.get("survey_id").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("type_name") == null ? ""
                    : "\"" + record.get("type_name").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("login") == null ? ""
                    : "\"" + record.get("login").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("submission_date") == null ? ""
                    : "\"" + record.get("creation_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("creation_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");
            stringBuilder.append(record.get("last_update_date") == null ? ""
                    : "\"" + record.get("last_update_date").toString().replace("\"", "\"\"") + "\",");

            for (SurveyDefinitionPage page : surveyDefinition.getPages()) {
                for (Question question : page.getQuestions()) {
                    if (question.getType().getIsMatrix()) {
                        for (QuestionRowLabel questionRowLabel : question.getRowLabels()) {
                            for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) {
                                columnName = "p" + page.getOrder() + "q" + question.getOrder() + "r"
                                        + questionRowLabel.getOrder() + "c" + questionColumnLabel.getOrder();
                                stringBuilder.append(record.get(columnName) == null ? ","
                                        : "\"" + record.get(columnName).toString().replace("\"", "\"\"")
                                                + "\",");
                            }
                        }
                        continue;
                    }
                    if (question.getType().getIsMultipleValue()) {
                        for (QuestionOption questionOption : question.getOptions()) {
                            columnName = "p" + page.getOrder() + "q" + question.getOrder() + "o"
                                    + questionOption.getOrder();
                            stringBuilder.append(record.get(columnName) == null ? ","
                                    : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");
                        }
                        continue;
                    }
                    columnName = "p" + page.getOrder() + "q" + question.getOrder();
                    stringBuilder.append(record.get(columnName) == null ? ","
                            : "\"" + record.get(columnName).toString().replace("\"", "\"\"") + "\",");

                }
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1); //delete the last comma
            stringBuilder.append("\n");
        }

        //Zip file manipulations Code
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipEntry zipentry;
        ZipOutputStream zipfile = new ZipOutputStream(bos);
        zipentry = new ZipEntry("survey" + surveyDefinition.getId() + ".csv");
        zipfile.putNextEntry(zipentry);
        zipfile.write(stringBuilder.toString().getBytes("UTF-8"));
        zipfile.close();

        //response.setContentType("text/html; charset=utf-8");
        response.setContentType("application/octet-stream");
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache,must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Content-Disposition", "inline;filename=survey" + surveyDefinition.getId() + ".zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(bos.toByteArray());
        servletOutputStream.flush();

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

String[] getPathComponents(HttpServletRequest request) {
    String pathInfo = request.getPathInfo();

    StringTokenizer pathTokens = null;
    int tokenCount = 0;
    if (pathInfo != null) {
        pathTokens = new StringTokenizer(pathInfo, "/");
        tokenCount = pathTokens.countTokens();
    }/*w  w w  .  j  a v a  2s.c o  m*/
    String[] comps = new String[tokenCount + 1];
    comps[0] = request.getServletPath();
    int i = 1;
    while (pathTokens != null && pathTokens.hasMoreTokens()) {
        comps[i] = pathTokens.nextToken();
        if (comps[i] != null && comps[i].length() > 0)
            ++i;
    }

    if (i != comps.length) {
        String[] comps0 = new String[i];
        System.arraycopy(comps, 0, comps0, 0, i);
        comps = comps0;
    }
    return comps;
}