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

The following examples show how to use org.apache.tomcat.util.buf.MessageBytes#newInstance() . 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: 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 2
Source File: TestMapper.java    From tomcatsrc 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 3
Source File: TesterHostPerformance.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testParseHost() throws Exception {
    long start = System.nanoTime();
    for (int i = 0; i < ITERATIONS; i++) {
        Host.parse(hostname);
    }
    long time = System.nanoTime() - start;

    System.out.println("St " + hostname + ": " + ITERATIONS + " iterations in " + time + "ns");
    System.out.println("St " + hostname + ": " + ITERATIONS * 1000000000.0/time + " iterations per second");

    MessageBytes mb = MessageBytes.newInstance();
    mb.setString(hostname);
    mb.toBytes();

    start = System.nanoTime();
    for (int i = 0; i < ITERATIONS; i++) {
        Host.parse(mb);
    }
    time = System.nanoTime() - start;

    System.out.println("MB " + hostname + ": " + ITERATIONS + " iterations in " + time + "ns");
    System.out.println("MB " + hostname + ": " + ITERATIONS * 1000000000.0/time + " iterations per second");
}
 
Example 4
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 5
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 6
Source File: ApplicationHttpRequest.java    From tomcatsrc with Apache License 2.0 5 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);

    String encoding = getCharacterEncoding();
    // No need to process null value, as ISO-8859-1 is the default encoding
    // in MessageBytes.toBytes().
    if (encoding != null) {
        try {
            queryMB.setCharset(B2CConverter.getCharset(encoding));
        } catch (UnsupportedEncodingException ignored) {
            // Fall-back to ISO-8859-1
        }
    }

    paramParser.setQuery(queryMB);
    paramParser.setQueryStringEncoding(encoding);
    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));
    }
}
 
Example 7
Source File: TestCoyoteAdapter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doTestNormalize(String input, String expected) {
    MessageBytes mb = MessageBytes.newInstance();
    byte[] b = input.getBytes(StandardCharsets.UTF_8);
    mb.setBytes(b, 0, b.length);

    boolean result = CoyoteAdapter.normalize(mb);
    mb.toString();

    if (expected == null) {
        Assert.assertFalse(result);
    } else {
        Assert.assertTrue(result);
        Assert.assertEquals(expected, mb.toString());
    }
}
 
Example 8
Source File: BSTAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "This method tests the authenticate method of BST Authenticator when all the relevant "
        + "details", dependsOnMethods = "testInitWithRemote")
public void testAuthenticate() throws NoSuchFieldException, IllegalAccessException, IOException {
    Request request = createSoapRequest("CorrectBST.xml");
    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);
    bstAuthenticator.canHandle(request);
    AuthenticationInfo authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "Authentication status of authentication info is wrong");
    Assert.assertEquals(authenticationInfo.getUsername(), "admin",
            "User name in the authentication info is different than original user");
    OAuth2TokenValidationResponseDTO unAuthorizedValidationRespose = new OAuth2TokenValidationResponseDTO();
    unAuthorizedValidationRespose.setValid(false);
    unAuthorizedValidationRespose.setErrorMsg("User is not authorized");
    Mockito.doReturn(oAuth2ClientApplicationDTO).when(oAuth2TokenValidationService)
            .findOAuthConsumerIfTokenIsValid(Mockito.any());
    oAuth2ClientApplicationDTO.setAccessTokenValidationResponse(unAuthorizedValidationRespose);
    AuthenticatorFrameworkDataHolder.getInstance().setOAuth2TokenValidationService(oAuth2TokenValidationService);
    authenticationInfo = bstAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.FAILURE,
            "Un-authorized user got authenticated with BST");
}
 
Example 9
Source File: TomcatHeadersAdapter.java    From java-technology-stack 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 10
Source File: FormAuthenticator.java    From Tomcat7.0.67 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 11
Source File: ApplicationContext.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
public DispatchData() {
    uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    mappingData = new MappingData();
}
 
