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.atlassian.jira.web.dispatcher.JiraWebworkActionDispatcher.java

private String getDestinationUrl(HttpServletRequest httpServletRequest) {
    return JiraUrlCodec.encode(httpServletRequest.getServletPath()
            + (httpServletRequest.getPathInfo() == null ? "" : httpServletRequest.getPathInfo())
            + (httpServletRequest.getQueryString() == null ? "" : "?" + httpServletRequest.getQueryString()));
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);//from   w  ww.ja  v a 2 s  . co m
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:de.mpg.mpdl.inge.syndication.presentation.RestServlet.java

/**
 * {@inheritDoc}/*w w w . j a  v  a  2  s.c om*/
 */
@Override
protected final void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String url = null;
    try {
        url = PropertyReader.getProperty("escidoc.syndication.service.url") + req.getServletPath()
                + req.getPathInfo();
    } catch (Exception e) {
        handleException(e, resp);
    }
    String q = req.getQueryString();

    if (Utils.checkVal(q)) {
        url += "?" + q;
    }

    Feed feed = synd.getFeeds().matchFeedByUri(url);

    // set correct mime-type
    resp.setContentType("application/" + (url.contains("rss_") ? "rss" : "atom") + "+xml; charset=utf-8");

    // cache handling
    String ttl = feed.getCachingTtl();

    if (Utils.checkVal(ttl)) {
        long ttlLong = Long.parseLong(ttl) * 1000L;
        resp.setHeader("control-cache", "max-age=" + ttl + ", must-revalidate");

        DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
        df.setTimeZone(TimeZone.getTimeZone("GMT"));
        resp.setHeader("Expires", df.format(new Date(System.currentTimeMillis() + ttlLong)));
    }

    try {
        synd.getFeed(url, resp.getWriter());
    } catch (SyndicationException e) {
        handleException(e, resp);
    } catch (URISyntaxException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong URI syntax: " + url);
        return;
    } catch (FeedException e) {
        handleException(e, resp);
    }

}

From source file:org.dspace.app.webui.cris.controller.jdyna.CrisFileServiceController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {// w  ww.  ja  v a2  s .com
        return super.handleRequest(request, response);
    } catch (RuntimeException ex) {
        JSPManager.showJSP(request, response, "/error/404.jsp");
        return null;
    } finally {

        String idString = request.getPathInfo();
        String[] pathInfo = idString.split("/", 4);
        String folder = pathInfo[3];

        int indexOf = folder.indexOf("/");
        String id = folder.substring(0, indexOf);
        String idTP = folder.substring((indexOf + 1), folder.length() - 1);
        TP tp = applicationService.get(getTargetPropertyDefinition(), Integer.parseInt(idTP));
        if (tp.getRendering() instanceof AWidgetFileCris) {
            AWidgetFileCris widget = (AWidgetFileCris) tp.getRendering();
            // Fire usage event.
            if (widget.isUseInStatistics()) {
                request.setAttribute("sectionid", tp.getId());
                new DSpace().getEventService().fireEvent(
                        new UsageEvent(UsageEvent.Action.VIEW, request, UIUtil.obtainContext(request),
                                applicationService.getEntityByCrisId(id, getTargetObject())));
            }
        }

    }

}

From source file:com.sonicle.webtop.core.app.servlet.DocEditor.java

