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:com.iisigroup.cap.base.handler.CheckTimeoutHandler.java

@SuppressWarnings({ "unchecked", "unused" })
public Result checkTO(Request request) throws CapException {
    AjaxFormResult result = new AjaxFormResult();
    HttpServletRequest sreq = (HttpServletRequest) request.getServletRequest();

    String refPath = sreq.getHeader("referer");
    refPath = StringEscapeUtils.unescapeHtml(refPath);
    String path = sreq.getPathInfo();
    boolean isNewSes = sreq.getSession(false).isNew();
    String isFresh = request.get("REFSH_TO", "");

    HttpSession session = sreq.getSession(false);
    Map<String, String> map = (Map<String, String>) session.getAttribute(TOCM);

    String curPage = request.get(CCPAGE_NO);

    if (curPage.lastIndexOf("ap") >= 0) {
        if (map != null && map.containsKey(curPage)) {
            // DO NOT THING
        } else {//from www.  j  av  a 2  s .co m
            map = new HashMap<String, String>();
            session.setAttribute(TOCM, map);
        }
    }
    if (map == null) {
        map = new HashMap<String, String>();
    }
    if (!CapString.isEmpty(curPage)) {
        if (map.containsKey(curPage) && !"Y".equals(isFresh)) {
            String openTime = map.get(curPage);

            // ??db??
            sysProp.remove(TIME_OUT);
            String stout = sysProp.get(TIME_OUT);
            if (CapString.isEmpty(stout)) {
                stout = "10"; // default 10mins
            }

            // ??
            String lastPageNo = getLastRcordTOMC(map);
            if (lastPageNo.compareTo(curPage) != 0) {
                /*
                 * ??timeout? ???
                 */
                if (map.get(lastPageNo) != null) {
                    long lastOpenTime = Long.parseLong(map.get(lastPageNo));
                    // Calculate difference in milliseconds
                    long curTime = CapDate.getCurrentTimestamp().getTime();
                    long diff = curTime - lastOpenTime;
                    // Difference in seconds
                    long diffSec = diff / 1000;
                    long propTimeout = (Long.parseLong(stout) + 1) * 60;
                    if (diffSec > propTimeout) {
                        map.remove(lastPageNo);
                        session.setAttribute(TOCM, map);
                    }
                }
                // ??????
                return result;
            }

            long time = Long.parseLong(openTime);
            Timestamp ts1 = new Timestamp(time);
            String d12str = CapDate.convertTimestampToString(ts1, "HH:mm:ss.sss");
            long curTime = CapDate.getCurrentTimestamp().getTime();
            long propTimeOut = sreq.getSession(false).getMaxInactiveInterval();
            if (!CapString.isEmpty(stout)) {
                propTimeOut = Long.parseLong(stout);
                long remindTime = (propTimeOut - 1) * 60;
                propTimeOut = propTimeOut * 60;
                // Calculate difference in milliseconds
                long diff = curTime - time;
                // Difference in seconds
                long diffSec = diff / 1000;
                String isContinues = request.get("isCntnu");
                if ("true".equals(isContinues)) {
                    map.put(curPage, String.valueOf(curTime));
                    session.setAttribute(TOCM, map);
                } else if (CapString.isEmpty(isContinues) && diffSec >= remindTime) {
                    result.set("SHOW_REMIND", "true");
                }
                // ?falsetimeout(user??,1??)
                else if ("false".equals(isContinues) || diffSec > propTimeOut) {
                    String webApUrl = sysProp.get("WEB_AP_URL");
                    String st1 = sreq.getScheme();
                    String st2 = sreq.getServerName();
                    int port = sreq.getServerPort();
                    String st4 = sreq.getContextPath();
                    webApUrl = st1 + "://" + st2 + ":" + port + st4;
                    result.set("errorPage", st4 + "/page/timeout");
                    map.remove(curPage);
                    session.setAttribute(TOCM, map);
                }
            }
        } else {
            long curTime = CapDate.getCurrentTimestamp().getTime();
            map.put(curPage, String.valueOf(curTime));
            session.setAttribute(TOCM, map);
        }
    }
    return result;
}

