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:be.fedict.eid.dss.webapp.ProtocolEntryServlet.java

@Override
protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    LOG.debug("handle request");
    LOG.debug("request URI: " + request.getRequestURI());
    LOG.debug("request method: " + request.getMethod());
    LOG.debug("request path info: " + request.getPathInfo());
    LOG.debug("request context path: " + request.getContextPath());
    LOG.debug("request query string: " + request.getQueryString());
    LOG.debug("request path translated: " + request.getPathTranslated());
    String protocolServiceContextPath = request.getPathInfo();
    HttpSession httpSession = request.getSession();
    storeProtocolServiceContextPath(protocolServiceContextPath, httpSession);

    DSSProtocolService dssProtocolService = super.findProtocolService(protocolServiceContextPath);
    if (null == dssProtocolService) {
        LOG.warn("unsupported protocol: " + protocolServiceContextPath);
        response.sendRedirect(request.getContextPath() + this.unknownProtocolPageInitParam);
        return;// w  w  w.j  a  va 2  s  .  c o  m
    }

    DSSRequest dssRequest;
    try {
        dssRequest = dssProtocolService.handleIncomingRequest(request, response);
    } catch (Exception e) {
        error(request, response, e.getMessage(), e);
        return;
    }

    // try to identify a RP from the domain
    LOG.debug("DSS Request domain: " + dssRequest.getDomain());
    RPEntity rp = this.rpService.find(dssRequest.getDomain());
    if (null != rp) {

        if (!isValid(rp, dssRequest, request, response)) {
            return;
        }

    }

    // get document data, either from artifact map or direct
    byte[] documentData;
    String contentType;
    if (null != dssRequest.getDocumentId()) {

        DocumentEntity document = this.documentService.find(dssRequest.getDocumentId());
        if (null == document) {
            error(request, response, "Document not found!", null);
            return;
        }
        documentData = document.getData();
        contentType = document.getContentType();

    } else {
        documentData = dssRequest.getDocumentData();
        contentType = dssRequest.getContentType();
    }

    if (null == documentData || null == contentType) {
        error(request, response, "No document data or content type found.", null);
        return;
    }

    DocumentRepository documentRepository = new DocumentRepository(httpSession);

    // store artifact if specified for later
    if (null != dssRequest.getDocumentId()) {
        documentRepository.setDocumentId(dssRequest.getDocumentId());
    }

    /*
     * Check the document format.
     */
    LOG.debug("document content type: " + contentType);
    documentRepository.setDocumentContentType(contentType);
    DSSDocumentService documentService = super.findDocumentService(contentType);
    if (null == documentService) {
        LOG.debug("no document service found for content type: " + contentType);
        documentRepository.setSignatureStatus(SignatureStatus.FILE_FORMAT);
        response.sendRedirect(request.getContextPath() + this.exitPageInitParam);
        return;
    }
    try {
        documentService.checkIncomingDocument(documentData);
    } catch (Exception e) {
        LOG.debug("document verification error: " + e.getMessage(), e);
        documentRepository.setSignatureStatus(SignatureStatus.FILE_FORMAT);
        response.sendRedirect(request.getContextPath() + this.exitPageInitParam);
        return;
    }

    /*
     * Store the relevant data into the HTTP session document repository.
     */
    documentRepository.setDocument(documentData);

    /*
     * i18n
     */
    String language = dssRequest.getLanguage();
    if (null != language) {
        httpSession.setAttribute(View.LANGUAGE_SESSION_ATTRIBUTE, language);
    } else {
        httpSession.removeAttribute(View.LANGUAGE_SESSION_ATTRIBUTE);
    }

    // accounting
    accountingService.addRequest(dssRequest.getDomain());

    /*
     * Goto the next eID DSS page.
     */
    response.sendRedirect(request.getContextPath() + this.nextPageInitParam);
}

