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.example.cloud.bigtable.helloworld.JsonServlet.java

/**
 * doPost() - for a given row, get all values from a simple JSON request.
 * (basically a simple map<key,v>)
 *
 * Column Family CF1 is well known and will be what we add columns to that don't have a ':' column
 * prefix.  If you specify a column family, it should have been created as we aren't creating them
 * here./*from w w  w . ja v  a  2s.  c  o  m*/
 *
 * Bigtable (and hbase) fields are basically blobs, so I've chosen to recognize a few "datatypes"
 * bool is defined as 1 byte (either 0x00 / 0x01) for (false / true)
 * counter (long) 64 bits 8 bytes and the first 4 bytes are either 0 or -128
 * doubles we will keep as text in Bigtable / hbase
 *
 * Since we are in a managed VM, we could use a bufferedMutator
 **/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = req.getPathInfo();

    if (path.length() < 5) {
        log("doPost-bad length-" + path.length());
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // IMPORTANT - This try() is a java7 try w/ resources which will close() the table at the end.
    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {
        JSONObject json = new JSONObject(new JSONTokener(req.getReader()));
        String[] names = JSONObject.getNames(json);

        Put p = new Put(Bytes.toBytes(path.substring(1)));
        for (String key : names) {
            byte[] col = CF1;
            String[] k = key.split(":"); // Some other column family?
            if (k.length > 1) {
                col = Bytes.toBytes(k[0]);
                key = k[1];
            }
            Object o = json.opt(key);
            if (o == null) {
                continue; // skip null's for Bigtable / hbase
            }
            switch (o.getClass().getSimpleName()) {
            case "Boolean":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((boolean) o));
                break;

            case "String":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((String) o));
                break;

            case "Double": // Store as Strings
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes(o.toString()));
                break;

            case "Long":
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes((long) o));
                break;
            case "Integer":
                long x = ((Integer) o);
                p.addColumn(col, Bytes.toBytes(key), Bytes.toBytes(x));
                break;
            }
        }
        t.put(p);
    } catch (Exception io) {
        log("Json", io);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }
    resp.addHeader("Access-Control-Allow-Origin", "*");
    resp.setStatus(HttpServletResponse.SC_OK);
}

From source file:snoopware.api.UserGridProxyServlet.java

/**
 * Override to add Authorization to requests that need it.
 * @param req//from w  w w .  java  2  s.  c  om
 * @param proxyReq
 */
@Override
protected void copyRequestHeaders(HttpServletRequest req, HttpRequest proxyReq) {
    super.copyRequestHeaders(req, proxyReq);

    boolean hasAccessToken = req.getQueryString() == null ? false
            : req.getQueryString().contains("access_token=");

    if (!hasAccessToken && ("POST".equalsIgnoreCase(req.getMethod()) || "GET".equalsIgnoreCase(req.getMethod()))
            && req.getPathInfo().contains("/" + applicationName + "/user")) {

        String header = "Bearer " + client.getAccessToken();
        proxyReq.setHeader("Authorization", header);
        log.debug("Added header {} to URL {}", header, req.getRequestURL().toString());
    } else {
        log.debug("Not adding header to request with " + req.getRequestURL().toString());
    }
}

From source file:com.cyclopsgroup.waterview.servlet.ServletPageRuntime.java

/**
 * Default constructor of default web runtime
 * //from www. j av  a 2  s.  c o  m
 * @param request Http request object
 * @param response Http response object
 * @param fileUpload File upload component
 * @param services ServiceManager object
 * @throws Exception Throw it out
 */
ServletPageRuntime(HttpServletRequest request, HttpServletResponse response, FileUpload fileUpload,
        ServiceManager services) throws Exception {
    this.response = response;
    this.request = request;
    setSessionContext(new HttpSessionContext(request.getSession()));

    String requestPath = request.getPathInfo();
    if (StringUtils.isEmpty(requestPath) || requestPath.equals("/")) {
        requestPath = "Index.jelly";
    } else if (requestPath.charAt(0) == '/') {
        requestPath = requestPath.substring(1);
    }
    setRequestPath(requestPath);

    setOutput(new PrintWriter(response.getOutputStream()));
    if (FileUpload.isMultipartContent(request)) {
        setRequestParameters(new MultipartServletRequestValueParser(request, fileUpload));
    } else {
        setRequestParameters(new ServletRequestValueParser(request));
    }
    setServiceManager(services);

    StringBuffer sb = new StringBuffer(request.getScheme());
    sb.append("://").append(request.getServerName());
    if (request.getServerPort() != 80) {
        sb.append(':').append(request.getServerPort());
    }
    sb.append(request.getContextPath());
    setApplicationBaseUrl(sb.toString());

    sb.append(request.getServletPath());
    setPageBaseUrl(sb.toString());

    Context pageContext = new DefaultContext(new HashMap());
    pageContext.put("request", request);
    pageContext.put("response", response);
    setPageContext(pageContext);
}