protected void processRequestAsAdmin(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    DomainURIPath path = new DomainURIPath(URIUtils.removeTrailingSeparator(request.getPathInfo()));
    WebTopApp wta = WebTopApp.get(request);
    DocEditorManager docEdMgr = wta.getDocEditorManager();

    String domainId = WT.findDomainIdByPublicName(path.getDomainPublicName());
    if (domainId == null)
        throw new WTServletException("Invalid domain public name [{0}]", path.getDomainPublicName());
    if (!wta.getDocumentServerEnabled(domainId))
        throw new WTServletException("DocumentServer not enabled for domain [{}]", domainId);

    String remainingPath = path.getRemainingPath();
    if (StringUtils.equalsIgnoreCase(remainingPath, DOWNLOAD_PATH)) {
        String editingId = ServletUtils.getStringParameter(request, EDITING_ID_PARAM, true);

        BaseDocEditorDocumentHandler docHandler = docEdMgr.getDocumentHandler(editingId);
        if (docHandler == null)
            throw new WTServletException("Missing DocumentHandler [{}]", editingId);

        ServletUtils.setContentTypeHeader(response, "application/octet-stream");
        IOUtils.copy(docHandler.readDocument(), response.getOutputStream());

    } else if (StringUtils.equalsIgnoreCase(remainingPath, TRACK_PATH)) {
        String editingId = ServletUtils.getStringParameter(request, EDITING_ID_PARAM, true);
        Payload<MapItem, DocEditorCallbackPayload> payload = ServletUtils.getPayload(request,
                DocEditorCallbackPayload.class);

        if (payload.data.status == 1) {
            logger.debug("Document is being edited [{}, {}]", editingId, payload.data.key);

            ServletUtils.writeJsonResponse(response, new DocEditorCallbackResponse(0));

        } else if ((payload.data.status == 2) || (payload.data.status == 6)) {
            BaseDocEditorDocumentHandler docHandler = docEdMgr.getDocumentHandler(editingId);
            if (docHandler == null)
                throw new WTServletException("Missing DocumentHandler [{}]", editingId);

            if (payload.data.status == 2) {
                logger.debug("Document is ready for saving [{}, {}]", editingId, payload.data.key);
            } else if (payload.data.status == 6) {
                logger.debug("Document is being edited, but the current document state is saved [{}, {}]",
                        editingId, payload.data.key);
            }//from   w ww .  j a  va  2 s. c  o  m
            if (!docHandler.isWriteSupported())
                throw new WTServletException("Write is not supported here [{}]", editingId);

            URI url = URIUtils.createURIQuietly(payload.data.url);
            if (url == null)
                throw new WTServletException("Invalid URL [{}]", payload.data.url);

            /*
            if (true) {
               long lastModified = docHandler.getLastModifiedTime();
               if (lastModified != -1) {
                  String key = docEdMgr.buildDocumentKey(docHandler.getDocumentUniqueId(), lastModified);
                  if (!StringUtils.equals(payload.data.key, key)) {
             throw new WTServletException("Original file was modified outside this session [{}]", editingId);
                  }
               }
            }
            */

            InputStream is = null;
            try {
                HttpClient httpCli = HttpClientUtils
                        .createBasicHttpClient(HttpClientUtils.configureSSLAcceptAll(), url);
                is = HttpClientUtils.getContent(httpCli, url);
                docHandler.writeDocument(is);
            } catch (IOException ex) {
                throw new WTServletException("Unable to save edited content [{}]", editingId, ex);
            } finally {
                IOUtils.closeQuietly(is);
            }

            //UserProfileId profileId = new UserProfileId(payload.data.users.get(0));
            if (payload.data.status == 2) {
                docEdMgr.unregisterDocumentHandler(editingId);
            }
            ServletUtils.writeJsonResponse(response, new DocEditorCallbackResponse(0));

        } else if ((payload.data.status == 3) || (payload.data.status == 7)) {
            if (payload.data.status == 3) {
                logger.error("Document saving error has occurred [{}, {}]", editingId, payload.data.key);
                logger.error("Changes URL: {}", payload.data.changesurl);

            } else if (payload.data.status == 7) {
                logger.error("Error has occurred while force saving the document [{}, {}]", editingId,
                        payload.data.key);
            }
            docEdMgr.unregisterDocumentHandler(editingId);
            ServletUtils.writeJsonResponse(response, new DocEditorCallbackResponse(0));

        } else if (payload.data.status == 4) {
            logger.debug("Document is closed with no changes [{}, {}]", editingId, payload.data.key);
            docEdMgr.unregisterDocumentHandler(editingId);
            ServletUtils.writeJsonResponse(response, new DocEditorCallbackResponse(0));
        }
    }
}

