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.dspace.app.webui.cris.controller.RedirectEntityDetailsController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String id = request.getParameter("id");
    T entity = null;// w  w w.ja  v  a  2  s. com
    if (id == null || id.isEmpty()) {

        String modeCode = request.getParameter("code");
        if (modeCode != null && !modeCode.isEmpty()) {
            entity = ((ApplicationService) applicationService).getEntityBySourceId(modeCode, modelClass);
        } else {
            String path = request.getPathInfo().substring(1); // remove
                                                              // first /
            String[] splitted = path.split("/");
            request.setAttribute("authority", splitted[1]);
            entity = ((ApplicationService) applicationService).get(modelClass,
                    ResearcherPageUtils.getRealPersistentIdentifier(splitted[1], modelClass));

        }
    } else {
        try {
            entity = applicationService.get(modelClass, Integer.parseInt(id));
        } catch (NumberFormatException e) {
            log.error(e.getMessage(), e);
        }
    }

    return new ModelAndView("redirect:" + ResearcherPageUtils.getPersistentIdentifier(entity));
}

From source file:com.sonicle.webtop.calendar.PublicService.java

@Override
public void processDefaultAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
    PublicPath path = new PublicPath(request.getPathInfo());
    WebTopSession wts = getEnv().getWebTopSession();

    try {/*www .  j a  v a2s.  c o  m*/
        try {
            String domainId = WT.findDomainIdByPublicName(path.getDomainPublicName());
            if (domainId == null)
                throw new WTException("Invalid domain public name [{0}]", path.getDomainPublicName());

            if (path.getContext().equals(PUBPATH_CONTEXT_EVENT)) {
                EventUrlPath eventUrlPath = new EventUrlPath(path.getRemainingPath());
                CalendarManager adminCalMgr = getAdminManager(domainId);

                Event event = null;
                if (!StringUtils.isBlank(eventUrlPath.getPublicUid())) {
                    if (eventUrlPath.isActionReply()) {
                        String aid = ServletUtils.getStringParameter(request, "aid", true);
                        String resp = ServletUtils.getStringParameter(request, "resp", true);

                        EventAttendee.ResponseStatus responseStatus = toResponseStatus(resp);
                        if (responseStatus == null)
                            throw new WTException("Invalid resp [{0}]", resp);

                        event = adminCalMgr.updateEventFromSite(eventUrlPath.getPublicUid(), aid,
                                responseStatus);

                    } else {
                        event = adminCalMgr.getEventFromSite(eventUrlPath.getPublicUid());
                    }
                }

                if (event == null) {
                    logger.trace("Event not found [{}]", eventUrlPath.getPublicUid());
                    writeErrorPage(request, response, wts, "eventnotfound");

                } else {
                    Calendar calendar = adminCalMgr.getCalendar(event.getCalendarId());
                    writeEventPage(request, response, wts, "Event", calendar, event);
                }

            } else {
                logger.trace("Invalid context [{}]", path.getContext());
                writeErrorPage(request, response, wts, "badrequest");
            }

        } catch (Exception ex) {
            logger.trace("Error", ex);
            writeErrorPage(request, response, wts, "badrequest");
        }
    } catch (Throwable t) {
        logger.error("Unexpected error", t);
    }
}

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