From source file:com.github.restdriver.clientdriver.unit.HttpRealRequestTest.java

@Test
public void instantiationWithHttpRequestPopulatesCorrectly() throws IOException {

    HttpServletRequest mockRequest = mock(HttpServletRequest.class);
    String expectedPathInfo = "someUrlPath";
    String expectedMethod = "GET";
    Enumeration<String> expectedHeaderNames = Collections.enumeration(Arrays.asList("header1"));

    String bodyContent = "bodyContent";
    String expectedContentType = "contentType";

    when(mockRequest.getPathInfo()).thenReturn(expectedPathInfo);
    when(mockRequest.getMethod()).thenReturn(expectedMethod);
    when(mockRequest.getQueryString()).thenReturn("hello=world");
    when(mockRequest.getHeaderNames()).thenReturn(expectedHeaderNames);
    when(mockRequest.getHeader("header1")).thenReturn("thisIsHeader1");
    when(mockRequest.getInputStream())/*from w  w w . j  ava  2  s .  c  o m*/
            .thenReturn(new DummyServletInputStream(IOUtils.toInputStream(bodyContent)));
    when(mockRequest.getContentType()).thenReturn(expectedContentType);

    RealRequest realRequest = new HttpRealRequest(mockRequest);

    assertThat((String) realRequest.getPath(), is(expectedPathInfo));
    assertThat(realRequest.getMethod(), is(Method.GET));
    assertThat(realRequest.getParams().size(), is(1));
    assertThat((String) realRequest.getParams().get("hello").iterator().next(), is("world"));
    assertThat((String) realRequest.getHeaders().get("header1"), is("thisIsHeader1"));
    assertThat((String) realRequest.getBodyContentType(), is(expectedContentType));

}

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

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    String searchCriteria = getUserSearchInformation(req.getPathInfo());
    WSUser[] users = null;//w ww .  j av  a 2  s .c  o m
    WSUserSearchCriteria wsUserSearchCriteria = restUtils.getWSUserSearchCriteria(searchCriteria);

    try {
        // get the resources....
        users = userAndRoleManagementService.findUsers(wsUserSearchCriteria);
    } catch (AxisFault axisFault) {
        throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, "could not locate users in uri: "
                + wsUserSearchCriteria.getName() + axisFault.getLocalizedMessage());
    }
    if (log.isDebugEnabled()) {
        log.debug("" + users.length + " users were found");
    }

    String marshal = generateSummeryReport(users);
    if (log.isDebugEnabled()) {
        log.debug("Marshaling OK");
    }
    restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, marshal);
}

From source file:com.github.rnewson.couchdb.lucene.LuceneServlet.java

private void doPostInternal(final HttpServletRequest req, final HttpServletResponse resp)
        throws IOException, JSONException {
    switch (StringUtils.countMatches(req.getRequestURI(), "/")) {
    case 3:/*from   www .  j  ava 2s  .co  m*/
        if (req.getPathInfo().endsWith("/_cleanup")) {
            cleanup(req, resp);
            return;
        }
        break;
    case 5: {
        final DatabaseIndexer indexer = getIndexer(req);
        if (indexer == null) {
            ServletUtils.sendJsonError(req, resp, 500, "error_creating_index");
            return;
        }
        indexer.search(req, resp);
        break;
    }
    case 6:
        final DatabaseIndexer indexer = getIndexer(req);
        indexer.admin(req, resp);
        return;
    }
    ServletUtils.sendJsonError(req, resp, 400, "bad_request");
}

From source file:io.hops.hopsworks.api.admin.llap.LlapMonitorProxyServlet.java