From source file:com.novartis.pcs.ontology.rest.servlet.TermsServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = getExpectedMediaType(request);
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    if (mediaType == null || !MEDIA_TYPE_JSON.equals(mediaType)) {
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        response.setContentLength(0);/*w w w  .ja  v a2  s  .c  om*/
    } else if (pathInfo != null && pathInfo.length() > 1) {
        String referenceId = pathInfo.substring(1);
        serialize(referenceId, response);
    } else {
        // perform search using query string params
        String name = StringUtils.trimToNull(request.getParameter("name"));
        String ontology = StringUtils.trimToNull(request.getParameter("ontology"));
        boolean includeSynonyms = Boolean.parseBoolean(request.getParameter("synonyms"));
        int maxResults = Integer.MAX_VALUE;

        try {
            maxResults = Integer.parseInt(request.getParameter("max"));
            if (maxResults <= 0) {
                maxResults = Integer.MAX_VALUE;
            }
        } catch (Exception e) {
            maxResults = Integer.MAX_VALUE;
        }

        serialize(name, ontology, includeSynonyms, maxResults, response);
    }
}

From source file:ch.entwine.weblounge.kernel.endpoint.SitesEndpoint.java

/**
 * Returns the endpoint documentation./*from  www. j  a  v a 2s .c om*/
 * 
 * @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 = SitesEndpointDocs.createDocumentation(servicePath);
    }
    return docs;
}

From source file:es.tid.cep.esperanza.Rules.java

/**
 * Handles the HTTP <code>DELETE</code> method.
 *
 * @param request servlet request//from   w w  w  . j a  va2  s  . c  o  m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    response.setContentType("application/json;charset=UTF-8");
    try {
        String ruleName = request.getPathInfo();
        ruleName = ruleName == null ? "" : ruleName.substring(1);
        logger.debug("rule asked for " + ruleName);
        EPAdministrator epa = epService.getEPAdministrator();

        if (ruleName.length() != 0) {
            EPStatement st = epa.getStatement(ruleName);
            if (st == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                out.printf("{\"error\":\"%s not found\"}\n", ruleName);
            } else {
                st.destroy();
                out.println(Utils.Statement2JSONObject(st));
            }
        } else {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            out.println("{\"error\":\"not rule specified for deleting\"}");
        }

    } catch (EPException epe) {
        logger.error("deleting statement", epe);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        out.printf("{\"error\":%s}\n", JSONObject.valueToString(epe.getMessage()));
    } finally {
        out.close();
    }
}

From source file:ShoppingCartViewerRewrite.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");
    out.println("<BODY>");

    // Get the current session ID, or generate one if necessary
    String sessionid = req.getPathInfo();
    if (sessionid == null) {
        sessionid = generateSessionId();
    }/*from w ww.  j a  v  a2s . co m*/

    // Cart items are associated with the session ID
    String[] items = getItemsFromCart(sessionid);

    // Print the current cart items.
    out.println("You currently have the following items in your cart:<BR>");
    if (items == null) {
        out.println("<B>None</B>");
    } else {
        out.println("<UL>");
        for (int i = 0; i < items.length; i++) {
            out.println("<LI>" + items[i]);
        }
        out.println("</UL>");
    }

    // Ask if the user wants to add more items or check out.
    // Include the session ID in the action URL.
    out.println("<FORM ACTION=\"/servlet/ShoppingCart/" + sessionid + "\" METHOD=POST>");
    out.println("Would you like to<BR>");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
    out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");
    out.println("</FORM>");

    // Offer a help page. Include the session ID in the URL.
    out.println("For help, click <A HREF=\"/servlet/Help/" + sessionid
            + "?topic=ShoppingCartViewerRewrite\">here</A>");

    out.println("</BODY></HTML>");
}

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.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])+(.)+")) {
        String target = "http://" + servletRequest.getPathInfo().substring(7);
        servletRequest.setAttribute(ATTR_TARGET_URI, target);
        uri.append(target);//  w ww. j  a v  a  2 s  .  co m
    } 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();
}