From source file:com.bosch.iot.things.tutorial.ui.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from   ww  w .j  av  a  2s . c om*/
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(Base64.getDecoder().decode(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.palantir.stash.disapprove.servlet.DisapprovalServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    final String user = authenticateUser(req, res);
    if (user == null) {
        // not logged in, redirect
        res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString());
        return;/*from  www.j  a v a  2s.  co  m*/
    }

    final String URL_FORMAT = "BASE_URL/REPO_ID";
    final String pathInfo = req.getPathInfo();
    final String[] parts = pathInfo.split("/");

    if (parts.length != 5) {
        throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT);
    }

    final Integer repoId;
    final Long prId;
    try {
        repoId = Integer.valueOf(parts[3]);
        prId = Long.valueOf(parts[4]);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("The format of the URL is " + URL_FORMAT, e);
    }

    final PullRequest pr = pullRequestService.getById(repoId, prId);
    if (pr == null) {
        throw new IllegalArgumentException("No PR found for repo id " + repoId + " pr id " + prId.toString());
    }

    PullRequestDisapproval prd;
    DisapprovalConfiguration dc;
    try {
        prd = pm.getPullRequestDisapproval(pr);
        dc = pm.getDisapprovalConfiguration(pr.getToRef().getRepository());
    } catch (SQLException e) {
        throw new ServletException(e);
    }

    try {
        Writer w = res.getWriter();
        //res.setContentType("text/html;charset=UTF-8");
        res.setContentType("application/json;charset=UTF-8");
        w.append(new JSONObject(ImmutableMap.of("disapproval", prd.isDisapproved(), "disapprovedBy",
                prd.getDisapprovedBy(), "enabledForRepo", dc.isEnabled())).toString());
    } finally {
        res.getWriter().close();
    }
}

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

