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.palantir.stash.disapprove.servlet.StaticContentServlet.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   w w  w.  ja v  a  2 s.  co m*/
    }

    final String pathInfo = req.getPathInfo();
    OutputStream os = null;
    try {
        // The class loader that found this class will also find the static resources
        ClassLoader cl = this.getClass().getClassLoader();
        InputStream is = cl.getResourceAsStream(PREFIX + pathInfo);
        if (is == null) {
            res.sendError(404, "File " + pathInfo + " could not be found");
            return;
        }
        os = res.getOutputStream();
        //res.setContentType("text/html;charset=UTF-8");
        String contentType = URLConnection.guessContentTypeFromStream(is);
        if (contentType == null) {
            contentType = URLConnection.guessContentTypeFromName(pathInfo);
        }
        if (contentType == null) {
            contentType = "application/binary";
        }
        log.debug("Serving file " + pathInfo + " with content type " + contentType);
        res.setContentType(contentType);
        IOUtils.copy(is, os);
        /*
        byte[] buffer = new byte[4096];
        int bytesRead = 0;
        while ((bytesRead = bis.read(buffer)) != -1) {
        os.write(buffer, 0, bytesRead);
        }
        */
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

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

/**
 * The get method get resources of a produced report
 * Urls in this case look like /reports/samples/myreport;uniqueidentifier?file=filename
 *///from w  w  w. ja  v  a 2s . co m
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    // Get the uri of the resource
    String uuid = restUtils.extractRepositoryUri(req.getPathInfo());

    if (uuid.startsWith("/"))
        uuid = uuid.substring(1);

    // Add all the options...
    Map<String, String> options = new HashMap<String, String>();
    // Add as option all the GET parameters...
    Enumeration en = req.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        options.put(key, req.getParameter(key));
    }

    // Find the report in session...
    HttpSession session = req.getSession();
    Report report = (Report) session.getAttribute(uuid);

    if (report == null) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp,
                "Report not found (uuid not found in session)");
        return;
    }

    JasperPrint jp = report.getJasperPrint();

    // highcharts report for REST v1 is by default noninteractive.
    if (!options.containsKey(Argument.PARAM_INTERACTIVE)) {
        options.put(Argument.PARAM_INTERACTIVE, Boolean.FALSE.toString());
    }

    OperationResult or = runReportService.exportReport(report.getOriginalUri(), jp, options,
            report.getAttachments());

    if (or.getReturnCode() != 0) {
        restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, or.getMessage());
        return;
    } else {
        // If the jasperprint is present as attribute, it means it has been modified
        // in some way (i.e. using a RUN_TRANSFORMER_KEY).
        if (runReportService.getAttributes().get("jasperPrint") != null) {
            jp = (JasperPrint) runReportService.getAttributes().get("jasperPrint");
            report.setJasperPrint(jp);
        }

        // Send out the xml...
        resp.setContentType("text/xml; charset=UTF-8");
        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, report.toXml());
    }
}

From source file:com.neelo.glue.ApplicationModule.java

public RequestResolution resolve(Lifecycle lifecycle) throws ResolutionException {
    HttpServletRequest request = lifecycle.getRequest();
    HttpMethod method = HttpMethod.valueOf(request.getMethod());

    // TODO: These two lines depend on the servlet mapping (/app/*, /)
    // String path =
    // request.getRequestURI().substring(request.getContextPath().length());
    String path = request.getPathInfo();
    path = StringUtils.removeEnd(path, FORWARD_SLASH);

    for (Route route : routes) {
        if (!method.equals(route.getHttpMethod()))
            continue;

        if (StringUtils.isBlank(path) && StringUtils.isBlank(route.getFullPath()))
            return new RequestResolution(route, EMPTY_PARAMETERS);

        NamedPattern np = NamedPattern.compile(route.getFullPath());
        NamedMatcher nm = np.matcher(path);

        List<String> names = np.groupNames();

        if (nm.matches()) {
            if (names.size() > 0) {
                List<Parameter> params = new ArrayList<Parameter>();
                for (String name : names) {
                    params.add(new Parameter(name, nm.group(name)));
                }/*from   w  w w.j  a v a2s.  c o m*/
                return new RequestResolution(route, params);
            }
            return new RequestResolution(route, EMPTY_PARAMETERS);
        }
    }

    throw new ResolutionException(404, "Resource not found @ " + path);
}

