org.apache.catalina.util.URLEncoder Java Examples

The following examples show how to use org.apache.catalina.util.URLEncoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Substitution.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public String evaluate(Matcher rule, Matcher cond, Resolver resolver) {
    String result = rule.group(n);
    if (result == null) {
        result = "";
    }
    if (escapeBackReferences) {
        // Note: This should be consistent with the way httpd behaves.
        //       We might want to consider providing a dedicated decoder
        //       with an option to add additional safe characters to
        //       provide users with more flexibility
        return URLEncoder.DEFAULT.encode(result, resolver.getUriCharset());
    } else {
        return result;
    }
}
 
Example #2
Source File: TestApplicationContextGetRequestDispatcher.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext ac = req.startAsync();
    // Quick and dirty. Sufficient for this test but ignores lots of
    // edge cases.
    String target = null;
    if (dispatchPath != null) {
        target = req.getServletPath();
        int lastSlash = target.lastIndexOf('/');
        target = target.substring(0, lastSlash + 1);
        if (encodePath) {
            target = URLEncoder.DEFAULT.encode(target, StandardCharsets.UTF_8);
        }
        target += dispatchPath;
    }
    try {
        ac.dispatch(target);
    } catch (UnsupportedOperationException uoe) {
        ac.complete();
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(NULL);
    }
}
 
Example #3
Source File: TestApplicationContextGetRequestDispatcher.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    AsyncContext ac = req.startAsync();
    // Quick and dirty. Sufficient for this test but ignores lots of
    // edge cases.
    String target = null;
    if (dispatchPath != null) {
        target = req.getServletPath();
        int lastSlash = target.lastIndexOf('/');
        target = target.substring(0, lastSlash + 1);
        if (encodePath) {
            target = URLEncoder.DEFAULT.encode(target, "UTF-8");
        }
        target += dispatchPath;
    }
    try {
        ac.dispatch(target);
    } catch (UnsupportedOperationException uoe) {
        ac.complete();
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(NULL);
    }
}
 
Example #4
Source File: SSIMediator.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected String encode(String value, String encoding) {
    String retVal = null;
    if (encoding.equalsIgnoreCase(ENCODING_URL)) {
        retVal = URLEncoder.DEFAULT.encode(value, StandardCharsets.UTF_8);
    } else if (encoding.equalsIgnoreCase(ENCODING_NONE)) {
        retVal = value;
    } else if (encoding.equalsIgnoreCase(ENCODING_ENTITY)) {
        retVal = Escape.htmlElementContent(value);
    } else {
        //This shouldn't be possible
        throw new IllegalArgumentException("Unknown encoding: " + encoding);
    }
    return retVal;
}
 
Example #5
Source File: Request.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * @return a RequestDispatcher that wraps the resource at the specified
 * path, which may be interpreted as relative to the current request path.
 *
 * @param path Path of the resource to be wrapped
 */
@Override
public RequestDispatcher getRequestDispatcher(String path) {

    Context context = getContext();
    if (context == null) {
        return null;
    }

    if (path == null) {
        return null;
    }

    int fragmentPos = path.indexOf('#');
    if (fragmentPos > -1) {
        log.warn(sm.getString("request.fragmentInDispatchPath", path));
        path = path.substring(0, fragmentPos);
    }

    // If the path is already context-relative, just pass it through
    if (path.startsWith("/")) {
        return context.getServletContext().getRequestDispatcher(path);
    }

    /*
     * Relative to what, exactly?
     *
     * From the Servlet 4.0 Javadoc:
     * - The pathname specified may be relative, although it cannot extend
     *   outside the current servlet context.
     * - If it is relative, it must be relative against the current servlet
     *
     * From Section 9.1 of the spec:
     * - The servlet container uses information in the request object to
     *   transform the given relative path against the current servlet to a
     *   complete path.
     *
     * It is undefined whether the requestURI is used or whether servletPath
     * and pathInfo are used. Given that the RequestURI includes the
     * contextPath (and extracting that is messy) , using the servletPath and
     * pathInfo looks to be the more reasonable choice.
     */

    // Convert a request-relative path to a context-relative one
    String servletPath = (String) getAttribute(
            RequestDispatcher.INCLUDE_SERVLET_PATH);
    if (servletPath == null) {
        servletPath = getServletPath();
    }

    // Add the path info, if there is any
    String pathInfo = getPathInfo();
    String requestPath = null;

    if (pathInfo == null) {
        requestPath = servletPath;
    } else {
        requestPath = servletPath + pathInfo;
    }

    int pos = requestPath.lastIndexOf('/');
    String relative = null;
    if (context.getDispatchersUseEncodedPaths()) {
        if (pos >= 0) {
            relative = URLEncoder.DEFAULT.encode(
                    requestPath.substring(0, pos + 1), StandardCharsets.UTF_8) + path;
        } else {
            relative = URLEncoder.DEFAULT.encode(requestPath, StandardCharsets.UTF_8) + path;
        }
    } else {
        if (pos >= 0) {
            relative = requestPath.substring(0, pos + 1) + path;
        } else {
            relative = requestPath + path;
        }
    }

    return context.getServletContext().getRequestDispatcher(relative);
}
 