@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String mediaType = StringUtils.trimToNull(request.getContentType());
    String encoding = StringUtils.trimToNull(request.getCharacterEncoding());
    String pathInfo = StringUtils.trimToNull(request.getPathInfo());
    Curator curator = loadCurator(request);

    if (mediaType != null && mediaType.indexOf(';') > 0) {
        mediaType = mediaType.substring(0, mediaType.indexOf(';'));
    }/*ww  w.j  a v a 2s  . c  om*/

    if (!StringUtils.equalsIgnoreCase(mediaType, MEDIA_TYPE_OBO)
            || !StringUtils.equalsIgnoreCase(encoding, "utf-8")) {
        log("Failed to import ontology: invalid media type or encoding " + mediaType + ";charset=" + encoding);
        response.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
    } else if (pathInfo == null || pathInfo.length() <= 1) {
        log("Failed to import ontology: ontology name not include in path");
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    } else if (curator == null) {
        log("Failed to import ontology: curator not found in request");
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
    } else {
        try {
            String ontologyName = pathInfo.substring(1);
            importService.importOntology(ontologyName, request.getInputStream(), curator);
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "public, max-age=0");
        } catch (DuplicateEntityException e) {
            log("Failed to import ontology: duplicate term", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidEntityException e) {
            log("Failed to import ontology: invalid entity", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (InvalidFormatException e) {
            log("Failed to import ontology: invalid format", e);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (Exception e) {
            log("Failed to import ontology: system error", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }
    response.setContentLength(0);
}

From source file:com.thinkberg.webdav.PropFindHandler.java

/**
 * Handle a PROPFIND request./*from ww w  . j a  v  a2s.  c  o m*/
 *
 * @param request  the servlet request
 * @param response the servlet response
 * @throws IOException if there is an error that cannot be handled normally
 */
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    SAXReader saxReader = new SAXReader();
    try {
        Document propDoc = saxReader.read(request.getInputStream());
        logXml(propDoc);

        Element propFindEl = propDoc.getRootElement();
        for (Object propElObject : propFindEl.elements()) {
            Element propEl = (Element) propElObject;
            if (VALID_PROPFIND_TAGS.contains(propEl.getName())) {
                FileObject object = VFSBackend.resolveFile(request.getPathInfo());
                if (object.exists()) {
                    // respond as XML encoded multi status
                    response.setContentType("text/xml");
                    response.setCharacterEncoding("UTF-8");
                    response.setStatus(SC_MULTI_STATUS);

                    Document multiStatusResponse = getMultiStatusResponse(object, propEl, getBaseUrl(request),
                            getDepth(request));
                    logXml(multiStatusResponse);

                    // write the actual response
                    XMLWriter writer = new XMLWriter(response.getWriter(), OutputFormat.createCompactFormat());
                    writer.write(multiStatusResponse);
                    writer.flush();
                    writer.close();

                } else {
                    response.sendError(HttpServletResponse.SC_NOT_FOUND);
                }
                break;
            }
        }
    } catch (DocumentException e) {
        LOG.error("invalid request: " + e.getMessage());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    }
}

From source file:uk.ac.ebi.phenotype.web.proxy.ExternalUrlConfiguratbleProxyServlet.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// www.j  a v a 2 s .  com
        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(this.targetUri.toString().length());
    }
    return theUrl;
}

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

private void doGetUnchecked(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String path;//from ww  w. j a  v  a  2 s .  co m

    path = request.getPathInfo();
    if (path == null) {
        response.sendRedirect(request.getContextPath() + request.getServletPath() + "/");
        return;
    }
    lazyInit(request);
    LOG.debug("get " + path);
    if (path.startsWith("/get/")) {
        get(request, response, path.substring(5));
        return;
    }
    if (path.equals("/admin/")) {
        main(response);
        return;
    }
    if (path.equals("/admin/repository")) {
        repository(request, response);
        return;
    }
    if (path.equals("/admin/hashCache")) {
        hashCache(response);
        return;
    }
    if (path.equals("/admin/contentCache")) {
        contentCache(response);
        return;
    }
    if (path.startsWith(MODULE_PREFIX)) {
        module(request, response, path.substring(MODULE_PREFIX.length()));
        return;
    }
    if (path.equals("/admin/reload")) {
        reload(response);
        return;
    }
    if (path.equals("/admin/check")) {
        fileCheck(response);
        return;
    }
    notFound(request, response);
}

From source file:com.bosch.cr.integration.helloworld.ProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//  w  w w .  j  a v a 2 s. c o m
    }

    try {
        long time = System.currentTimeMillis();
        CloseableHttpClient c = getHttpClient();

        String targetUrl = URL_PREFIX + req.getPathInfo()
                + (req.getQueryString() != null ? ("?" + req.getQueryString()) : "");
        BasicHttpRequest targetReq = new BasicHttpRequest(req.getMethod(), targetUrl);

        String user = "";
        if (auth.toUpperCase().startsWith("BASIC ")) {
            String userpassDecoded = new String(
                    new sun.misc.BASE64Decoder().decodeBuffer(auth.substring("BASIC ".length())));
            user = userpassDecoded.substring(0, userpassDecoded.indexOf(':'));
            String pass = userpassDecoded.substring(userpassDecoded.indexOf(':') + 1);
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);
            targetReq.addHeader(new BasicScheme().authenticate(creds, targetReq, null));
        }

        targetReq.addHeader("x-cr-api-token", req.getHeader("x-cr-api-token"));
        CloseableHttpResponse targetResp = c.execute(targetHost, targetReq);

        System.out.println("Request: " + targetHost + targetUrl + ", user " + user + " -> "
                + (System.currentTimeMillis() - time) + " msec: " + targetResp.getStatusLine());

        resp.setStatus(targetResp.getStatusLine().getStatusCode());
        targetResp.getEntity().writeTo(resp.getOutputStream());
    } catch (IOException | AuthenticationException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.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  va2  s .  co  m*/
 */
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    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
    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(encodeUriQuery(queryString));
    }

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