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:org.apache.ofbiz.base.util.UtilHttp.java

public static Map<String, Object> getPathInfoOnlyParameterMap(HttpServletRequest request,
        Set<? extends String> nameSet, Boolean onlyIncludeOrSkip) {
    return getPathInfoOnlyParameterMap(request.getPathInfo(), nameSet, onlyIncludeOrSkip);
}

From source file:net.oneandone.jasmin.main.Servlet.java

private void notFound(HttpServletRequest request, HttpServletResponse response) throws IOException {
    LOG.warn("not found: " + request.getPathInfo());
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

From source file:com.openmeap.admin.web.servlet.WebViewServlet.java

@SuppressWarnings("unchecked")
@Override/*  w  w w  .j a  v  a  2  s  . c  o m*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    logger.trace("in service");

    ModelManager mgr = getModelManager();
    GlobalSettings settings = mgr.getGlobalSettings();
    String validTempPath = settings.validateTemporaryStoragePath();
    if (validTempPath != null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, validTempPath);
    }

    String pathInfo = request.getPathInfo();
    String[] pathParts = pathInfo.split("[/]");
    if (pathParts.length < 4) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
    String remove = pathParts[1] + "/" + pathParts[2] + "/" + pathParts[3];
    String fileRelative = pathInfo.replace(remove, "");

    String applicationNameString = URLDecoder.decode(pathParts[APP_NAME_INDEX], FormConstants.CHAR_ENC_DEFAULT);
    String archiveHash = URLDecoder.decode(pathParts[APP_VER_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    Application app = mgr.getModelService().findApplicationByName(applicationNameString);
    ApplicationArchive arch = mgr.getModelService().findApplicationArchiveByHashAndAlgorithm(app, archiveHash,
            "MD5");

    String authSalt = app.getProxyAuthSalt();
    String authToken = URLDecoder.decode(pathParts[AUTH_TOKEN_INDEX], FormConstants.CHAR_ENC_DEFAULT);

    try {
        if (!AuthTokenProvider.validateAuthToken(authSalt, authToken)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
    } catch (DigestException e1) {
        throw new GenericRuntimeException(e1);
    }

    File fileFull = new File(
            arch.getExplodedPath(settings.getTemporaryStoragePath()).getAbsolutePath() + "/" + fileRelative);
    try {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String mimeType = fileNameMap.getContentTypeFor(fileFull.toURL().toString());
        response.setContentType(mimeType);
        response.setContentLength(Long.valueOf(fileFull.length()).intValue());

        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            //response.setStatus(HttpServletResponse.SC_FOUND);
            inputStream = new FileInputStream(fileFull);
            outputStream = response.getOutputStream();
            Utils.pipeInputStreamIntoOutputStream(inputStream, outputStream);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
    } catch (FileNotFoundException e) {
        logger.error("Exception {}", e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IOException ioe) {
        logger.error("Exception {}", ioe);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

From source file:net.riezebos.thoth.testutil.ThothTestBase.java

protected HttpServletRequest createHttpRequest(String contextName, String path) throws IOException {
    String fullPath = ThothUtil.prefix(contextName, "/") + path;
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(request.getRequestURI()).thenReturn(path);
    when(request.getContextPath()).thenReturn(ThothUtil.prefix(contextName, "/"));
    when(request.getServletPath()).thenReturn(path);
    when(request.getPathInfo()).thenReturn(fullPath);
    when(request.getParameterNames()).thenReturn(getParameterNames());
    recordGetParameter(request);//from w  w  w.j  a  v  a2s . com
    return request;
}

From source file:alpine.filters.FqdnForwardFilter.java

/**
 * Forward requests.....//from www . ja  v  a 2s  .  c  o m
 *
 * @param request The request object.
 * @param response The response object.
 * @param chain Refers to the {@code FilterChain} object to pass control to the next {@code Filter}.
 * @throws IOException a IOException
 * @throws ServletException a ServletException
 */
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest req = (HttpServletRequest) request;
    final HttpServletResponse res = (HttpServletResponse) response;

    if (req.getServerName().equals(host)) {
        chain.doFilter(request, response);
        return;
    }

    res.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

    StringBuilder sb = new StringBuilder();
    sb.append("http");
    if (req.isSecure()) {
        sb.append("s");
    }
    sb.append("://").append(host);
    if (StringUtils.isNotBlank(req.getPathInfo())) {
        sb.append(req.getPathInfo());
    }
    if (StringUtils.isNotBlank(req.getQueryString())) {
        sb.append("?").append(req.getQueryString());
    }
    res.setHeader("Location", sb.toString());
}

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

/**
 * Reads the request URI from {@code servletRequest} and rewrites it, considering targetUri.
 * It's used to make the new request./*  w  w  w. ja v  a  2  s.  c  o  m*/
 */