From source file:com.chaosinmotion.securechat.server.MessageServlet.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 www .j a  va  2  s  . 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("sendmessages")) {
                /*
                 * Process the send messages request. This takes an array
                 * of device IDs and messages. The assumption is that each
                 * messages.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = SendMessages.processRequest(userinfo, requestParams);

            } else if (path.equalsIgnoreCase("getmessages")) {
                /*
                 * Process the get messages request. This gets the messages
                 * associated with the device provided, so long as it is
                 * tied to the username that we've logged into. This will
                 * pull the data and delete the messages from the back
                 * end as they are pulled.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                retVal = GetMessages.processRequest(userinfo, requestParams);

            } else if (path.equalsIgnoreCase("dropmessages")) {
                /*
                 * Process the get messages request. This gets the messages
                 * associated with the device provided, so long as it is
                 * tied to the username that we've logged into. This will
                 * pull the data and delete the messages from the back
                 * end as they are pulled.
                 */

                JSONTokener tokener = new JSONTokener(req.getInputStream());
                JSONObject requestParams = new JSONObject(tokener);
                DropMessages.processRequest(userinfo, requestParams);
                retVal = new ReturnResult();

            } else if (path.equalsIgnoreCase("notifications")) {
                /*
                 * Process notification endpoint; this returns the
                 * port of the network connection endpoint the user
                 * can use for immediate notifications. This may also
                 * return failure if we were unable to open a port
                 * to receive connections.
                 */

                NotificationService n = NotificationService.getShared();
                if (n.isRunning()) {
                    SimpleReturnResult r = new SimpleReturnResult();
                    r.put("port", n.getServerPort());
                    r.put("host", n.getServerAddress());
                    r.put("ssl", n.getSSLFlag());
                    retVal = r;
                } else {
                    retVal = new ReturnResult(Errors.ERROR_NOTIFICATION, "No notification service");
                }
            }
        }
    } 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:be.iminds.aiolos.ui.CommonServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Not necessary for plugin only as standalone app.
    // doGetPlugin allways needed.
    // check whether we are not at .../{webManagerRoot}
    final String pathInfo = request.getPathInfo();
    if (pathInfo == null || pathInfo.equals("/")) {
        String path = request.getRequestURI();
        if (!path.endsWith("/")) {
            path = path.concat("/");
        }/*from   www  .  j  a v a 2 s.  c  o m*/
        path = path.concat(LABEL);
        response.sendRedirect(path);
        return;
    }

    int slash = pathInfo.indexOf("/", 1);
    if (slash < 2) {
        slash = pathInfo.length();
    }

    final String label = pathInfo.substring(1, slash);
    if (label != null && label.startsWith(LABEL)) {
        final RequestInfo reqInfo = new RequestInfo(request, LABEL);
        if (reqInfo.extension.equals("html")) {
            doGetPlugin(request, response);
        } else if (reqInfo.extension.equals("json")) {
            renderJSON(response, request.getLocale());
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }
}

From source file:com.jaspersoft.jasperserver.rest.services.RESTResource.java

