Java Code Examples for org.apache.tomcat.util.buf.MessageBytes#setString()

The following examples show how to use org.apache.tomcat.util.buf.MessageBytes#setString() . 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: UrlMapperValve.java    From carbon-commons with Apache License 2.0 6 votes vote down vote up
public void requestRewriteForService(Request request, String filterUri) throws Exception {
    //rewriting the request with actual service url in order to retrieve the resource
    MappingData mappingData = request.getMappingData();
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();

    MessageBytes requestPath = MessageBytes.newInstance();
    requestPath.setString(filterUri);
    mappingData.requestPath = requestPath;
    MessageBytes pathInfo = MessageBytes.newInstance();
    pathInfo.setString(filterUri);
    mappingData.pathInfo = pathInfo;

    coyoteRequest.requestURI().setString(filterUri);
    coyoteRequest.decodedURI().setString(filterUri);
    if (request.getQueryString() != null) {
        coyoteRequest.unparsedURI().setString(filterUri + "?" + request.getQueryString());
    } else {
        coyoteRequest.unparsedURI().setString(filterUri);
    }
    request.getConnector().
            getMapper().map(request.getCoyoteRequest().serverName(),
            request.getCoyoteRequest().decodedURI(), null,
            mappingData);
    //connectorReq.setHost((Host)DataHolder.getInstance().getCarbonTomcatService().getTomcat().getEngine().findChild("testapp.wso2.com"));
    request.setCoyoteRequest(coyoteRequest);
}
 
Example 2
Source File: WebappAuthenticationValveTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To create a request with the given authorization header
 *
 * @param authorizationHeader Authorization header
 * @return the relevant request.
 * @throws IllegalAccessException Illegal Access Exception.
 * @throws NoSuchFieldException   No Such Field Exception.
 */
private Request createRequest(String authorizationHeader) throws IllegalAccessException, NoSuchFieldException {
    Request request = new TestRequest("", "");
    Context context = new StandardContext();
    context.addParameter("basicAuth", "true");
    context.addParameter("managed-api-enabled", "true");
    context.setPath("carbon1");
    context.addParameter("doAuthentication", String.valueOf(true));
    request.setContext(context);
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(authorizationHeader);
    Field headersField = org.apache.coyote.Request.class.getDeclaredField("headers");
    headersField.setAccessible(true);
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example 3
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To create a soap request by reading the request from given file.
 *
 * @param fileName Name of the file that has the soap request content.
 * @return Request created with soap content.
 * @throws IllegalAccessException Illegal Access Exception.
 * @throws IOException            IO Exception.
 */
private Request createSoapRequest(String fileName) throws IllegalAccessException, IOException {
    Request request = new Request();
    ClassLoader classLoader = getClass().getClassLoader();
    URL resourceUrl = classLoader
            .getResource("requests" + File.separator + "BST" + File.separator + fileName);
    String bstRequestContent = null;
    if (resourceUrl != null) {
        File bst = new File(resourceUrl.getFile());
        bstRequestContent = FileUtils.readFileToString(bst);
    }
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue("content-type");
    bytes.setString("application/xml");
    bytes = mimeHeaders.addValue("custom");
    bytes.setString(bstRequestContent);
    headersField.set(coyoteRequest, mimeHeaders);
    TestInputBuffer inputBuffer = new TestInputBuffer();
    coyoteRequest.setInputBuffer(inputBuffer);
    Context context = new StandardContext();
    request.setContext(context);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example 4
Source File: TestMapperPerformance.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private long testPerformanceImpl(String requestedHostName) throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString(requestedHostName);
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        mappingData.recycle();
        mapper.map(host, uri, null, mappingData);
    }
    long time = System.currentTimeMillis() - start;
    return time;
}
 
Example 5
Source File: JWTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
/**
 * To create a JWT request with the given jwt header.
 *  @param jwtToken JWT token to be added to the header
 * @param requestUri Request URI to be added to the request.
 */