/**
* Reads the request URI from {@code servletRequest} and rewrites it,
* considering targetUri./*w  w w.j  a v  a  2s .com*/
* It's used to make the new request.
*
* The servlet name ends with llapmonitor/. This means that the llaphost will be
* forwarded to with the request as part of the pathInfo.
* We need to remove the llaphost from the info
*/
@Override
protected String rewriteUrlFromRequest(HttpServletRequest servletRequest) {
    StringBuilder uri = new StringBuilder(500);
    String targetUri = getTargetUri(servletRequest);
    uri.append(targetUri);
    // Handle the path given to the servlet

    String[] pathInfoSplits = servletRequest.getPathInfo().split("/");
    // Concatenate pathInfo without the llaphost
    StringBuilder newPathInfo = new StringBuilder();
    for (int i = 2; i < pathInfoSplits.length; i++) {
        newPathInfo.append('/').append(pathInfoSplits[i]);
    }
    uri.append(encodeUriQuery(newPathInfo.toString()));

    // 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.nesscomputing.httpserver.jetty.ClasspathResourceHandler.java

@Override
public void handle(final String target, final Request baseRequest, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    if (baseRequest.isHandled()) {
        return;/*w  w  w.jav a2 s.  c o  m*/
    }

    String pathInfo = request.getPathInfo();

    // Only serve the content if the request matches the base path.
    if (pathInfo == null || !pathInfo.startsWith(basePath)) {
        return;
    }

    pathInfo = pathInfo.substring(basePath.length());

    if (!pathInfo.startsWith("/") && !pathInfo.isEmpty()) {
        // basepath is /foo and request went to /foobar --> pathInfo starts with bar
        // basepath is /foo and request went to /foo --> pathInfo should be /index.html
        return;
    }

    // Allow index.html as welcome file
    if ("/".equals(pathInfo) || "".equals(pathInfo)) {
        pathInfo = "/index.html";
    }

    boolean skipContent = false;

    // When a request hits this handler, it will serve something. Either data or an error.
    baseRequest.setHandled(true);

    final String method = request.getMethod();
    if (!StringUtils.equals(HttpMethods.GET, method)) {
        if (StringUtils.equals(HttpMethods.HEAD, method)) {
            skipContent = true;
        } else {
            response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
    }

    // Does the request contain an IF_MODIFIED_SINCE header?
    final long ifModifiedSince = request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
    if (ifModifiedSince > 0 && startupTime <= ifModifiedSince / 1000 && !is304Disabled) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    InputStream resourceStream = null;

    try {
        if (pathInfo.startsWith("/")) {
            final String resourcePath = resourceLocation + pathInfo;
            resourceStream = getClass().getResourceAsStream(resourcePath);
        }

        if (resourceStream == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        final Buffer mime = MIME_TYPES.getMimeByExtension(request.getPathInfo());
        if (mime != null) {
            response.setContentType(mime.toString("ISO8859-1"));
        }

        response.setDateHeader(HttpHeaders.LAST_MODIFIED, startupTime * 1000L);

        if (skipContent) {
            return;
        }

        // Send the content out. Lifted straight out of ResourceHandler.java

        OutputStream out = null;
        try {
            out = response.getOutputStream();
        } catch (IllegalStateException e) {
            out = new WriterOutputStream(response.getWriter());
        }

        if (out instanceof AbstractHttpConnection.Output) {
            ((AbstractHttpConnection.Output) out).sendContent(resourceStream);
        } else {
            ByteStreams.copy(resourceStream, out);
        }
    } finally {
        IOUtils.closeQuietly(resourceStream);
    }
}

From source file:graphql.servlet.GraphQLServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    GraphQLContext context = createContext(Optional.of(req), Optional.of(resp));
    String path = req.getPathInfo();
    if (path == null) {
        path = req.getServletPath();// www.  j  ava2 s  . c  om
    }
    if (path.contentEquals("/schema.json")) {
        query(CharStreams.toString(
                new InputStreamReader(GraphQLServlet.class.getResourceAsStream("introspectionQuery"))), null,
                new HashMap<>(), getSchema(), req, resp, context);
    } else {
        if (req.getParameter("q") != null) {
            query(req.getParameter("q"), null, new HashMap<>(), getReadOnlySchema(), req, resp, context);
        } else if (req.getParameter("query") != null) {
            Map<String, Object> variables = new HashMap<>();
            if (req.getParameter("variables") != null) {
                variables.putAll(new ObjectMapper().readValue(req.getParameter("variables"),
                        new TypeReference<Map<String, Object>>() {
                        }));
            }
            String operationName = null;
            if (req.getParameter("operationName") != null) {
                operationName = req.getParameter("operationName");
            }
            query(req.getParameter("query"), operationName, variables, getReadOnlySchema(), req, resp, context);
        }
    }
}

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

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServiceException {
    try {/*from   ww  w.  j ava2 s  . com*/
        String userName = restUtils.extractResourceName(req.getPathInfo());

        WSUser user = restUtils.unmarshal(WSUser.class, req.getInputStream());
        if (isUserNameValid(userName, user))
            this.updateUser(user);
        else {
            throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "check your request parameters");
        }
        restUtils.setStatusAndBody(HttpServletResponse.SC_OK, resp, "");
    } catch (AxisFault axisFault) {
        throw new ServiceException(axisFault.getLocalizedMessage());
    } catch (IOException e) {
        throw new ServiceException(e.getLocalizedMessage());
    } catch (JAXBException e) {
        throw new ServiceException(HttpServletResponse.SC_BAD_REQUEST, "could not marshal the user descriptor");
    }
}