Example #6
Source File: ApplicationHttpRequest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Return a RequestDispatcher that wraps the resource at the specified
 * path, which may be interpreted as relative to the current request path.
 *
 * @param path Path of the resource to be wrapped
 */
@Override
public RequestDispatcher getRequestDispatcher(String path) {

    if (context == null)
        return null;

    if (path == null) {
        return null;
    }

    int fragmentPos = path.indexOf('#');
    if (fragmentPos > -1) {
        context.getLogger().warn(sm.getString("applicationHttpRequest.fragmentInDispatchPath", path));
        path = path.substring(0, fragmentPos);
    }

    // If the path is already context-relative, just pass it through
    if (path.startsWith("/")) {
        return context.getServletContext().getRequestDispatcher(path);
    }

    // Convert a request-relative path to a context-relative one
    String servletPath =
        (String) getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH);
    if (servletPath == null)
        servletPath = getServletPath();

    // Add the path info, if there is any
    String pathInfo = getPathInfo();
    String requestPath = null;

    if (pathInfo == null) {
        requestPath = servletPath;
    } else {
        requestPath = servletPath + pathInfo;
    }

    int pos = requestPath.lastIndexOf('/');
    String relative = null;
    if (context.getDispatchersUseEncodedPaths()) {
        if (pos >= 0) {
            relative = URLEncoder.DEFAULT.encode(
                    requestPath.substring(0, pos + 1), StandardCharsets.UTF_8) + path;
        } else {
            relative = URLEncoder.DEFAULT.encode(requestPath, StandardCharsets.UTF_8) + path;
        }
    } else {
        if (pos >= 0) {
            relative = requestPath.substring(0, pos + 1) + path;
        } else {
            relative = requestPath + path;
        }
    }

    return context.getServletContext().getRequestDispatcher(relative);

}
 
Example #7
Source File: Request.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Return a RequestDispatcher that wraps the resource at the specified
 * path, which may be interpreted as relative to the current request path.
 *
 * @param path Path of the resource to be wrapped
 */
@Override
public RequestDispatcher getRequestDispatcher(String path) {

    if (context == null) {
        return null;
    }

    // If the path is already context-relative, just pass it through
    if (path == null) {
        return null;
    } else if (path.startsWith("/")) {
        return (context.getServletContext().getRequestDispatcher(path));
    }

    // Convert a request-relative path to a context-relative one
    String servletPath = (String) getAttribute(
            RequestDispatcher.INCLUDE_SERVLET_PATH);
    if (servletPath == null) {
        servletPath = getServletPath();
    }

    // Add the path info, if there is any
    String pathInfo = getPathInfo();
    String requestPath = null;

    if (pathInfo == null) {
        requestPath = servletPath;
    } else {
        requestPath = servletPath + pathInfo;
    }

    int pos = requestPath.lastIndexOf('/');
    String relative = null;
    if (context.getDispatchersUseEncodedPaths()) {
        if (pos >= 0) {
            relative = URLEncoder.DEFAULT.encode(
                    requestPath.substring(0, pos + 1), "UTF-8") + path;
        } else {
            relative = URLEncoder.DEFAULT.encode(requestPath, "UTF-8") + path;
        }
    } else {
        if (pos >= 0) {
            relative = requestPath.substring(0, pos + 1) + path;
        } else {
            relative = requestPath + path;
        }
    }

    return context.getServletContext().getRequestDispatcher(relative);
}
 