From source file:grails.plugin.springsecurity.web.filter.DebugFilter.java

public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
        throws ServletException, IOException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    List<Filter> filters = getFilters(request);
    log(false, "Request received for '{}':\n\n{}\n\nservletPath:{}\npathInfo:{}\n\n{}",
            UrlUtils.buildRequestUrl(request), request, request.getServletPath(), request.getPathInfo(),
            formatFilters(filters));/*from  w  w  w  .  j  a va 2s.  c o m*/

    if (request.getAttribute(ALREADY_FILTERED_ATTR_NAME) == null) {
        invokeWithWrappedRequest(request, response, filterChain);
    } else {
        filterChainProxy.doFilter(request, response, filterChain);
    }
}

From source file:org.killbill.billing.plugin.avatax.core.AvaTaxServlet.java

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Tenant tenant = getTenant(req);
    if (tenant == null) {
        buildNotFoundResponse("No tenant specified", resp);
        return;//  www  . java2  s.  c  om
    }

    final String pathInfo = req.getPathInfo();
    final Matcher matcher = TAX_CODES_PATTERN.matcher(pathInfo);
    if (matcher.matches()) {
        addTaxCode(tenant, req, resp);
    } else {
        buildNotFoundResponse("Resource " + pathInfo + " not found", resp);
    }
}

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

protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//w  w  w  .  ja  v  a2 s.com
        WSUserSearchCriteria c = restUtils.getWSUserSearchCriteria(getUserSearchInformation(req.getPathInfo()));

        WSUser userToDelete = new WSUser();
        userToDelete.setUsername(c.getName());
        userToDelete.setTenantId(c.getTenantId());

        if (isLoggedInUser(restUtils.getCurrentlyLoggedUser(), userToDelete)) {
            throw new ServiceException(HttpServletResponse.SC_FORBIDDEN,
                    "user: " + userToDelete.getUsername() + " can not to delete himself");
        } else if (validateUserForGetOrDelete(userToDelete)) {
            if (isAlreadyAUser(userToDelete)) {
                userAndRoleManagementService.deleteUser(userToDelete);
            } else {
                throw new ServiceException(HttpServletResponse.SC_NOT_FOUND,
                        "user: " + userToDelete.getUsername() + " was not found");
            }
        } else {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check request parameters");
        }
        if (log.isDebugEnabled()) {
            log.debug(userToDelete.getUsername() + " was deleted");
        }

        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, e.getLocalizedMessage());
    }
}

From source file:org.eclipse.virgo.snaps.core.internal.webapp.StaticResourceServlet.java

/** 
 * {@inheritDoc}//from  ww w.  j  a va 2s .  c o  m
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // As an alternative of the Tomcat's escaping utility we can use one of the following libraries:
    // - org.springframework.web.util.HtmlUtils.htmlEscape(String)
    // - org.apache.commons.lang3.StringEscapeUtils.escapeHtml4(String)
    String pathInfo = RequestUtil.filter(request.getPathInfo());
    try {
        URL resource = getServletContext().getResource(pathInfo);
        if (resource == null) {
            logger.warn("Resource {} not found", pathInfo);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource '" + pathInfo + "' not found.");
        } else {
            logger.info("Resource {} found", pathInfo);
            InputStream input = null;
            try {
                input = new BufferedInputStream(resource.openStream());
                OutputStream output = response.getOutputStream();
                byte[] buffer = new byte[4096];
                int len;
                while ((len = input.read(buffer)) > 0) {
                    output.write(buffer, 0, len);
                }
                output.flush();
            } finally {
                if (input != null) {
                    IOUtils.closeQuietly(input);
                }
            }
        }
    } catch (MalformedURLException e) {
        logger.error(String.format("Malformed servlet path %s", pathInfo), e);
        throw new ServletException("Malformed servlet path " + pathInfo, e);
    }
}

From source file:org.killbill.billing.plugin.avatax.core.AvaTaxServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Tenant tenant = getTenant(req);
    if (tenant == null) {
        buildNotFoundResponse("No tenant specified", resp);
        return;/*from  w w  w  . ja  va 2 s .  co m*/
    }

    final String pathInfo = req.getPathInfo();
    final Matcher matcher = TAX_CODES_PATTERN.matcher(pathInfo);
    if (matcher.matches()) {
        final String productName = matcher.group(2);
        if (productName == null) {
            getTaxCodes(tenant, resp);
        } else {
            getTaxCode(productName, tenant, resp);
        }
    } else {
        buildNotFoundResponse("Resource " + pathInfo + " not found", resp);
    }
}

