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.openkm.servlet.CssServlet.java

/**
 * //from w w w . ja va 2 s .  c o m
 */
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String path = request.getPathInfo();
    OutputStream os = null;

    try {
        if (path.length() > 1) {
            String[] foo = path.substring(1).split("/");

            if (foo.length > 1) {
                String context = foo[0];
                String name = foo[1];
                Css css = CssDAO.getInstance().findByContextAndName(context, name);

                if (css == null) {
                    InputStream is = null;

                    try {
                        if (Css.CONTEXT_FRONTEND.equals(context)) {

                        } else if (Css.CONTEXT_EXTENSION.equals(context)) {
                            if ("htmlEditor".equals(name)) {
                                is = getServletContext().getResourceAsStream("/css/tiny_mce/content.css");
                            }
                        }

                        if (is != null) {
                            css = new Css();
                            css.setContent(IOUtils.toString(is));
                            css.setContext(context);
                            css.setName(name);
                            css.setActive(true);
                        }
                    } finally {
                        IOUtils.closeQuietly(is);
                    }
                }

                if (css != null) {
                    // Prepare file headers
                    WebUtils.prepareSendFile(request, response, css.getName() + ".css", MimeTypeConfig.MIME_CSS,
                            false);
                    PrintWriter out = new PrintWriter(
                            new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
                    out.append(css.getContent());
                    out.flush();
                }
            }
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:guru.nidi.ramlproxy.core.MockServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    final String pathInfo = req.getPathInfo();
    final int pos = pathInfo.lastIndexOf('/');
    final String path = pathInfo.substring(1, pos + 1);
    final String name = pathInfo.substring(pos + 1);
    final ServletOutputStream out = res.getOutputStream();
    final File targetDir = new File(mockDir, path);
    final File file = findFileOrParent(targetDir, name, req.getMethod());
    CommandDecorators.ALLOW_ORIGIN.set(req, res);
    if (file == null) {
        res.sendError(HttpServletResponse.SC_NOT_FOUND,
                "No or multiple file '" + name + "' found in directory '" + targetDir.getAbsolutePath() + "'");
        return;/* w  w w.  j a v a 2  s.  com*/
    }
    handleMeta(req, res, file.getParentFile(), file.getName());
    res.setContentLength((int) file.length());
    res.setContentType(mineType(file));
    try (final InputStream in = new FileInputStream(file)) {
        copy(in, out);
    } catch (IOException e) {
        res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Problem delivering file '" + file.getAbsolutePath() + "': " + e);
    }
    out.flush();
}

From source file:org.killbill.billing.plugin.payment.retries.PaymentRetriesServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final String pathInfo = req.getPathInfo();

    if (PAYMENT_METHOD_CHECK_PATTERN.matcher(pathInfo).matches()) {
        final String paymentExternalKey = req.getParameter(PAYMENT_EXTERNAL_KEY);

        // Set by the TenantFilter
        final Tenant tenant = (Tenant) req.getAttribute(KILLBILL_TENANT);
        if (tenant == null) {
            resp.sendError(404);/*www. ja v  a  2  s  .  com*/
            return;
        }

        final AuthorizationDeclineCode authorizationDeclineCode = paymentRetriesApi
                .getAuthorizationDeclineCode(paymentExternalKey, tenant.getId());
        if (authorizationDeclineCode == null) {
            resp.sendError(404);
        } else {
            resp.getOutputStream().write(jsonMapper.writeValueAsBytes(authorizationDeclineCode));
            resp.setContentType(APPLICATION_JSON);
        }
    } else if (CONFIGURATION_PATTERN.matcher(pathInfo).matches()) {
        final boolean retryable = Boolean.valueOf(req.getParameter(RETRYABLE));
        final String errorMessage = req.getParameter(ERROR_MESSAGE);

        final Map<String, Map<Integer, AuthorizationDeclineCode>> perPluginDeclineCodes = paymentRetriesApi
                .getPerPluginDeclineCodes();
        final Map<String, Map<Integer, AuthorizationDeclineCode>> returnedMap = new TreeMap<String, Map<Integer, AuthorizationDeclineCode>>();
        for (final String pluginName : perPluginDeclineCodes.keySet()) {
            returnedMap.put(pluginName, Maps.<Integer, AuthorizationDeclineCode>filterValues(
                    perPluginDeclineCodes.get(pluginName), new Predicate<AuthorizationDeclineCode>() {
                        @Override
                        public boolean apply(final AuthorizationDeclineCode authorizationDeclineCode) {
                            return retryable == authorizationDeclineCode.isRetryable()
                                    && (errorMessage == null || authorizationDeclineCode.getErrorMessage()
                                            .name().equalsIgnoreCase(errorMessage));
                        }
                    }));
        }

        resp.getOutputStream().write(jsonMapper.writeValueAsBytes(returnedMap));
        resp.setContentType(APPLICATION_JSON);
    } else {
        resp.sendError(404);
    }
}

From source file:org.ngrinder.security.SvnHttpBasicEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response, // LB
        AuthenticationException authException) throws IOException, ServletException {
    // Get the first part of url path and use it as a realm.
    String pathInfo = request.getPathInfo();
    String[] split = StringUtils.split(pathInfo, '/');
    response.addHeader("WWW-Authenticate",
            "Basic realm=\"" + StringUtils.defaultIfBlank(split[0], "admin") + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
}

From source file:br.com.siprot.framework.servlet.FacesServlet.java

public void service(ServletRequest request, ServletResponse response) throws IOException, ServletException {

    HttpServletRequest httpRequest = ((HttpServletRequest) request);
    String pathInfo = httpRequest.getPathInfo();

    // if it is a prefix mapping ...
    if (pathInfo != null && (pathInfo.startsWith("/WEB-INF") || pathInfo.startsWith("/META-INF"))) {
        StringBuffer buffer = new StringBuffer();

        buffer.append(" Someone is trying to access a secure resource : ").append(pathInfo);
        buffer.append("\n remote address is ").append(httpRequest.getRemoteAddr());
        buffer.append("\n remote host is ").append(httpRequest.getRemoteHost());
        buffer.append("\n remote user is ").append(httpRequest.getRemoteUser());
        buffer.append("\n request URI is ").append(httpRequest.getRequestURI());

        log.warn(buffer.toString());//w  w w .j  ava  2s .  c om

        // Why does RI return a 404 and not a 403, SC_FORBIDDEN ?

        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }

    if (log.isTraceEnabled())
        log.trace("service begin");
    FacesContext facesContext = _facesContextFactory.getFacesContext(_servletConfig.getServletContext(),
            request, response, _lifecycle);
    try {
        _lifecycle.execute(facesContext);
        _lifecycle.render(facesContext);
    } catch (Throwable e) {
        //bloco de tratamento para excecao tratada
        if (e instanceof FacesException) {
            try {
                ErrorHandler.handleException(facesContext, (Exception) e);
                _lifecycle.render(facesContext);
            } catch (Exception ex) {
                throw new ServletException(ex);
            }
        }
        //fim do bloco de  tratamento
        else if (e instanceof IOException) {
            throw (IOException) e;
        } else if (e instanceof ServletException) {
            throw (ServletException) e;
        } else if (e.getMessage() != null) {
            throw new ServletException(e.getMessage(), e);
        } else {
            throw new ServletException(e);
        }
    } finally {
        facesContext.release();
    }
    if (log.isTraceEnabled())
        log.trace("service end");
}

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

@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {//ww w. ja  v a 2 s  .com
        String userName = restUtils.getFullUserName(restUtils.extractResourceName(req.getPathInfo()));
        @SuppressWarnings("unchecked")
        JAXBList<ProfileAttribute> atts = (JAXBList<ProfileAttribute>) restUtils.unmarshal(req.getInputStream(),
                JAXBList.class, ProfileAttributeImpl.class);

        for (int i = 0; i < atts.size(); i++) {
            attributesRemoteService.putAttribute(userName, atts.get(i));
        }

        restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, "");
    } catch (IOException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:org.sakaiproject.imagegallery.web.MultiFileUploaderController.java

public void multiFileUpload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (log.isInfoEnabled())
        log.info("req contextPath=" + request.getContextPath() + ", pathInfo=" + request.getPathInfo()
                + ", query=" + request.getQueryString() + ", URI=" + request.getRequestURI() + ", URL="
                + request.getRequestURL() + ", servlet=" + request.getServletPath());
    if (request instanceof MultipartHttpServletRequest) {
        String newImageId = storeNewImage((MultipartHttpServletRequest) request);
        response.setContentType("text/plain");
        PrintWriter responseWriter = response.getWriter();
        responseWriter.print(newImageId);
        responseWriter.close();//from  w  ww.  j  a v  a2s .com
    }
}