/**
 * Get a resource based of the requested URI.
 * If the parameter file is set, it will be used to retrieve the content of the file.
 * //from  w w w.  j a v  a  2s. c  om
 * @param req
 * @param resp
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {

    // Get the uri of the resource
    String uri = restUtils.extractRepositoryUri(req.getPathInfo());
    if (!validParameters(req.getParameterMap().keySet())) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST,
                "request contains unsupported parameters");
    }

    // by default get the root...
    if (uri == null || uri.length() == 0)
        uri = "/";

    // get the resources....
    // Add all the options...
    Map<String, Object> options = new HashMap<String, Object>();

    // This options allow to get the informations about an input control
    // including the data to fill the input control....
    if (req.getParameter(Argument.IC_GET_QUERY_DATA) != null) {
        options.put(Argument.IC_GET_QUERY_DATA, req.getParameter(Argument.IC_GET_QUERY_DATA));

        // Extract parameters
        Map<String, Object> parameters = restUtils.extractParameters(req);

        // Add the parsed parameters to the options map (only if it makes sense)
        if (parameters.size() > 0) {
            options.put(Argument.PARAMS_ARG, parameters);
        }
    }

    options.put(restUtils.SWITCH_PARAM_GET_LOCAL_RESOURCE,
            restUtils.isLocalResource(uri) && req.getParameterMap().containsKey(restUtils.FILE_DATA));
    if (log.isDebugEnabled()) {
        log.debug("adding the local resource with data flag");
    }

    ResourceDescriptor rd = null;
    try {
        rd = resourcesManagementRemoteService.getResource(uri, options);
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex.getMessage());
    }

    // This check should not be useful, since an execption should have been thrown by service.getReporse
    if (rd == null) {
        if (log.isDebugEnabled()) {
            log.debug("Could not find resource: " + uri);
        }
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "Could not find resource: " + uri);
    }

    // If the client specified a specific file, return the file
    if (Boolean.parseBoolean(req.getParameter(restUtils.FILE_DATA))) {
        if (runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString()).get(rd.getUriString()),
                    resp);
        else if (runReportService.getReportAttachments(rd.getUriString())
                .get(FileResourceHandler.MAIN_ATTACHMENT_ID) != null)
            restUtils.sendFile(runReportService.getReportAttachments(rd.getUriString())
                    .get(FileResourceHandler.MAIN_ATTACHMENT_ID), resp);
        return;

    } else // else return the resource descriptor
    {

        Marshaller m = new Marshaller();
        String xml = m.writeResourceDescriptor(rd);

        resp.setContentType("text/xml");
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, xml);
    }
    return;
}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected boolean hasPathPrefix(HttpServletRequest request, String prefix) {
    String pathInfo = request.getPathInfo();

    if (pathInfo == null) {
        return false;
    }//ww  w . j  a  v  a2  s .c om

    if (!prefix.startsWith("/")) {
        prefix = '/' + prefix;
    }

    return pathInfo.startsWith(prefix);
}

From source file:com.netspective.sparx.util.HttpServletResponseCache.java

public void cacheResponse(long servletLastModf, HttpServletRequest req, ResponseCache res) {
    synchronized (pageCache) {
        String cacheKey = req.getServletPath() + req.getPathInfo() + req.getQueryString();
        pageCache.put(cacheKey, new CacheData(res, servletLastModf, req.getServletPath(), req.getPathInfo(),
                req.getQueryString()));//from  w  ww.  java 2  s  . c  om
    }
}

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

private boolean isGitLfsRequest(HttpServletRequest request) {
    String lfsApiPath = "/api/" + GitLfsResourceConstants.PATH_ROOT;
    String joinedRequestPath = request.getServletPath() + request.getPathInfo();
    return joinedRequestPath.contains(lfsApiPath) || request.getRequestURL().toString().contains(lfsApiPath);
}

From source file:edu.harvard.med.screensaver.ui.arch.util.servlet.ImageProviderServlet.java

/**
 * Http requests to this servlet are be treated as image requests. The image is 
 * located by prepending a filesystem location to the "extra path info" URL 
 * requested by the client. The image, if found, is written to the response.<br>
 * /*from w w  w. j a v  a2s  . com*/
 * @throws IOException if the image file cannot be found
 */
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if (log.isDebugEnabled()) {
        log.debug("ImageProviderServlet: \"" + ScreensaverConstants.IMAGES_BASE_DIR + "\": "
                + _imagesFileSystemPath);
        log.debug("service: req.getPathInfo(): " + req.getPathInfo());
    }
    String pathInfo = req.getPathInfo();

    if (pathInfo != null) {
        // FYI... setting the content type is not necessary for most (modern) browsers
        if (pathInfo.toLowerCase().matches(".*\\.png")) {
            resp.setContentType("image/png");
        } else if (pathInfo.toLowerCase().matches(".*\\.gif")) {
            resp.setContentType("image/gif");
        } else if (pathInfo.toLowerCase().matches(".*\\.bmp")) {
            resp.setContentType("image/bmp");
        } else if (pathInfo.toLowerCase().matches(".*\\.tiff")) {
            resp.setContentType("image/tiff");
        } else {
            resp.setContentType("image/jpeg"); // default should be ok, since not strictly req'd
        }
        FileInputStream fis = null;
        try {
            File file = getImage(req.getSession().getServletContext().getRealPath("/"), pathInfo);
            if (log.isDebugEnabled()) {
                log.debug("retrieve the image: " + file.getAbsolutePath());
            }
            if (!file.exists()) {
                log.warn("image file not found: " + file);
            }
            fis = new FileInputStream(file);
            resp.getOutputStream().write(IOUtils.toByteArray(fis));
        } catch (Exception e) {
            log.error("on serving the image for req: " + req.getPathInfo() + ", interpreted as: " + pathInfo
                    + ", " + e.getMessage());
            resp.sendError(resp.SC_NOT_FOUND, "Image not found: " + pathInfo);
        } finally {
            if (fis != null)
                fis.close();
        }
    } else {
        throw new ServletException("No image pathInfo specified");
    }
}

From source file:de.zazaz.iot.bosch.indego.ifttt.IftttIndegoAdapter.java

/**
 * This handles a command request//from   ww  w.j  ava2  s .com
 * 
 * @param req_ the servlet request
 * @param resp_ the servlet response
 */
private void handleIftttCommand(HttpServletRequest req_, HttpServletResponse resp_) {
    String commandStr = req_.getPathInfo();
    int idx = commandStr.lastIndexOf('/');
    if (idx > 0) {
        commandStr = commandStr.substring(idx + 1);
    }
    commandToExecute.set(commandStr);
    semThreadWaker.release();
}

From source file:io.mapzone.controller.vm.http.HttpResponseForwarder.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  ww .  ja va2 s .  c  o  m
protected String rewriteUrlFromResponse(HttpServletRequest servletRequest, String theUrl) {
    // TODO document example paths
    final String targetUri = requestForwarder.targetUri.get();
    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;
}