commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ol...@apache.org
Subject cvs commit: jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server HttpService.java SimpleResponse.java
Date Fri, 27 Feb 2004 19:04:32 GMT
olegk       2004/02/27 11:04:32

  Added:       httpclient/src/test/org/apache/commons/httpclient/auth
                        TestBasicAuth.java
               httpclient/src/test/org/apache/commons/httpclient/server
                        HttpService.java SimpleResponse.java
  Log:
  Changelog
  
  * SimpleRequest and SimpleResponse classes factored out
  * Interface HttpService can be used instead of HttpRequestHandler to implement test cases
in a way very similar to writing servlets
  * Basic authentication test cases ported to the new testing framework
  
  Contributed by Oleg Kalnichevski
  
  Revision  Changes    Path
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/auth/TestBasicAuth.java
  
  Index: TestBasicAuth.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/auth/TestBasicAuth.java,v
1.1 2004/02/27 19:04:32 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/02/27 19:04:32 $
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  package org.apache.commons.httpclient.auth;
  
  import java.io.IOException;
  
  import junit.framework.Test;
  import junit.framework.TestSuite;
  
  import org.apache.commons.codec.binary.Base64;
  import org.apache.commons.httpclient.Header;
  import org.apache.commons.httpclient.HttpClientTestBase;
  import org.apache.commons.httpclient.HttpState;
  import org.apache.commons.httpclient.HttpStatus;
  import org.apache.commons.httpclient.UsernamePasswordCredentials;
  import org.apache.commons.httpclient.methods.GetMethod;
  import org.apache.commons.httpclient.server.HttpService;
  import org.apache.commons.httpclient.server.RequestLine;
  import org.apache.commons.httpclient.server.SimpleRequest;
  import org.apache.commons.httpclient.server.SimpleResponse;
  import org.apache.commons.httpclient.util.EncodingUtil;
  
  /**
   * Basic authentication test cases.
   *
   * @author Oleg Kalnichevski
   * 
   * @version $Id: TestBasicAuth.java,v 1.1 2004/02/27 19:04:32 olegk Exp $
   */
  public class TestBasicAuth extends HttpClientTestBase {
  
      // ------------------------------------------------------------ Constructor
      public TestBasicAuth(String testName) {
          super(testName);
      }
  
      // ------------------------------------------------------------------- Main
      public static void main(String args[]) {
          String[] testCaseName = { TestBasicAuth.class.getName() };
          junit.textui.TestRunner.main(testCaseName);
      }
  
      // ------------------------------------------------------- TestCase Methods
  
      public static Test suite() {
          return new TestSuite(TestBasicAuth.class);
      }
  
      private class BasicAuthService implements HttpService {
  
          public BasicAuthService() {
              super();
          }
  
          public boolean process(final SimpleRequest request, final SimpleResponse response)
              throws IOException
          {
              Header challenge = new Header("WWW-Authenticate", "Basic realm=\"test\"");
              RequestLine requestLine = request.getRequestLine();
              Header auth = request.getFirstHeader("Authorization");
              if (auth == null) { 
                  response.setStatusLine("HTTP/1.1 401 Unauthorized");
                  response.addHeader(challenge);
                  response.setBodyString("Authorization required");
                  return true;
              }
              boolean pass = false;
              String s = auth.getValue();
              int i = s.indexOf(" ");
              if (i != -1) {
                  String authtype = s.substring(0, i);
                  if ("BASIC".equalsIgnoreCase(authtype)) {
                      String creds = s.substring(i + 1, s.length());
                      creds = EncodingUtil.getAsciiString(
                          Base64.decodeBase64(
                              EncodingUtil.getAsciiBytes(creds)));
                      if (creds.equals("test:test")) {
                          pass = true;    
                      }
                  }
              }
              if (!pass) {
                  response.setStatusLine("HTTP/1.1 403 Forbidden");
                  response.addHeader(challenge);
                  response.setBodyString("Access forbidden");
                  return true;
              }
              response.setStatusLine("HTTP/1.1 200 OK");
              response.setBodyString("Authorization successful");
              return true;
          }
      }
  
      private class BasicAuthService2 implements HttpService {
  
          public BasicAuthService2() {
              super();
          }
  
          public boolean process(final SimpleRequest request, final SimpleResponse response)
              throws IOException
          {
              Header challenge = new Header("WWW-Authenticate", "Basic realm=\"test2\"");
              RequestLine requestLine = request.getRequestLine();
              Header auth = request.getFirstHeader("Authorization");
              if (auth == null) { 
                  response.setStatusLine("HTTP/1.1 401 Unauthorized");
                  response.addHeader(challenge);
                  response.setBodyString("Authorization required");
                  return true;
              }
              boolean pass = false;
              String s = auth.getValue();
              int i = s.indexOf(" ");
              if (i != -1) {
                  String authtype = s.substring(0, i);
                  if ("BASIC".equalsIgnoreCase(authtype)) {
                      String creds = s.substring(i + 1, s.length());
                      creds = EncodingUtil.getAsciiString(
                          Base64.decodeBase64(
                              EncodingUtil.getAsciiBytes(creds)));
                      if (creds.equals("test2:test2")) {
                          pass = true;    
                      }
                  }
              }
              if (!pass) {
                  response.setStatusLine("HTTP/1.1 403 Forbidden");
                  response.addHeader(challenge);
                  response.setBodyString("Access forbidden");
                  return true;
              }
              response.setStatusLine("HTTP/1.1 200 OK");
              response.setBodyString("Authorization successful");
              return true;
          }
      }
  
      private class BasicAuthService3 implements HttpService {
  
          public BasicAuthService3() {
              super();
          }
  
          public boolean process(final SimpleRequest request, final SimpleResponse response)
              throws IOException
          {
              Header challenge = new Header("WwW-AuThEnTiCaTe", "bAsIc ReAlM=\"test\"");
              RequestLine requestLine = request.getRequestLine();
              Header auth = request.getFirstHeader("Authorization");
              if (auth == null) { 
                  response.setStatusLine("HTTP/1.1 401 Unauthorized");
                  response.addHeader(challenge);
                  response.setBodyString("Authorization required");
                  return true;
              }
              boolean pass = false;
              String s = auth.getValue();
              int i = s.indexOf(" ");
              if (i != -1) {
                  String authtype = s.substring(0, i);
                  if ("BASIC".equalsIgnoreCase(authtype)) {
                      String creds = s.substring(i + 1, s.length());
                      creds = EncodingUtil.getAsciiString(
                          Base64.decodeBase64(
                              EncodingUtil.getAsciiBytes(creds)));
                      if (creds.equals("test:test")) {
                          pass = true;    
                      }
                  }
              }
              if (!pass) {
                  response.setStatusLine("HTTP/1.1 403 Forbidden");
                  response.addHeader(challenge);
                  response.setBodyString("Access forbidden");
                  return true;
              }
              response.setStatusLine("HTTP/1.1 200 OK");
              response.setBodyString("Authorization successful");
              return true;
          }
      }
  
      public void testBasicAuthenticationWithNoCreds() throws IOException {
          this.server.setHttpService(new BasicAuthService());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
              assertNotNull(httpget.getStatusLine());
              assertEquals(HttpStatus.SC_UNAUTHORIZED, httpget.getStatusLine().getStatusCode());
          } finally {
              httpget.releaseConnection();
          }
      }
  
      public void testBasicAuthenticationWithNoRealm() {
          String challenge = "Basic";
          try {
              AuthScheme authscheme = new BasicScheme();
              authscheme.processChallenge(challenge);
              fail("Should have thrown MalformedChallengeException");
          } catch(MalformedChallengeException e) {
              // expected
          }
      }
  
      public void testBasicAuthenticationWith88591Chars() throws Exception {
          int[] germanChars = { 0xE4, 0x2D, 0xF6, 0x2D, 0xFc };
          StringBuffer buffer = new StringBuffer();
          for (int i = 0; i < germanChars.length; i++) {
              buffer.append((char)germanChars[i]); 
          }
          
          UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("dh",
buffer.toString());
          assertEquals("Basic ZGg65C32Lfw=", 
              BasicScheme.authenticate(credentials, "ISO-8859-1"));
      }
      
      public void testBasicAuthenticationWithDefaultCreds() throws Exception {
          HttpState state = new HttpState();
          state.setCredentials(new HttpAuthRealm(), new UsernamePasswordCredentials("test",
"test"));
          this.client.setState(state);
          this.server.setHttpService(new BasicAuthService());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
          } finally {
              httpget.releaseConnection();
          }
          assertNotNull(httpget.getStatusLine());
          assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
          Header auth = httpget.getRequestHeader("Authorization");
          assertNotNull(auth);
          String expected = "Basic " + EncodingUtil.getAsciiString(
              Base64.encodeBase64(EncodingUtil.getAsciiBytes("test:test")));
          assertEquals(expected, auth.getValue());
      }
  
      public void testBasicAuthentication() throws Exception {
          HttpState state = new HttpState();
          HttpAuthRealm realm = new HttpAuthRealm(
              this.server.getLocalAddress(), 
              this.server.getLocalPort(),
              "test");
          state.setCredentials(realm, new UsernamePasswordCredentials("test", "test"));
          this.client.setState(state);
          this.server.setHttpService(new BasicAuthService());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
          } finally {
              httpget.releaseConnection();
          }
          assertNotNull(httpget.getStatusLine());
          assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
          Header auth = httpget.getRequestHeader("Authorization");
          assertNotNull(auth);
          String expected = "Basic " + EncodingUtil.getAsciiString(
              Base64.encodeBase64(EncodingUtil.getAsciiBytes("test:test")));
          assertEquals(expected, auth.getValue());
      }
  
      public void testBasicAuthenticationWithInvalidCredentials() throws Exception {
          HttpState state = new HttpState();
          HttpAuthRealm realm = new HttpAuthRealm(
              this.server.getLocalAddress(), 
              this.server.getLocalPort(),
              "test");
          state.setCredentials(realm, new UsernamePasswordCredentials("test", "stuff"));
          this.client.setState(state);
          this.server.setHttpService(new BasicAuthService());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
          } finally {
              httpget.releaseConnection();
          }
          assertNotNull(httpget.getStatusLine());
          assertEquals(HttpStatus.SC_FORBIDDEN, httpget.getStatusLine().getStatusCode());
      }
  
      public void testBasicAuthenticationWithMutlipleRealms() throws Exception {
          HttpState state = new HttpState();
          HttpAuthRealm realm1 = new HttpAuthRealm(
              this.server.getLocalAddress(), 
              this.server.getLocalPort(),
              "test");
          HttpAuthRealm realm2 = new HttpAuthRealm(
              this.server.getLocalAddress(), 
              this.server.getLocalPort(),
              "test2");
          state.setCredentials(realm1, new UsernamePasswordCredentials("test","test"));
          state.setCredentials(realm2, new UsernamePasswordCredentials("test2","test2"));
          this.client.setState(state);
          {
              this.server.setHttpService(new BasicAuthService());
              GetMethod httpget = new GetMethod("/test/");
              try {
                  this.client.executeMethod(httpget);
              } finally {
                  httpget.releaseConnection();
              }
              assertNotNull(httpget.getStatusLine());
              assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
              Header auth = httpget.getRequestHeader("Authorization");
              assertNotNull(auth);
              String expected = "Basic " + EncodingUtil.getAsciiString(
                  Base64.encodeBase64(EncodingUtil.getAsciiBytes("test:test")));
              assertEquals(expected, auth.getValue());
          }
          {
              this.server.setHttpService(new BasicAuthService2());
              GetMethod httpget = new GetMethod("/test2/");
              try {
                  this.client.executeMethod(httpget);
              } finally {
                  httpget.releaseConnection();
              }
              assertNotNull(httpget.getStatusLine());
              assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
              Header auth = httpget.getRequestHeader("Authorization");
              assertNotNull(auth);
              String expected = "Basic " + EncodingUtil.getAsciiString(
                  Base64.encodeBase64(EncodingUtil.getAsciiBytes("test2:test2")));
              assertEquals(expected, auth.getValue());
          }
      }
  
      public void testPreemptiveAuthorizationTrueWithCreds() throws Exception {
          HttpState state = new HttpState();
          state.setCredentials(new HttpAuthRealm(), new UsernamePasswordCredentials("test",
"test"));
          this.client.setState(state);
          this.client.getParams().setAuthenticationPreemptive(true);
          this.server.setHttpService(new BasicAuthService());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
          } finally {
              httpget.releaseConnection();
          }
          assertNotNull(httpget.getStatusLine());
          assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
          Header auth = httpget.getRequestHeader("Authorization");
          assertNotNull(auth);
          String expected = "Basic " + EncodingUtil.getAsciiString(
              Base64.encodeBase64(EncodingUtil.getAsciiBytes("test:test")));
          assertEquals(expected, auth.getValue());
      }
  
      public void testBasicAuthenticationCaseInsensitivity() throws Exception {
          HttpState state = new HttpState();
          HttpAuthRealm realm = new HttpAuthRealm(
              this.server.getLocalAddress(), 
              this.server.getLocalPort(),
              "test");
          state.setCredentials(realm, new UsernamePasswordCredentials("test", "test"));
          this.client.setState(state);
          this.server.setHttpService(new BasicAuthService3());
          GetMethod httpget = new GetMethod("/test/");
          try {
              this.client.executeMethod(httpget);
          } finally {
              httpget.releaseConnection();
          }
          assertNotNull(httpget.getStatusLine());
          assertEquals(HttpStatus.SC_OK, httpget.getStatusLine().getStatusCode());
          Header auth = httpget.getRequestHeader("Authorization");
          assertNotNull(auth);
          String expected = "Basic " + EncodingUtil.getAsciiString(
              Base64.encodeBase64(EncodingUtil.getAsciiBytes("test:test")));
          assertEquals(expected, auth.getValue());
      }
  }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/HttpService.java
  
  Index: HttpService.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/HttpService.java,v