private String rewriteUrlFromRequest(HttpProxyContext proxyContext) {
    HttpServletRequest servletRequest = proxyContext.getRequest();
    StringBuilder uri = new StringBuilder(500);
    uri.append(proxyContext.getTargetPath());
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(HttpProxyUtil.encodeUriQuery(servletRequest.getPathInfo()));
    }
    // Handle the query string & fragment
    String queryString = servletRequest.getQueryString();//ex:(following '?'): name=value&foo=bar#fragment
    String fragment = null;
    //split off fragment from queryString, updating queryString if found
    if (queryString != null) {
        int fragIdx = queryString.indexOf('#');
        if (fragIdx >= 0) {
            fragment = queryString.substring(fragIdx + 1);
            queryString = queryString.substring(0, fragIdx);
        }
    }

    queryString = rewriteQueryStringFromRequest(servletRequest, queryString);
    if (queryString != null && queryString.length() > 0) {
        uri.append('?');
        uri.append(HttpProxyUtil.encodeUriQuery(queryString));
    }

    if (DO_SEND_URL_FRAGMENT && fragment != null) {
        uri.append('#');
        uri.append(HttpProxyUtil.encodeUriQuery(fragment));
    }
    return uri.toString();
}

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

@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN" })
@RequestMapping(value = "/{id}", params = "spss", produces = "text/html")
public void surveySPSSExport(@PathVariable("id") Long surveyDefinitionId, Principal principal,
        HttpServletRequest httpServletRequest, HttpServletResponse response) {
    try {//from  w  ww .  j ava  2  s  . c om
        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 metadataFileName = "survey" + surveyDefinitionId + ".sps";
        String dataFileName = "survey" + surveyDefinitionId + ".dat";

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zipfile = new ZipOutputStream(baos);

        //metadata    
        zipfile.putNextEntry(new ZipEntry(metadataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSMetadata(surveyDefinitionId, dataFileName));
        //data
        zipfile.putNextEntry(new ZipEntry(dataFileName));
        zipfile.write(sPSSHelperService.getSurveyDefinitionSPSSData(surveyDefinitionId));
        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" + surveyDefinitionId + "_spss.zip");
        ServletOutputStream servletOutputStream = response.getOutputStream();
        //servletOutputStream.write(stringBuilder.toString().getBytes("UTF-8"));
        servletOutputStream.write(baos.toByteArray());
        servletOutputStream.flush();

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

From source file:org.redhat.jboss.httppacemaker.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(this.targetUri.toString())) {
        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
        }/*from   w w w.ja  v  a  2 s .  co  m*/
        theUrl = curUrl + theUrl.substring(this.targetUri.toString().length());
    }
    return theUrl;
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.APIServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String[] pathInfo = req.getPathInfo().split("/"); // Expected path info is /command/command_param_1/command_param_2/...etc.    
    // Notes: if the request is valid (e.g. looks like /command/command_params), 
    //      pathInfo[0] contains an empty string,
    //      pathInfo[1] contains "command",
    //      pathInfo[2] and next each contains a command parameter. Command parameters are "/"-separated.
    if (pathInfo != null && pathInfo.length > 1) {
        if (pathInfo[1].equals("gettcmbaseid")) {
            JSONObject o = new JSONObject();

            try {
                o.put("tcmBaseID", tcmManager.getTransceiverBaseID());
            } catch (JSONException e) {
                resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error));
                return;
            }//w  w  w  .  jav a 2  s  .co  m

            resp.getWriter().write(WebApiCommons.okMessage(o));
            return;
        } else if (pathInfo[1].equals("getProperties")) {
            String itemUID = pathInfo[2];
            try {
                BlindAndShutterMotorDevice device = (BlindAndShutterMotorDevice) deviceManager
                        .getDevice(itemUID);
                resp.getWriter().write(WebApiCommons.okMessage(device.getValueAsJSON()));
                return;
            } catch (Exception e) {
                resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error));
                return;
            }
        } else if (pathInfo[1].equals("getDimmerValue")) {
            String itemUID = pathInfo[2];
            try {
                ElectronicSwitchWithEnergyMeasurement device = (ElectronicSwitchWithEnergyMeasurement) deviceManager
                        .getDevice(itemUID);
                resp.getWriter().write(WebApiCommons.okMessage(device.getDimmerValueAsJSON()));
                return;
            } catch (Exception e) {
                resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.internal_error));
                return;
            }
        }
    }

    resp.getWriter().write(WebApiCommons.errorMessage(WebApiCommons.Errors.invalid_query));
}

From source file:be.milieuinfo.core.proxy.controller.ProxyServlet.java

private String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) {
    //TODO document example paths
    if (theUrl.startsWith(this.targetUri.toString())) {
        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
        }//from www  .  j ava2 s . c o m
        theUrl = curUrl + theUrl.substring(this.targetUri.toString().length());
    }
    return theUrl;
}