Example #8
Source File: ClusterRestControllerIntegrationTest.java    From genie with Apache License 2.0 4 votes vote down vote up
/**
 * This test "documents" a known bug in Spring HATEOAS links that resulted in doubly-encoded pagination links.
 * https://github.com/spring-projects/spring-hateoas/issues/559
 * We worked around this bug in the UI by decoding these elements (see Pagination.js).
 * This test now documents the contract that this bug should be fixed.
 *
 * @throws Exception on error
 */
@Test
void testPagingDoubleEncoding() throws Exception {
    final String id1 = UUID.randomUUID().toString();
    final String id2 = UUID.randomUUID().toString();
    final String id3 = UUID.randomUUID().toString();
    final String name1 = "Test " + UUID.randomUUID().toString();
    final String name2 = "Test " + UUID.randomUUID().toString();
    final String name3 = "Test " + UUID.randomUUID().toString();
    final String user1 = UUID.randomUUID().toString();
    final String user2 = UUID.randomUUID().toString();
    final String user3 = UUID.randomUUID().toString();
    final String version1 = UUID.randomUUID().toString();
    final String version2 = UUID.randomUUID().toString();
    final String version3 = UUID.randomUUID().toString();

    this.createConfigResource(
        new Cluster.Builder(name1, user1, version1, ClusterStatus.UP).withId(id1).build(),
        null
    );
    Thread.sleep(1000);
    this.createConfigResource(
        new Cluster.Builder(name2, user2, version2, ClusterStatus.OUT_OF_SERVICE).withId(id2).build(),
        null
    );
    Thread.sleep(1000);
    this.createConfigResource(
        new Cluster.Builder(name3, user3, version3, ClusterStatus.TERMINATED).withId(id3).build(),
        null
    );

    Assertions.assertThat(this.clusterRepository.count()).isEqualTo(3L);

    final URLEncoder urlEncoder = new URLEncoder();

    final String unencodedNameQuery = "Test %";
    final String singleEncodedNameQuery = urlEncoder.encode(unencodedNameQuery, StandardCharsets.UTF_8);

    // Query by name with wildcard and get the second page containing a single result (out of 3)
    final JsonNode responseJsonNode = GenieObjectMapper
        .getMapper()
        .readTree(
            RestAssured
                .given(this.getRequestSpecification())
                .param("name", unencodedNameQuery)
                .param("size", 1)
                .param("page", 1)
                .when()
                .port(this.port)
                .get(CLUSTERS_API)
                .then()
                .statusCode(Matchers.is(HttpStatus.OK.value()))
                .contentType(Matchers.containsString(MediaTypes.HAL_JSON_VALUE))
                .body(CLUSTERS_LIST_PATH, Matchers.hasSize(1))
                .extract()
                .asByteArray()
        );

    // Self link is not double-encoded
    Assertions
        .assertThat(
            responseJsonNode
                .get("_links")
                .get("self")
                .get("href")
                .asText()
        )
        .contains(singleEncodedNameQuery);

    // Pagination links that were double-encoded
    final String[] doubleEncodedHREFS = new String[]{
        "first", "next", "prev", "last",
    };

    for (String doubleEncodedHref : doubleEncodedHREFS) {
        final String linkString = responseJsonNode
            .get("_links")
            .get(doubleEncodedHref)
            .get("href")
            .asText();
        Assertions.assertThat(linkString).isNotBlank();
        final Map<String, String> params = Maps.newHashMap();
        URLEncodedUtils
            .parse(new URI(linkString), StandardCharsets.UTF_8)
            .forEach(nameValuePair -> params.put(nameValuePair.getName(), nameValuePair.getValue()));

        Assertions.assertThat(params).containsKey("name");
        Assertions.assertThat(params.get("name")).isEqualTo(unencodedNameQuery);
    }
}
 
Example #9
Source File: DefaultServlet.java    From Tomcat8-Source-Read with MIT License 2 votes vote down vote up
/**
 * URL rewriter.
 *
 * @param path Path which has to be rewritten
 * @return the rewritten path
 */
protected String rewriteUrl(String path) {
    return URLEncoder.DEFAULT.encode(path, StandardCharsets.UTF_8);
}