1.1 2004/02/27 19:04:32 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/02/27 19:04:32 $
   *
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  import java.io.IOException;
  
  /**
   * Defines an HTTP request/response service for the SimpleHttpServer
   * 
   * @author Oleg Kalnichevski
   */
  public interface HttpService {
      /**
       * This interface represents a serice to process HTTP requests.
       * 
       * @param request       The HTTP request object.
       * @param response      The HTTP response object.
       * @return true if this service was able to handle the request, false otherwise.
       * 
       * @throws IOException
       */
      public boolean process(
          final SimpleRequest request, final SimpleResponse response) 
              throws IOException;
  }
  
  
  
  1.1                  jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java
  
  Index: SimpleResponse.java
  ===================================================================
  /*
   * $Header: /home/cvs/jakarta-commons/httpclient/src/test/org/apache/commons/httpclient/server/SimpleResponse.java,v
1.1 2004/02/27 19:04:32 olegk Exp $
   * $Revision: 1.1 $
   * $Date: 2004/02/27 19:04:32 $
   *
   * ====================================================================
   *
   *  Copyright 1999-2004 The Apache Software Foundation
   *
   *  Licensed under the Apache License, Version 2.0 (the "License");
   *  you may not use this file except in compliance with the License.
   *  You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
   *  Unless required by applicable law or agreed to in writing, software
   *  distributed under the License is distributed on an "AS IS" BASIS,
   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   *  See the License for the specific language governing permissions and
   *  limitations under the License.
   * ====================================================================
   *
   * This software consists of voluntary contributions made by many
   * individuals on behalf of the Apache Software Foundation.  For more
   * information on the Apache Software Foundation, please see
   * <http://www.apache.org/>.
   *
   * [Additional notices, if required by prior licensing conditions]
   *
   */
  
  package org.apache.commons.httpclient.server;
  
  import java.util.Iterator;
  
  import org.apache.commons.httpclient.Header;
  import org.apache.commons.httpclient.HeaderGroup;
  
  /**
   * A generic HTTP response.
   * 
   * @author Christian Kohlschuetter
   * @author Oleg Kalnichevski
   */
  public class SimpleResponse {
      
      private String statusLine = "HTTP/1.0 200 OK";
      private String contentType = "text/plain";
      private String bodyString = null;
      private HeaderGroup headers = new HeaderGroup();
  
      public SimpleResponse() {
          super();
      }
  
      public SimpleResponse(final String statusLine) {
          super();
          this.statusLine = statusLine;
      }
  
      public String getContentType() {
          return this.contentType;
      }
      
      public void setContentType(String string) {
          this.contentType = string;
      }
  
      public void setBodyString(String string) {
          this.bodyString = string;
      }
      
      public String getBodyString() {
          return this.bodyString;
      }
  
      public String getStatusLine() {
          return this.statusLine;
      }
  
      public void setStatusLine(String string) {
          this.statusLine = string;
      }
  
      public boolean containsHeader(final String name) {
          return this.headers.containsHeader(name);
      }
  
      public Header[] getHeaders() {
          return this.headers.getAllHeaders();
      }
  
      public void setHeader(final Header header) {
          if (header == null) {
              return;
          }
          Header[] headers = this.headers.getHeaders(header.getName());
          for (int i = 0; i < headers.length; i++) {
              this.headers.removeHeader(headers[i]);
          }
          this.headers.addHeader(header);
      }
  
      public void addHeader(final Header header) {
          if (header == null) {
              return;
          }
          this.headers.addHeader(header);
      }
  
      public void setHeaders(final Header[] headers) {
          if (headers == null) {
              return;
          }
          this.headers.setHeaders(headers);
      }
  
      public Iterator getHeaderIterator() {
          return this.headers.getIterator();
      }
  }
  
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message