From source file:com.orangeandbronze.jblubble.sample.UploadServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo = request.getPathInfo();
    if (pathInfo == null) {
        pathInfo = "/";
    }//from   ww  w. j av  a2s .  com
    LOGGER.debug("GET {}{}", PATH, pathInfo);
    if ("/create".equals(pathInfo)) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/create.jsp");
        requestDispatcher.forward(request, response);
    } else if (pathInfo.length() > 1) {
        BlobKey blobKey = new BlobKey(pathInfo.substring(1));
        BlobInfo blobInfo = blobstoreService.getBlobInfo(blobKey);
        response.setContentType(blobInfo.getContentType());
        // In Servlet API 3.1, use #setContentLengthLong(long)
        response.setContentLength((int) blobInfo.getSize());
        response.setDateHeader("Last-Modified", blobInfo.getDateCreated().getTime());
        blobstoreService.serveBlob(blobKey, response.getOutputStream());
    } else {
        // else show links to blobs that were previously uploaded (if any)
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("/WEB-INF/views/uploads/index.jsp");
        List<BlobInfo> blobInfos = new LinkedList<>();
        for (BlobKey blobKey : blobKeys) {
            blobInfos.add(blobstoreService.getBlobInfo(blobKey));
        }
        request.setAttribute("blobstoreService", blobstoreService);
        request.setAttribute("blobKeys", blobKeys);
        request.setAttribute("blobInfos", blobInfos);
        requestDispatcher.forward(request, response);
    }
}