From source file:org.killbill.billing.plugin.avatax.core.AvaTaxServlet.java

@Override
protected void doDelete(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Tenant tenant = getTenant(req);
    if (tenant == null) {
        buildNotFoundResponse("No tenant specified", resp);
        return;//from  ww  w  . j  ava 2 s.c  om
    }

    final String pathInfo = req.getPathInfo();
    final Matcher matcher = TAX_CODES_PATTERN.matcher(pathInfo);
    if (matcher.matches()) {
        final String productName = matcher.group(2);
        if (productName != null) {
            deleteTaxCode(productName, tenant, resp);
        } else {
            buildNotFoundResponse("Resource " + pathInfo + " not found", resp);
        }
    } else {
        buildNotFoundResponse("Resource " + pathInfo + " not found", resp);
    }
}

From source file:com.sap.dirigible.runtime.registry.RegistryServlet.java

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

    String repositoryPath = null;
    final String requestPath = request.getPathInfo();
    boolean deep = false;
    if (requestPath == null) {
        deep = true;//from  w w  w .  ja  v a2s  .  co  m
    }
    final OutputStream out = response.getOutputStream();
    try {
        repositoryPath = extractRepositoryPath(request);
        final IEntity entity = getEntity(repositoryPath, request);
        byte[] data;
        if (entity != null) {
            if (entity instanceof IResource) {
                data = buildResourceData(entity, request, response);
            } else if (entity instanceof ICollection) {
                String collectionPath = request.getRequestURI().toString();
                String acceptHeader = request.getHeader(ACCEPT_HEADER);
                if (acceptHeader != null && acceptHeader.contains(JSON)) {
                    if (!collectionPath.endsWith(IRepository.SEPARATOR)) {
                        collectionPath += IRepository.SEPARATOR;
                    }
                    data = buildCollectionData(deep, entity, collectionPath);
                } else {
                    // welcome file support
                    IResource index = ((ICollection) entity).getResource(INDEX_HTML);
                    if (index.exists() && (collectionPath.endsWith(IRepository.SEPARATOR))) {
                        data = buildResourceData(index, request, response);
                    } else {
                        // listing of collections is forbidden
                        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                                LISTING_OF_FOLDERS_IS_FORBIDDEN);
                        return;
                    }
                }
            } else {
                exceptionHandler(response, repositoryPath, HttpServletResponse.SC_FORBIDDEN,
                        LISTING_OF_FOLDERS_IS_FORBIDDEN);
                return;
            }
        } else {
            exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NOT_FOUND,
                    String.format("Resource at [%s] does not exist", requestPath));
            return;
        }

        if (entity instanceof IResource) {
            final IResource resource = (IResource) entity;
            String mimeType = null;
            String extension = ContentTypeHelper.getExtension(resource.getName());
            if ((mimeType = ContentTypeHelper.getContentType(extension)) != null) {
                response.setContentType(mimeType);
            } else {
                response.setContentType(resource.getContentType());
            }
        }
        sendData(out, data);
    } catch (final IllegalArgumentException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_BAD_REQUEST, ex.getMessage());
    } catch (final MissingResourceException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_NO_CONTENT, ex.getMessage());
    } catch (final RuntimeException ex) {
        exceptionHandler(response, repositoryPath, HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                ex.getMessage());
    } finally {
        out.flush();
        out.close();
    }
}