private Request createJWTRequest(String jwtToken, String requestUri)
        throws IllegalAccessException, NoSuchFieldException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(JWT_HEADER);
    bytes.setString(jwtToken);
    headersField.set(coyoteRequest, mimeHeaders);
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    bytes = MessageBytes.newInstance();
    bytes.setString(requestUri);
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example 6
Source File: TestMapper.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private long testPerformanceImpl() throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString("iowejoiejfoiew");
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    long start = System.currentTimeMillis();
    for (int i = 0; i < 1000000; i++) {
        mappingData.recycle();
        mapper.map(host, uri, null, mappingData);
    }
    long time = System.currentTimeMillis() - start;
    return time;
}
 
Example 7
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests the canHandle method of the BSTAuthenticator under faulty conditions")
public void testCanHandleWithFalseConditions() throws IllegalAccessException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request without content type");

    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue("content-type");
    bytes.setString("test");
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    Assert.assertFalse(bstAuthenticator.canHandle(request),
            "BST Authenticator can handle a request with content type test");
}
 
Example 8
Source File: TomcatHeadersAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean containsValue(Object value) {
	if (value instanceof String) {
		MessageBytes needle = MessageBytes.newInstance();
		needle.setString((String) value);
		for (int i = 0; i < this.headers.size(); i++) {
			if (this.headers.getValue(i).equals(needle)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 9
Source File: OauthAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * This will create an OAuth request.
 *
 * @param authorizationHeader Authorization Header
 */
private Request createOauthRequest(String authorizationHeader) throws IllegalAccessException {
    Request request = new Request();
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(authorizationHeader);
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example 10
Source File: CertificateAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
/**
 * To create a request that can be understandable by Certificate Authenticator.
 *
 * @param headerName Name of the header
 * @param value      Value for the header
 * @return Request that is created.
 * @throws IllegalAccessException Illegal Access Exception.
 * @throws NoSuchFieldException   No Such Field Exception.
 */
private Request createRequest(String headerName, String value) throws IllegalAccessException, NoSuchFieldException {
    Request request = new Request();
    Context context = new StandardContext();
    request.setContext(context);
    org.apache.coyote.Request coyoteRequest = new org.apache.coyote.Request();
    MimeHeaders mimeHeaders = new MimeHeaders();
    MessageBytes bytes = mimeHeaders.addValue(headerName);
    bytes.setString(value);
    headersField.set(coyoteRequest, mimeHeaders);

    request.setCoyoteRequest(coyoteRequest);
    return request;
}
 
Example 11
Source File: TestMapper.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testMap() throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString("iowejoiejfoiew");
    MessageBytes alias = MessageBytes.newInstance();
    alias.setString("iowejoiejfoiew_alias");
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    mapper.map(host, uri, null, mappingData);
    assertEquals("blah7", mappingData.host);
    assertEquals("context2", mappingData.context);
    assertEquals("wrapper5", mappingData.wrapper);
    assertEquals("/foo/bar", mappingData.contextPath.toString());
    assertEquals("/blah/bobou", mappingData.wrapperPath.toString());
    assertEquals("/foo", mappingData.pathInfo.toString());
    assertTrue(mappingData.redirectPath.isNull());

    mappingData.recycle();
    uri.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(host, uri, null, mappingData);
    assertEquals("blah7", mappingData.host);
    assertEquals("context3", mappingData.context);
    assertEquals("wrapper7", mappingData.wrapper);
    assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    assertEquals("/bobou", mappingData.wrapperPath.toString());
    assertEquals("/foo", mappingData.pathInfo.toString());
    assertTrue(mappingData.redirectPath.isNull());

    mappingData.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(alias, uri, null, mappingData);
    assertEquals("blah7", mappingData.host);
    assertEquals("context3", mappingData.context);
    assertEquals("wrapper7", mappingData.wrapper);
    assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    assertEquals("/bobou", mappingData.wrapperPath.toString());
    assertEquals("/foo", mappingData.pathInfo.toString());
    assertTrue(mappingData.redirectPath.isNull());
}
 
Example 12
Source File: ApplicationPushBuilder.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Override
public void push() {
    if (path == null) {
        throw new IllegalStateException(sm.getString("pushBuilder.noPath"));
    }

    org.apache.coyote.Request pushTarget = new org.apache.coyote.Request();

    pushTarget.method().setString(method);
    // The next three are implied by the Javadoc getPath()
    pushTarget.serverName().setString(baseRequest.getServerName());
    pushTarget.setServerPort(baseRequest.getServerPort());
    pushTarget.scheme().setString(baseRequest.getScheme());

    // Copy headers
    for (Map.Entry<String,List<String>> header : headers.entrySet()) {
        for (String value : header.getValue()) {
            pushTarget.getMimeHeaders().addValue(header.getKey()).setString(value);
        }
    }

    // Path and query string
    int queryIndex = path.indexOf('?');
    String pushPath;
    String pushQueryString = null;
    if (queryIndex > -1) {
        pushPath = path.substring(0, queryIndex);
        if (queryIndex + 1 < path.length()) {
            pushQueryString = path.substring(queryIndex + 1);
        }
    } else {
        pushPath = path;
    }

    // Session ID (do this before setting the path since it may change it)
    if (sessionId != null) {
        if (addSessionPathParameter) {
            pushPath = pushPath + ";" + sessionPathParameterName + "=" + sessionId;
            pushTarget.addPathParameter(sessionPathParameterName, sessionId);
        }
        if (addSessionCookie) {
            String sessionCookieHeader = sessionCookieName + "=" + sessionId;
            MessageBytes mb = pushTarget.getMimeHeaders().getValue("cookie");
            if (mb == null) {
                mb = pushTarget.getMimeHeaders().addValue("cookie");
                mb.setString(sessionCookieHeader);
            } else {
                mb.setString(mb.getString() + ";" + sessionCookieHeader);
            }
        }
    }

    // Undecoded path - just %nn encoded
    pushTarget.requestURI().setString(pushPath);
    pushTarget.decodedURI().setString(decode(pushPath,
            catalinaRequest.getConnector().getURICharset()));

    // Query string
    if (pushQueryString == null && queryString != null) {
        pushTarget.queryString().setString(queryString);
    } else if (pushQueryString != null && queryString == null) {
        pushTarget.queryString().setString(pushQueryString);
    } else if (pushQueryString != null && queryString != null) {
        pushTarget.queryString().setString(pushQueryString + "&" +queryString);
    }

    // Authorization
    if (userName != null) {
        pushTarget.getRemoteUser().setString(userName);
        pushTarget.setRemoteUserNeedsAuthorization(true);
    }

    coyoteRequest.action(ActionCode.PUSH_REQUEST, pushTarget);

    // Reset for next call to this method
    path = null;
    headers.remove("if-none-match");
    headers.remove("if-modified-since");
}
 
Example 13
Source File: FormAuthenticator.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
/**
 * Restore the original request from information stored in our session.
 * If the original request is no longer present (because the session
 * timed out), return <code>false</code>; otherwise, return
 * <code>true</code>.
 *
 * @param request The request to be restored
 * @param session The session containing the saved information
 */
protected boolean restoreRequest(Request request, Session session)
        throws IOException {

    // Retrieve and remove the SavedRequest object from our session
    SavedRequest saved = (SavedRequest)
        session.getNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_REQUEST_NOTE);
    session.removeNote(Constants.FORM_PRINCIPAL_NOTE);
    if (saved == null) {
        return (false);
    }

    // Swallow any request body since we will be replacing it
    // Need to do this before headers are restored as AJP connector uses
    // content length header to determine how much data needs to be read for
    // request body
    byte[] buffer = new byte[4096];
    InputStream is = request.createInputStream();
    while (is.read(buffer) >= 0) {
        // Ignore request body
    }

    // Modify our current request to reflect the original one
    request.clearCookies();
    Iterator<Cookie> cookies = saved.getCookies();
    while (cookies.hasNext()) {
        request.addCookie(cookies.next());
    }

    String method = saved.getMethod();
    MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders();
    rmh.recycle();
    boolean cachable = "GET".equalsIgnoreCase(method) ||
                       "HEAD".equalsIgnoreCase(method);
    Iterator<String> names = saved.getHeaderNames();
    while (names.hasNext()) {
        String name = names.next();
        // The browser isn't expecting this conditional response now.
        // Assuming that it can quietly recover from an unexpected 412.
        // BZ 43687
        if(!("If-Modified-Since".equalsIgnoreCase(name) ||
             (cachable && "If-None-Match".equalsIgnoreCase(name)))) {
            Iterator<String> values = saved.getHeaderValues(name);
            while (values.hasNext()) {
                rmh.addValue(name).setString(values.next());
            }
        }
    }

    request.clearLocales();
    Iterator<Locale> locales = saved.getLocales();
    while (locales.hasNext()) {
        request.addLocale(locales.next());
    }

    request.getCoyoteRequest().getParameters().recycle();
    request.getCoyoteRequest().getParameters().setQueryStringEncoding(
            request.getConnector().getURIEncoding());

    ByteChunk body = saved.getBody();

    if (body != null) {
        request.getCoyoteRequest().action
            (ActionCode.REQ_SET_BODY_REPLAY, body);

        // Set content type
        MessageBytes contentType = MessageBytes.newInstance();

        // If no content type specified, use default for POST
        String savedContentType = saved.getContentType();
        if (savedContentType == null && "POST".equalsIgnoreCase(method)) {
            savedContentType = "application/x-www-form-urlencoded";
        }

        contentType.setString(savedContentType);
        request.getCoyoteRequest().setContentType(contentType);
    }

    request.getCoyoteRequest().method().setString(method);

    request.getCoyoteRequest().queryString().setString
        (saved.getQueryString());

    request.getCoyoteRequest().requestURI().setString
        (saved.getRequestURI());
    return (true);

}
 
Example 14
Source File: CrossSubdomainSessionValve.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
protected void replaceCookie(Request request, Response response, Cookie cookie) {

        Delegator delegator = (Delegator) request.getAttribute("delegator");
        // copy the existing session cookie, but use a different domain (only if domain is valid)
        String cookieDomain = null;
        cookieDomain = EntityUtilProperties.getPropertyValue("url", "cookie.domain", "", delegator);

        if (UtilValidate.isEmpty(cookieDomain)) {
            String serverName = request.getServerName();
            String[] domainArray = serverName.split("\\.");
            // check that the domain isn't an IP address
            if (domainArray.length == 4) {
                boolean isIpAddress = true;
                for (String domainSection : domainArray) {
                    if (!UtilValidate.isIntegerInRange(domainSection, 0, 255)) {
                        isIpAddress = false;
                        break;
                    }
                }
                if (isIpAddress) {
                    return;
                }
            }
            if (domainArray.length > 2) {
                cookieDomain = "." + domainArray[domainArray.length - 2] + "." + domainArray[domainArray.length - 1];
            }
        }


        if (UtilValidate.isNotEmpty(cookieDomain)) {
            Cookie newCookie = new Cookie(cookie.getName(), cookie.getValue());
            if (cookie.getPath() != null) {
                newCookie.setPath(cookie.getPath());
            }
            newCookie.setDomain(cookieDomain);
            newCookie.setMaxAge(cookie.getMaxAge());
            newCookie.setVersion(cookie.getVersion());
            if (cookie.getComment() != null) {
                newCookie.setComment(cookie.getComment());
            }
            newCookie.setSecure(cookie.getSecure());
            newCookie.setHttpOnly(cookie.isHttpOnly());

            // if the response has already been committed, our replacement strategy will have no effect
            if (response.isCommitted()) {
                Debug.logError("CrossSubdomainSessionValve: response was already committed!", module);
            }

            // find the Set-Cookie header for the existing cookie and replace its value with new cookie
            MimeHeaders mimeHeaders = request.getCoyoteRequest().getMimeHeaders();
            for (int i = 0, size = mimeHeaders.size(); i < size; i++) {
                if (mimeHeaders.getName(i).equals("Set-Cookie")) {
                    MessageBytes value = mimeHeaders.getValue(i);
                    if (value.indexOf(cookie.getName()) >= 0) {
                        String newCookieValue = request.getContext().getCookieProcessor().generateHeader(newCookie);
                        if (Debug.verboseOn()) Debug.logVerbose("CrossSubdomainSessionValve: old Set-Cookie value: " + value.toString(), module);
                        if (Debug.verboseOn()) Debug.logVerbose("CrossSubdomainSessionValve: new Set-Cookie value: " + newCookieValue, module);
                        value.setString(newCookieValue);
                    }
                }
            }
        }
    }
 
Example 15
Source File: TestMapper.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddRemoveContextVersion() throws Exception {
    final String hostName = "iowejoiejfoiew";
    final int iowPos = 3;
    final String contextPath = "/foo/bar";
    final int contextPos = 2;

    MappingData mappingData = new MappingData();
    MessageBytes hostMB = MessageBytes.newInstance();
    MessageBytes uriMB = MessageBytes.newInstance();
    hostMB.setString(hostName);
    uriMB.setString("/foo/bar/blah/bobou/foo");

    // Verifying configuration created by setUp()
    Mapper.Host mappedHost = mapper.hosts[iowPos];
    assertEquals(hostName, mappedHost.name);
    Mapper.Context mappedContext = mappedHost.contextList.contexts[contextPos];
    assertEquals(contextPath, mappedContext.name);
    assertEquals(1, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    Object oldHost = mappedHost.object;
    Object oldContext = mappedContext.versions[0].object;
    assertEquals("context2", oldContext.toString());

    Object oldContext1 = mappedHost.contextList.contexts[contextPos - 1].versions[0].object;
    assertEquals("context1", oldContext1.toString());

    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("blah7", mappingData.host.toString());
    assertEquals("context2", mappingData.context.toString());
    assertEquals("wrapper5", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext2.map(uriMB, mappingData);
    assertEquals("wrapper5", mappingData.wrapper.toString());

    Object newContext = "newContext";
    mapper.addContextVersion(
            hostName,
            oldHost,
            contextPath,
            "1",
            newContext,
            null,
            null,
            Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo(
                    "/", "newContext-default", false, false) }));

    assertEquals(2, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    assertEquals("1", mappedContext.versions[1].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-default", mappingData.wrapper.toString());

    mapper.removeContextVersion(hostName, contextPath, "0");

    assertEquals(1, mappedContext.versions.length);
    assertEquals("1", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-default", mappingData.wrapper.toString());

    mapper.removeContextVersion(hostName, contextPath, "1");

    assertNotSame(mappedContext, mappedHost.contextList.contexts[contextPos]);
    assertEquals("/foo/bar/bla", mappedHost.contextList.contexts[contextPos].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("context1", mappingData.context.toString());
    assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext1.map(uriMB, mappingData);
    assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());

    mapper.addContextVersion(
            hostName,
            oldHost,
            contextPath,
            "0",
            newContext,
            null,
            null,
            Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo(
                    "/", "newContext-defaultWrapper2", false, false) }));
    mappedContext = mappedHost.contextList.contexts[contextPos];

    assertEquals(contextPath, mappedContext.name);
    assertEquals(1, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-defaultWrapper2", mappingData.wrapper.toString());
}
 
Example 16
Source File: TestMapper.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddRemoveContextVersion() throws Exception {
    final String hostName = "iowejoiejfoiew";
    final int iowPos = 3;
    final String contextPath = "/foo/bar";
    final int contextPos = 2;

    MappingData mappingData = new MappingData();
    MessageBytes hostMB = MessageBytes.newInstance();
    MessageBytes uriMB = MessageBytes.newInstance();
    hostMB.setString(hostName);
    uriMB.setString("/foo/bar/blah/bobou/foo");

    // Verifying configuration created by setUp()
    Mapper.Host mappedHost = mapper.hosts[iowPos];
    assertEquals(hostName, mappedHost.name);
    Mapper.Context mappedContext = mappedHost.contextList.contexts[contextPos];
    assertEquals(contextPath, mappedContext.name);
    assertEquals(1, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    Object oldHost = mappedHost.object;
    Object oldContext = mappedContext.versions[0].object;
    assertEquals("context2", oldContext.toString());

    Object oldContext1 = mappedHost.contextList.contexts[contextPos - 1].versions[0].object;
    assertEquals("context1", oldContext1.toString());

    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("blah7", mappingData.host.toString());
    assertEquals("context2", mappingData.context.toString());
    assertEquals("wrapper5", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext2.map(uriMB, mappingData);
    assertEquals("wrapper5", mappingData.wrapper.toString());

    Object newContext = "newContext";
    mapper.addContextVersion(
            hostName,
            oldHost,
            contextPath,
            "1",
            newContext,
            null,
            null,
            Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo(
                    "/", "newContext-default", false, false) }),
            false,
            false);

    assertEquals(2, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    assertEquals("1", mappedContext.versions[1].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-default", mappingData.wrapper.toString());

    mapper.removeContextVersion(hostName, contextPath, "0");

    assertEquals(1, mappedContext.versions.length);
    assertEquals("1", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-default", mappingData.wrapper.toString());

    mapper.removeContextVersion(hostName, contextPath, "1");

    assertNotSame(mappedContext, mappedHost.contextList.contexts[contextPos]);
    assertEquals("/foo/bar/bla", mappedHost.contextList.contexts[contextPos].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("context1", mappingData.context.toString());
    assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());
    mappingData.recycle();
    mapperForContext1.map(uriMB, mappingData);
    assertEquals("context1-defaultWrapper", mappingData.wrapper.toString());

    mapper.addContextVersion(
            hostName,
            oldHost,
            contextPath,
            "0",
            newContext,
            null,
            null,
            Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo(
                    "/", "newContext-defaultWrapper2", false, false) }),
            false,
            false);
    mappedContext = mappedHost.contextList.contexts[contextPos];

    assertEquals(contextPath, mappedContext.name);
    assertEquals(1, mappedContext.versions.length);
    assertEquals("0", mappedContext.versions[0].name);
    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("newContext", mappingData.context.toString());
    assertEquals("newContext-defaultWrapper2", mappingData.wrapper.toString());
}
 
Example 17
Source File: OauthAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Test(description = "This method tests the authenticate under different parameters",
        dependsOnMethods = {"testInit"})
public void testAuthenticate() throws Exception {
    Request request = createOauthRequest(BEARER_HEADER);
    Assert.assertEquals(oAuthAuthenticator.authenticate(request, null).getStatus(),
            WebappAuthenticator.Status.CONTINUE, "Authentication status mismatched");
    request = createOauthRequest(BEARER_HEADER + "abc");
    org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest();
    Field uriMB = org.apache.coyote.Request.class.getDeclaredField("uriMB");
    uriMB.setAccessible(true);
    MessageBytes bytes = MessageBytes.newInstance();
    bytes.setString("test");
    uriMB.set(coyoteRequest, bytes);
    request.setCoyoteRequest(coyoteRequest);
    Field tokenValidator = OAuthAuthenticator.class.getDeclaredField("tokenValidator");
    tokenValidator.setAccessible(true);

    GenericObjectPool genericObjectPool = Mockito.mock(GenericObjectPool.class, Mockito.CALLS_REAL_METHODS);
    RemoteOAuthValidator remoteOAuthValidator = Mockito
            .mock(RemoteOAuthValidator.class, Mockito.CALLS_REAL_METHODS);
    tokenValidator.set(oAuthAuthenticator, remoteOAuthValidator);
    Field stubs = RemoteOAuthValidator.class.getDeclaredField("stubs");
    stubs.setAccessible(true);
    stubs.set(remoteOAuthValidator, genericObjectPool);
    OAuth2TokenValidationResponseDTO oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
    oAuth2TokenValidationResponseDTO.setValid(true);
    oAuth2TokenValidationResponseDTO.setAuthorizedUser("[email protected]");
    OAuth2ClientApplicationDTO oAuth2ClientApplicationDTO = Mockito
            .mock(OAuth2ClientApplicationDTO.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(oAuth2TokenValidationResponseDTO).when(oAuth2ClientApplicationDTO)
            .getAccessTokenValidationResponse();
    OAuth2TokenValidationServiceStub oAuth2TokenValidationServiceStub = Mockito
            .mock(OAuth2TokenValidationServiceStub.class, Mockito.CALLS_REAL_METHODS);
    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationServiceStub)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    Mockito.doReturn(oAuth2TokenValidationServiceStub).when(genericObjectPool).borrowObject();
    oAuthAuthenticator.canHandle(request);
    AuthenticationInfo authenticationInfo = oAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getUsername(), "admin");

}
 
Example 18
Source File: TestMapper.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testContextListConcurrencyBug56653() throws Exception {
    final Host host = createHost("localhost");
    final Context contextRoot = createContext("ROOT");
    final Context context1 = createContext("foo");
    final Context context2 = createContext("foo#bar");
    final Context context3 = createContext("foo#bar#bla");
    final Context context4 = createContext("foo#bar#bla#baz");

    mapper.addHost("localhost", new String[] { "alias" }, host);
    mapper.setDefaultHostName("localhost");

    mapper.addContextVersion("localhost", host, "", "0", contextRoot,
            new String[0], null, null);
    mapper.addContextVersion("localhost", host, "/foo", "0", context1,
            new String[0], null, null);
    mapper.addContextVersion("localhost", host, "/foo/bar", "0", context2,
            new String[0], null, null);
    mapper.addContextVersion("localhost", host, "/foo/bar/bla", "0",
            context3, new String[0], null, null);
    mapper.addContextVersion("localhost", host, "/foo/bar/bla/baz", "0",
            context4, new String[0], null, null);

    final AtomicBoolean running = new AtomicBoolean(true);
    Thread t = new Thread() {
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                mapper.removeContextVersion(context4, "localhost",
                        "/foo/bar/bla/baz", "0");
                mapper.addContextVersion("localhost", host,
                        "/foo/bar/bla/baz", "0", context4, new String[0],
                        null, null);
            }
            running.set(false);
        }
    };

    MappingData mappingData = new MappingData();
    MessageBytes hostMB = MessageBytes.newInstance();
    hostMB.setString("localhost");
    MessageBytes aliasMB = MessageBytes.newInstance();
    aliasMB.setString("alias");
    MessageBytes uriMB = MessageBytes.newInstance();
    char[] uri = "/foo/bar/bla/bobou/foo".toCharArray();
    uriMB.setChars(uri, 0, uri.length);

    mapper.map(hostMB, uriMB, null, mappingData);
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

    mappingData.recycle();
    uriMB.setChars(uri, 0, uri.length);
    mapper.map(aliasMB, uriMB, null, mappingData);
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

    t.start();
    while (running.get()) {
        mappingData.recycle();
        uriMB.setChars(uri, 0, uri.length);
        mapper.map(hostMB, uriMB, null, mappingData);
        Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

        mappingData.recycle();
        uriMB.setChars(uri, 0, uri.length);
        mapper.map(aliasMB, uriMB, null, mappingData);
        Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    }
}
 
Example 19
Source File: TestMapper.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testMap() throws Exception {
    MappingData mappingData = new MappingData();
    MessageBytes host = MessageBytes.newInstance();
    host.setString("iowejoiejfoiew");
    MessageBytes wildcard = MessageBytes.newInstance();
    wildcard.setString("foo.net");
    MessageBytes alias = MessageBytes.newInstance();
    alias.setString("iowejoiejfoiew_alias");
    MessageBytes uri = MessageBytes.newInstance();
    uri.setString("/foo/bar/blah/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);

    mapper.map(host, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.getName());
    Assert.assertEquals("context2", mappingData.context.getName());
    Assert.assertEquals("wrapper5", mappingData.wrapper.getName());
    Assert.assertEquals("/foo/bar", mappingData.contextPath.toString());
    Assert.assertEquals("/blah/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());

    mappingData.recycle();
    uri.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(host, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.getName());
    Assert.assertEquals("context3", mappingData.context.getName());
    Assert.assertEquals("wrapper7", mappingData.wrapper.getName());
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    Assert.assertEquals("/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());

    mappingData.recycle();
    uri.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(wildcard, uri, null, mappingData);
    Assert.assertEquals("blah16", mappingData.host.getName());
    Assert.assertEquals("context4", mappingData.context.getName());
    Assert.assertEquals("context4-defaultWrapper", mappingData.wrapper.getName());
    Assert.assertEquals("", mappingData.contextPath.toString());
    Assert.assertEquals("/foo/bar/bla/bobou/foo", mappingData.wrapperPath.toString());
    Assert.assertTrue(mappingData.pathInfo.isNull());
    Assert.assertTrue(mappingData.redirectPath.isNull());

    mappingData.recycle();
    uri.setString("/foo/bar/bla/bobou/foo");
    uri.toChars();
    uri.getCharChunk().setLimit(-1);
    mapper.map(alias, uri, null, mappingData);
    Assert.assertEquals("blah7", mappingData.host.getName());
    Assert.assertEquals("context3", mappingData.context.getName());
    Assert.assertEquals("wrapper7", mappingData.wrapper.getName());
    Assert.assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    Assert.assertEquals("/bobou", mappingData.wrapperPath.toString());
    Assert.assertEquals("/foo", mappingData.pathInfo.toString());
    Assert.assertTrue(mappingData.redirectPath.isNull());
}
 
Example 20
Source File: ApplicationHttpRequest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
/**
 * Merge the parameters from the saved query parameter string (if any), and
 * the parameters already present on this request (if any), such that the
 * parameter values from the query string show up first if there are
 * duplicate parameter names.
 */
private void mergeParameters() {

    if ((queryParamString == null) || (queryParamString.length() < 1))
        return;

    // Parse the query string from the dispatch target
    Parameters paramParser = new Parameters();
    MessageBytes queryMB = MessageBytes.newInstance();
    queryMB.setString(queryParamString);

    // TODO
    // - Should only use body encoding if useBodyEncodingForURI is true
    // - Otherwise, should use URIEncoding
    // - The problem is that the connector is not available...

    String encoding = getCharacterEncoding();
    Charset charset = null;
    if (encoding != null) {
        try {
            charset = B2CConverter.getCharset(encoding);
            queryMB.setCharset(charset);
        } catch (UnsupportedEncodingException e) {
            // Fall-back to default (ISO-8859-1)
            charset = StandardCharsets.ISO_8859_1;
        }
    }

    paramParser.setQuery(queryMB);
    paramParser.setQueryStringCharset(charset);
    paramParser.handleQueryParameters();

    // Insert the additional parameters from the dispatch target
    Enumeration<String> dispParamNames = paramParser.getParameterNames();
    while (dispParamNames.hasMoreElements()) {
        String dispParamName = dispParamNames.nextElement();
        String[] dispParamValues = paramParser.getParameterValues(dispParamName);
        String[] originalValues = parameters.get(dispParamName);
        if (originalValues == null) {
            parameters.put(dispParamName, dispParamValues);
            continue;
        }
        parameters.put(dispParamName, mergeValues(dispParamValues, originalValues));
    }
}