Example 12
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 13
Source File: TestMapper.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testContextListConcurrencyBug56653() throws Exception {
    final Object host = new Object(); // "localhost";
    final Object contextRoot = new Object(); // "ROOT";
    final Object context1 = new Object(); // "foo";
    final Object context2 = new Object(); // "foo#bar";
    final Object context3 = new Object(); // "foo#bar#bla";
    final Object context4 = new Object(); // "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("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);
    assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

    mappingData.recycle();
    uriMB.setChars(uri, 0, uri.length);
    mapper.map(aliasMB, uriMB, null, mappingData);
    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);
        assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

        mappingData.recycle();
        uriMB.setChars(uri, 0, uri.length);
        mapper.map(aliasMB, uriMB, null, mappingData);
        assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    }
}
 
Example 14
Source File: TestMapper.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testReloadContextVersion() 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());

    // Mark context as paused
    // This is what happens when context reload starts
    mapper.pauseContextVersion(oldContext, hostName, contextPath, "0");

    mappingData.recycle();
    mapper.map(hostMB, uriMB, null, mappingData);
    assertEquals("blah7", mappingData.host.toString());
    assertEquals("context2", mappingData.context.toString());
    // Wrapper is not mapped for incoming requests if context is paused
    assertNull(mappingData.wrapper);

    // Re-add the same context, but different list of wrappers
    // This is what happens when context reload completes
    mapper.addContextVersion(
            hostName,
            oldHost,
            contextPath,
            "0",
            oldContext,
            null,
            null,
            Arrays.asList(new WrapperMappingInfo[] { new WrapperMappingInfo(
                    "/", "newDefaultWrapper", 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("blah7", mappingData.host.toString());
    assertEquals("context2", mappingData.context.toString());
    assertEquals("newDefaultWrapper", mappingData.wrapper.toString());
}
 
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: 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 17
Source File: ApplicationContext.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
public DispatchData() {
    uriMB = MessageBytes.newInstance();
    CharChunk uriCC = uriMB.getCharChunk();
    uriCC.setLimit(-1);
    mappingData = new MappingData();
}
 
Example 18
Source File: TestMapper.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testContextListConcurrencyBug56653() throws Exception {
    final Object host = new Object(); // "localhost";
    final Object contextRoot = new Object(); // "ROOT";
    final Object context1 = new Object(); // "foo";
    final Object context2 = new Object(); // "foo#bar";
    final Object context3 = new Object(); // "foo#bar#bla";
    final Object context4 = new Object(); // "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, false, false);
    mapper.addContextVersion("localhost", host, "/foo", "0", context1,
            new String[0], null, null, false, false);
    mapper.addContextVersion("localhost", host, "/foo/bar", "0", context2,
            new String[0], null, null, false, false);
    mapper.addContextVersion("localhost", host, "/foo/bar/bla", "0",
            context3, new String[0], null, null, false, false);
    mapper.addContextVersion("localhost", host, "/foo/bar/bla/baz", "0",
            context4, new String[0], null, null, false, false);

    final AtomicBoolean running = new AtomicBoolean(true);
    Thread t = new Thread() {
        @Override
        public void run() {
            for (int i = 0; i < 100000; i++) {
                mapper.removeContextVersion("localhost",
                        "/foo/bar/bla/baz", "0");
                mapper.addContextVersion("localhost", host,
                        "/foo/bar/bla/baz", "0", context4, new String[0],
                        null, null, false, false);
            }
            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);
    assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

    mappingData.recycle();
    uriMB.setChars(uri, 0, uri.length);
    mapper.map(aliasMB, uriMB, null, mappingData);
    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);
        assertEquals("/foo/bar/bla", mappingData.contextPath.toString());

        mappingData.recycle();
        uriMB.setChars(uri, 0, uri.length);
        mapper.map(aliasMB, uriMB, null, mappingData);
        assertEquals("/foo/bar/bla", mappingData.contextPath.toString());
    }
}
 
Example 19
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 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));
    }
}