@BeforeMethod
public void setUp() throws Exception {
    super.setUp();
    myServer = new Server(12345);
    WebAppContext handler = new WebAppContext();
    handler.setResourceBase("/");
    handler.setContextPath(CONTEXT_PATH);
    myDownloadMap = new HashMap<String, File>();
    myDownloadAttempts = new ArrayList<String>();
    myDownloadHonestly = true;//from ww  w  .  j a  va  2s.c  om
    myDownloadHacks = new HashMap<String, byte[]>();
    myDownloadHackAttempts = new ArrayList<String>();
    handler.addServlet(new ServletHolder(new HttpServlet() {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            myDownloadAttempts.add(req.getPathInfo());
            final ServletOutputStream os = resp.getOutputStream();
            final File file = myDownloadMap.get(req.getPathInfo());
            final byte[] bytes = FileUtils.readFileToByteArray(file);
            os.write(bytes);
            os.close();
        }
    }), "/*");
    myServer.setHandler(handler);
    myServer.start();

    myAgentParametersMap = new HashMap<String, String>();

    Mockery m = new Mockery();
    myBuild = m.mock(AgentRunningBuild.class);
    final BuildProgressLogger myLogger = new BaseServerLoggerFacade() {
        @Override
        public void flush() {
        }

        @Override
        protected void log(final BuildMessage1 message) {

        }
    };

    m.checking(new Expectations() {
        {
            allowing(myBuild).getSharedConfigParameters();
            will(returnValue(myAgentParametersMap));
            allowing(myBuild).getBuildTypeId();
            will(returnValue("TC_Gaya80x_BuildDist"));
            allowing(myBuild).getBuildLogger();
            will(returnValue(myLogger));
        }
    });

    myDirectorySeeder = new TorrentsDirectorySeeder(createTempDir(), -1, 1);

    myTorrentTransport = new TorrentTransportFactory.TorrentTransport(myDirectorySeeder, new HttpClient(),
            myBuild.getBuildLogger()) {
        @Override
        protected byte[] download(@NotNull String urlString) throws IOException {
            if (myDownloadHonestly) {
                return super.download(urlString);
            } else {
                myDownloadHackAttempts.add(urlString);
                return myDownloadHacks.get(urlString);
            }
        }
    };

    myTempDir = createTempDir();
}

From source file:com.google.code.pathlet.web.PathletAjaxProcessor.java

/**
 * Retrieves the current request servlet path.
 * Deals with differences between servlet specs (2.2 vs 2.3+)
 *
 * @param request the request// w  w  w  .ja v a 2s  . c  om
 * @return the servlet path
 */
private String getServletPath(HttpServletRequest request) {
    String servletPath = request.getServletPath();

    if (ValueUtils.notEmpty(servletPath)) {
        return servletPath;
    }

    String requestUri = request.getRequestURI();
    int startIndex = request.getContextPath().equals("") ? 0 : request.getContextPath().length();
    int endIndex = request.getPathInfo() == null ? requestUri.length()
            : requestUri.lastIndexOf(request.getPathInfo());

    if (startIndex > endIndex) { // this should not happen
        endIndex = startIndex;
    }

    return requestUri.substring(startIndex, endIndex);
}

From source file:io.hops.hopsworks.api.tensorflow.TensorboardProxyServlet.java

/**
 * Reads the request URI from {@code servletRequest} and rewrites it,
 * considering targetUri./*  w  ww .java2s . com*/
 * It's used to make the new request.
 */
@Override
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    String theUri = getTargetUri(servletRequest);
    uri.append(theUri);
    // Handle the path given to the servlet
    if (servletRequest.getPathInfo() != null) {//ex: /my/path.html
        String pathInfo = servletRequest.getPathInfo();
        pathInfo = pathInfo.substring(1);
        String targetUrl = ((String) servletRequest.getAttribute(ATTR_HOST_PORT))
                + ((String) servletRequest.getAttribute(ATTR_URI_FINISH));
        if (pathInfo.contains(targetUrl)) {
            pathInfo = pathInfo.substring(pathInfo.indexOf(targetUrl) + targetUrl.length());
        } else {
            pathInfo = "";
        }
        uri.append(encodeUriQuery(pathInfo));
    }
    // 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:com.brokenmodel.swats.RouterServlet.java

