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:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    if (servletRequest.getPathInfo() != null
            && servletRequest.getPathInfo().matches("/http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) {

        // Remove '/' from the beginning of the path
        String target = servletRequest.getPathInfo().substring(1);
        if (target.startsWith("https")) {
            target = "https:/" + target.substring(6);
        } else {//www.j a v  a 2s  . c  o m
            target = "http:/" + target.substring(5);
        }
        servletRequest.setAttribute(ATTR_TARGET_URI, target);
        uri.append(target);
    } else {
        uri.append(getTargetUri(servletRequest));
        // Handle the path given to the servlet
        if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
            uri.append(encodeUriQuery(servletRequest.getPathInfo()));
        }
    }
    // Handle the query string & fragment
    //ex:(following '?'): name=value&foo=bar#fragment
    String queryString = servletRequest.getQueryString();
    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 + 2); // '#!', not '#'
            //        fragment = queryString.substring(fragIdx + 1);
            queryString = queryString.substring(0, fragIdx);
        }
    }

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

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

From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java

/**
 * Reads the request URI from {@code servletRequest} and rewrites it, considering
 * targetUri. It's used to make the new request.
 *//*from w  w w  .  j  a  v  a  2 s.c  o m*/
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    uri.append(targetUriObj);
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {// ex: /my/path.html
        uri.append(encodeUriQuery(rewritePath(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 = rewriteQueryString(queryString);
    if (queryString != null && queryString.length() > 0) {
        uri.append('?');
        uri.append(encodeUriQuery(queryString));
    }

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

From source file:com.centurylink.mdw.hub.servlet.RestServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    CodeTimer timer = new CodeTimer("RestServlet.doGet()", true);

    if (request.getPathInfo() == null) {
        // redirect to html documentation
        response.sendRedirect(ApplicationContext.getMdwHubUrl() + "/doc/webServices.html");
        return;/*from w  ww.ja v a2  s .  c  o m*/
    } else if (request.getPathInfo().startsWith("/SOAP")) {
        // forward to SOAP servlet
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(request.getPathInfo());
        requestDispatcher.forward(request, response);
        return;
    } else if (ApplicationContext.isDevelopment() && isFromLocalhost(request)) {
        // this is only allowed from localhost and in dev
        if ("/System/exit".equals(request.getPathInfo())) {
            response.setStatus(200);
            new Thread(new Runnable() {
                public void run() {
                    System.exit(0);
                }
            }).start();
            return;
        }
    }

    Map<String, String> metaInfo = buildMetaInfo(request);
    try {
        String responseString = handleRequest(request, response, metaInfo);

        String downloadFormat = metaInfo.get(Listener.METAINFO_DOWNLOAD_FORMAT);
        if (downloadFormat != null) {
            response.setContentType(Listener.CONTENT_TYPE_DOWNLOAD);
            String fileName = request.getPathInfo().substring(1).replace('/', '-') + "." + downloadFormat;
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            if (downloadFormat.equals(Listener.DOWNLOAD_FORMAT_JSON)
                    || downloadFormat.equals(Listener.DOWNLOAD_FORMAT_XML)
                    || downloadFormat.equals(Listener.DOWNLOAD_FORMAT_TEXT)) {
                response.getOutputStream().write(responseString.getBytes());
            } else if (downloadFormat.equals(Listener.DOWNLOAD_FORMAT_FILE)) {
                String f = metaInfo.get(Listener.METAINFO_DOWNLOAD_FILE);
                if (f == null)
                    throw new ServiceException(ServiceException.INTERNAL_ERROR, "Missing meta");
                File file = new File(f);
                if (!file.isFile())
                    throw new ServiceException(ServiceException.NOT_FOUND,
                            "File not found: " + file.getAbsolutePath());
                int max = PropertyManager.getIntegerProperty(PropertyNames.MAX_DOWNLOAD_BYTES, 104857600);
                if (file.length() > max)
                    throw new ServiceException(ServiceException.NOT_ALLOWED,
                            file.getAbsolutePath() + " exceeds max download size (" + max + "b )");
                response.setHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
                try (InputStream in = new FileInputStream(file)) {
                    int read = 0;
                    byte[] bytes = new byte[8192];
                    while ((read = in.read(bytes)) != -1)
                        response.getOutputStream().write(bytes, 0, read);
                }
            } else {
                // for binary content string response will have been Base64 encoded
                response.getOutputStream().write(Base64.decodeBase64(responseString.getBytes()));
            }
        } else {
            if ("/System/sysInfo".equals(request.getPathInfo())
                    && "application/json".equals(metaInfo.get(Listener.METAINFO_CONTENT_TYPE))) {
                responseString = WebAppContext.addContextInfo(responseString, request);
            }
            response.getOutputStream().write(responseString.getBytes());
        }
    } catch (ServiceException ex) {
        logger.severeException(ex.getMessage(), ex);
        response.setStatus(ex.getCode());
        response.getWriter().println(createErrorResponseMessage(request, metaInfo, ex));
    } finally {
        timer.stopAndLogTiming("");
    }
}

From source file:com.chaosinmotion.securechat.server.DeviceServlet.java

/**
 * Handle POST commands. This uses the cookie mechanism for Java
 * servlets to track users for security reasons, and handles the
 * commands for getting a token, for verifying server status, and for
 * logging in and changing a password./*from ww w. j a  v a  2s.  c  o m*/
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ReturnResult retVal = null;

    /*
     * Step 1: determine the path element after the api/1/ URL. This
     * determines the command
     */

    String path = req.getPathInfo();
    if (path == null) {
        resp.sendError(404);
        return;
    }
    if (path.startsWith("/"))
        path = path.substring(1);

    try {
        /*
         * All commands require authentication. This determines if we have
         * it or not.
         */
        HttpSession session = req.getSession();
        Login.UserInfo userinfo = (Login.UserInfo) session.getAttribute("userinfo");
        if (userinfo == null) {
            retVal = new ReturnResult(Errors.ERROR_UNAUTHORIZED, "Not authorized");
        } else {

            if (path.equalsIgnoreCase("adddevice")) {
                /*
                 * Process the adddevice request. This adds a new device
                 * to this user's list of device. We are basically a 
                 * key escrow system with each user associated with a 
                 * list of devices (by id) and their public keys.
                 * 
                 * This is a potential weak point in the protocol in that
                 * a bad guy could theoretically add his own device to
                 * this account. But to do so he'd have to have the
                 * username and password for this user, and the fact that
                 * there were multiple devices associated with this
                 * account would be effectively broadcast to all senders.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                if (AddDevice.processRequest(userinfo, requestParams)) {
                    retVal = new ReturnResult();
                } else {
                    retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error");
                }

            } else if (path.equalsIgnoreCase("removedevice")) {
                /*
                 * Process the removedevice request. This removes the
                 * device (by its device ID) from the list of devices
                 * associated with the user.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                if (RemoveDevice.processRequest(userinfo, requestParams)) {
                    retVal = new ReturnResult();
                } else {
                    retVal = new ReturnResult(Errors.ERROR_INTERNAL, "Internal error");
                }

            } else if (path.equalsIgnoreCase("devices")) {
                /*
                 * Process the devices request, which, for a given username
                 * returns an array of devices (device ID and public key)
                 * associated with the user. This allows each sender to
                 * know the devices to encrypt messages for.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = Devices.processRequest(userinfo, requestParams);
            }
        }
    } catch (Throwable th) {
        retVal = new ReturnResult(th);
    }

    /*
     * If we get here and we still haven't initialized return value,
     * set to a 404 error. We assume this reaches here with a null
     * value because the path doesn't exist.
     */

    if (retVal == null) {
        resp.sendError(404);

    } else {
        /*
         * We now have a return result. Formulate the response
         */

        ServletOutputStream stream = resp.getOutputStream();
        resp.setContentType("application/json");
        stream.print(retVal.toString());
    }
}

From source file:eu.gusak.orion.php.servlets.PhpServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    traceRequest(req);//from   w  w  w . ja va  2 s.c  o m
    String pathString = req.getPathInfo();
    if (pathString == null || pathString.equals("/")) { //$NON-NLS-1$
        handleException(resp, "No mode defined in request URI", new InvalidParameterException());
        return;
    }
    IPath path = new Path(pathString);
    if (path.segmentCount() != 2) { // /index.html is being added
        handleException(resp, "No mode defined in request URI", new InvalidParameterException());
        return;
    }

    String mode = path.segment(0);

    if (mode.equals("contentassist")) {
        doGetContentAssist(req, resp);
    } else if (mode.equals("codevalidation")) {
        doGetCodeValidation(req, resp);
    } else {
        handleException(resp, "Unknown mode provided in request URI", new InvalidParameterException());
        return;
    }
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doGet(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - GET");

    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());/*  www.  j  a v  a  2s .  c  om*/
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: " + uri.toString());
    try {
        String response = servicesClient.proxyGet(uri.toString(),
                getQueryParamsFromURI(servletRequest.getParameterMap()));
        servletResponse.getWriter().write(response);
    } catch (ClientException e) {
        e.printStackTrace();
    }
}

From source file:org.artifactory.webapp.servlet.RepoFilter.java

private boolean isDockerRequest(HttpServletRequest request) {
    String dockerApiPath = "/api/docker";
    String joinedRequestPath = request.getServletPath() + request.getPathInfo();
    return joinedRequestPath.contains(dockerApiPath)
            || request.getRequestURL().toString().contains(dockerApiPath);
}

From source file:edu.emory.cci.aiw.cvrg.eureka.servlet.ProxyServlet.java

@Override
protected void doDelete(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    LOGGER.debug("ProxyServlet - DELETE");

    StringBuilder uri = new StringBuilder(500);
    uri.append(getTargetUri());//from www.  ja v a 2 s  .  c o  m
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        uri.append(servletRequest.getPathInfo());
    }
    LOGGER.debug("uri: {}", uri.toString());

    try {
        servicesClient.proxyDelete(uri.toString());
    } catch (ClientException e) {
        e.printStackTrace();
    }

}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Forward.java

public void doGet(HttpServletRequest sreq, HttpServletResponse sres) throws ServletException, IOException {
    String path = (String) sreq.getAttribute("javax.servlet.include.servlet_path");
    if (path == null)
        path = sreq.getServletPath();//from   www.  jav a  2 s  .  c  o  m
    if (path.length() == 0) {
        path = (String) sreq.getAttribute("javax.servlet.include.path_info");
        if (path == null)
            path = sreq.getPathInfo();
    }

    String forward = (String) _forwardMap.get(path);
    if (log.isDebugEnabled())
        log.debug("Forward " + path + " to " + forward);
    if (forward != null) {
        ServletContext context = getServletContext().getContext(forward);
        String contextPath = sreq.getContextPath();
        if (contextPath.length() > 1)
            forward = forward.substring(contextPath.length());

        RequestDispatcher dispatch = context.getRequestDispatcher(forward);
        if (dispatch != null) {
            dispatch.forward(sreq, sres);
            return;
        }
    }

    sres.sendError(404);
}