From source file:com.autentia.common.util.web.ClasspathServlet.java

/**
 * Serve the file from the classpath// w  w w .j  a  v  a  2  s.  co m
 */
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String path = request.getPathInfo();

    /* if this servlet is not mapped to a path, use the request URI */
    if (path == null) {
        path = request.getRequestURI().substring(request.getContextPath().length());
    }

    if (!path.endsWith(PAGE_403)) {
        final String extension = path.substring(path.lastIndexOf('.'));
        if (!allowedExtensions.contains(extension)) {
            response.sendError(403, path + " denied");
            return;
        }
    }

    final URL resource = Thread.currentThread().getContextClassLoader().getResource(path.substring(1));
    if (resource == null) {
        response.sendError(404, path + " not found on classpath");

    } else {
        /* check modification date */
        final long ifModifiedSince = request.getDateHeader("If-Modified-Since");
        final long lastModified = resource.openConnection().getLastModified();
        if (ifModifiedSince != -1 && lastModified <= ifModifiedSince) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            return;
        }

        if (log.isDebugEnabled()) {
            log.debug("Resolving URL " + path);
        }

        /* write to response */
        response.setContentType(getServletContext().getMimeType(path));
        final OutputStream out = new BufferedOutputStream(response.getOutputStream(), 512);
        final InputStream in = new BufferedInputStream(resource.openStream(), 512);
        final byte[] data = new byte[512];
        int len;
        try {
            while ((len = in.read(data)) != -1) {
                out.write(data, 0, len);
            }
        } finally {
            in.close();
            out.close();
        }
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.request.HTTPRequest.java

public void applyRequest(final HttpServletRequest request) {
    setClientIP(request.getRemoteAddr());
    setPath(request.getPathInfo());
    setQueryString(request.getQueryString());
    setHostname(request.getServerName());
    setRequestedUrl(request.getRequestURL().toString());
    setUri(request.getRequestURI());/*ww  w .ja v a  2  s .  c  o  m*/

    final String xmm = request.getHeader(X_MM_CLIENT_IP);
    final String fip = request.getParameter(FAKE_IP);

    if (xmm != null) {
        setClientIP(xmm);
    } else if (fip != null) {
        setClientIP(fip);
    }

    final Map<String, String> headers = new HashMap<String, String>();
    final Enumeration<?> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String name = (String) headerNames.nextElement();
        final String value = request.getHeader(name);
        headers.put(name, value);
    }
    setHeaders(headers);
    secure = request.isSecure();
}