private void handleRequest(HttpServletRequest request, HttpServletResponse response,
        ControllerRequest.Type type) {
    try {//ww  w  . j a  v a  2s .  c o  m
        URL rootURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(),
                request.getContextPath() + request.getServletPath());

        String appRoot = rootURL.getFile();
        String htmlRoot = request.getContextPath();

        MatchedRoute matchedRoute = controllers.matchRoute(request.getPathInfo());
        ControllerRequest controllerRequest = new ControllerRequest(request, response, appRoot, htmlRoot,
                matchedRoute.getUrlParams(), type, handleMultipart(request), getDataSource());
        AbstractController controller = matchedRoute.getController();
        controller.doRequest(controllerRequest);
    } catch (Throwable t) {
        log(t);
        try {
            // only will work if output stream has not been opened
            PrintWriter pw = new PrintWriter(response.getWriter());
            pw.append("<pre>");
            pw.append("We're sorry - an error has occurred:\n\n");
            t.printStackTrace(pw);
            pw.append("</pre>");
        } catch (Throwable t2) {
        }
    }
}

From source file:com.ebay.pulsar.metric.servlet.MetricRestServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        inputStream.mark(Integer.MAX_VALUE);
    }/* w  ww  . j a v a 2s. c  o m*/
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith(PATH_PING)) {
            ping(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_COUNTER)) {
            stats.incQueryRequestCount();
            getCounters(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_METRICGROUP)) {
            stats.incQueryRequestCount();
            getMetrics(request, pathInfo, response);
        } else {
            stats.incInvalidRequestCount();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (Throwable ex) {
        String requestTxt = readRequest(request);
        stats.setLastFailedRequest(readRequestHead(request) + requestTxt);
        stats.registerError(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "*");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    }
}

From source file:com.kenlin.awsec2offering.App.java

@RequestMapping(method = RequestMethod.GET)
@ResponseBody/*from   w  w w  .j  a v a 2  s  .  c  o m*/
public JsonNode klugeForSingleBeanstalkWAR(HttpServletRequest req, HttpServletResponse resp) {
    //System.out.println("in klugeForSingleBeanstalkWAR - getPathInfo = " + req.getPathInfo());
    final int start = 1; // e.g., path == "/api/us-east-1a"
    String parts[] = req.getPathInfo().split("/");

    String availabilityZone = (parts.length >= start + 1) ? parts[start + 0] : AVAILABILITYZONE_DEFAULT;
    String productDescription = (parts.length >= start + 2) ? parts[start + 1] : PRODUCTDESCRIPTION_DEFAULT;
    String offeringType = (parts.length >= start + 3) ? parts[start + 2] : OFFERINGTYPE_DEFAULT;
    String instanceType = (parts.length >= start + 4) ? parts[start + 3] : INSTANCETYPE_DEFAULT;

    if (instanceType != null && instanceType.endsWith("."))
        instanceType = instanceType.substring(0, instanceType.length() - 1);

    return getOfferings(availabilityZone, productDescription, offeringType, instanceType, req, resp);
}

From source file:com.ebay.pulsar.collector.servlet.IngestServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletInputStream inputStream = request.getInputStream();
    if (inputStream != null) {
        inputStream.mark(Integer.MAX_VALUE);
    }/*  w  w  w.j  a  va2s .  co  m*/
    try {
        String pathInfo = request.getPathInfo();
        if (pathInfo.startsWith(PATH_INGEST)) {
            stats.incIngestRequestCount();
            add(request, pathInfo, response);
        } else if (pathInfo.startsWith(PATH_BATCH_INGEST)) {
            stats.incBatchIngestRequestCount();
            batchAdd(request, pathInfo, response);
        } else {
            stats.incInvalidRequestCount();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (Throwable ex) {
        String requestTxt = readRequest(request);
        stats.setLastFailedRequest(readRequestHead(request) + requestTxt);
        stats.registerError(ex);
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}

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

@Secured({ "ROLE_ADMIN" })
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
public String delete(@PathVariable("id") Long id, Principal principal, Model uiModel,
        HttpServletRequest httpServletRequest) {
    log.info("delete(): id=" + id);
    try {/* w ww .  j  av a2  s.  c om*/
        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";
        }
        surveySettingsService.sector_remove(id);
        return "redirect:/admin/sectors";
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }
}