com.sun.net.httpserver.HttpContext Java Examples

The following examples show how to use com.sun.net.httpserver.HttpContext. 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: RestApiCallDemoClient.java    From iotplatform with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
  HttpServer server = HttpServer.create(new InetSocketAddress(HTTP_SERVER_PORT), 0);

  HttpContext secureContext = server.createContext(DEMO_REST_BASIC_AUTH, new RestDemoHandler());
  secureContext.setAuthenticator(new BasicAuthenticator("demo-auth") {
    @Override
    public boolean checkCredentials(String user, String pwd) {
      return user.equals(USERNAME) && pwd.equals(PASSWORD);
    }
  });

  server.createContext(DEMO_REST_NO_AUTH, new RestDemoHandler());
  server.setExecutor(null);
  System.out.println("[*] Waiting for messages.");
  server.start();
}
 
Example #2
Source File: ContextStackAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void stackRegistry_autoConfigurationEnabled_returnsAutoConfiguredStackRegistry()
		throws Exception {
	HttpServer httpServer = MetaDataServer.setupHttpServer();
	HttpContext httpContext = httpServer.createContext(
			"/latest/meta-data/instance-id",
			new MetaDataServer.HttpResponseWriterHandler("test"));

	this.contextRunner
			.withUserConfiguration(
					AutoConfigurationStackRegistryTestConfiguration.class)
			.run(context -> assertThat(context.getBean(StackResourceRegistry.class))
					.isNotNull());

	httpServer.removeContext(httpContext);
	MetaDataServer.shutdownHttpServer();
}
 
Example #3
Source File: SimpleHttpServerFactoryBean.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException {
	InetSocketAddress address = (this.hostname != null ?
			new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
	this.server = HttpServer.create(address, this.backlog);
	if (this.executor != null) {
		this.server.setExecutor(this.executor);
	}
	if (this.contexts != null) {
		this.contexts.forEach((key, context) -> {
			HttpContext httpContext = this.server.createContext(key, context);
			if (this.filters != null) {
				httpContext.getFilters().addAll(this.filters);
			}
			if (this.authenticator != null) {
				httpContext.setAuthenticator(this.authenticator);
			}
		});
	}
	if (logger.isInfoEnabled()) {
		logger.info("Starting HttpServer at address " + address);
	}
	this.server.start();
}
 
Example #4
Source File: SimpleHttpServerFactoryBean.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException {
	InetSocketAddress address = (this.hostname != null ?
			new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
	this.server = HttpServer.create(address, this.backlog);
	if (this.executor != null) {
		this.server.setExecutor(this.executor);
	}
	if (this.contexts != null) {
		for (String key : this.contexts.keySet()) {
			HttpContext httpContext = this.server.createContext(key, this.contexts.get(key));
			if (this.filters != null) {
				httpContext.getFilters().addAll(this.filters);
			}
			if (this.authenticator != null) {
				httpContext.setAuthenticator(this.authenticator);
			}
		}
	}
	if (this.logger.isInfoEnabled()) {
		this.logger.info("Starting HttpServer at address " + address);
	}
	this.server.start();
}
 
Example #5
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static HTTPTestServer createProxy(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate,
                                    String path)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);

    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer server = protocol == HttpProtocolType.HTTPS
            ? new HttpsProxyTunnel(impl, null, delegate)
            : new HTTPTestServer(impl, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();

    return server;
}
 
Example #6
Source File: RpcHandler.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * Create the JSON-RPC request handler
 *
 * @param rpcPort
 *            RPC port
 * @param rpcAllowIp
 *            List of allowed host addresses
 * @param rpcUser
 *            RPC user
 * @param rpcPassword
 *            RPC password
 */
public RpcHandler(int rpcPort, List<InetAddress> rpcAllowIp, String rpcUser, String rpcPassword) {
	this.rpcPort = rpcPort;
	this.rpcAllowIp = rpcAllowIp;
	this.rpcUser = rpcUser;
	this.rpcPassword = rpcPassword;
	//
	// Create the HTTP server using a single execution thread
	//
	try {
		server = HttpServer.create(new InetSocketAddress(rpcPort), 10);
		HttpContext context = server.createContext("/", this);
		context.setAuthenticator(new RpcAuthenticator(LSystem.applicationName));
		server.setExecutor(null);
		server.start();
		BTCLoader.info(String.format("RPC handler started on port %d", rpcPort));
	} catch (IOException exc) {
		BTCLoader.error("Unable to set up HTTP server", exc);
	}
}
 
Example #7
Source File: ContextInstanceDataConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void propertySource_enableInstanceDataWithCustomValueSeparator_propertySourceConfiguredAndUsesCustomValueSeparator()
		throws Exception {
	// @checkstyle:on
	// Arrange
	HttpServer httpServer = MetaDataServer.setupHttpServer();
	HttpContext httpContext = httpServer.createContext("/latest/user-data",
			new MetaDataServer.HttpResponseWriterHandler("a=b;c=d"));

	// Act
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithCustomValueSeparator.class);

	// Assert
	assertThat(this.context.getEnvironment().getProperty("a")).isEqualTo("b");
	assertThat(this.context.getEnvironment().getProperty("c")).isEqualTo("d");

	httpServer.removeContext(httpContext);
}
 
Example #8
Source File: ContextStackConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void stackRegistry_noStackNameConfigured_returnsAutoConfiguredStackRegistry()
		throws Exception {
	// Arrange
	this.context = new AnnotationConfigApplicationContext();
	this.context.register(ApplicationConfigurationWithEmptyStackName.class);
	HttpServer httpServer = MetaDataServer.setupHttpServer();
	HttpContext httpContext = httpServer.createContext(
			"/latest/meta-data/instance-id",
			new MetaDataServer.HttpResponseWriterHandler("test"));

	// Act
	this.context.refresh();

	// Assert
	StackResourceRegistry stackResourceRegistry = this.context
			.getBean(StackResourceRegistry.class);
	assertThat(stackResourceRegistry).isNotNull();
	assertThat(stackResourceRegistry.getStackName()).isEqualTo("testStack");

	httpServer.removeContext(httpContext);
}
 
Example #9
Source File: ContextInstanceDataAutoConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void placeHolder_noExplicitConfiguration_missingInstanceDataResolverForNotAwsEnvironment()
		throws Exception {
	// Arrange
	HttpServer httpServer = MetaDataServer.setupHttpServer();
	HttpContext instanceIdHttpContext = httpServer.createContext(
			"/latest/meta-data/instance-id",
			new MetaDataServer.HttpResponseWriterHandler(null));

	this.context = new AnnotationConfigApplicationContext();
	this.context.register(ContextInstanceDataAutoConfiguration.class);

	// Act
	this.context.refresh();

	// Assert
	assertThat(this.context
			.containsBean("AmazonEc2InstanceDataPropertySourcePostProcessor"))
					.isFalse();

	httpServer.removeContext(instanceIdHttpContext);
}
 
Example #10
Source File: HTTPTestServer.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static HTTPTestServer createServer(HttpProtocolType protocol,
                                    HttpAuthType authType,
                                    HttpTestAuthenticator auth,
                                    HttpSchemeType schemeType,
                                    HttpHandler delegate,
                                    String path)
        throws IOException {
    Objects.requireNonNull(authType);
    Objects.requireNonNull(auth);

    HttpServer impl = createHttpServer(protocol);
    final HTTPTestServer server = new HTTPTestServer(impl, null, delegate);
    final HttpHandler hh = server.createHandler(schemeType, auth, authType);
    HttpContext ctxt = impl.createContext(path, hh);
    server.configureAuthentication(ctxt, schemeType, auth, authType);
    impl.start();
    return server;
}
 
Example #11
Source File: SimpleHttpServerFactoryBean.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException {
	InetSocketAddress address = (this.hostname != null ?
			new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
	this.server = HttpServer.create(address, this.backlog);
	if (this.executor != null) {
		this.server.setExecutor(this.executor);
	}
	if (this.contexts != null) {
		for (String key : this.contexts.keySet()) {
			HttpContext httpContext = this.server.createContext(key, this.contexts.get(key));
			if (this.filters != null) {
				httpContext.getFilters().addAll(this.filters);
			}
			if (this.authenticator != null) {
				httpContext.setAuthenticator(this.authenticator);
			}
		}
	}
	if (this.logger.isInfoEnabled()) {
		this.logger.info("Starting HttpServer at address " + address);
	}
	this.server.start();
}
 
Example #12
Source File: SimpleHttpServerFactoryBean.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public void afterPropertiesSet() throws IOException {
	InetSocketAddress address = (this.hostname != null ?
			new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
	this.server = HttpServer.create(address, this.backlog);
	if (this.executor != null) {
		this.server.setExecutor(this.executor);
	}
	if (this.contexts != null) {
		this.contexts.forEach((key, context) -> {
			HttpContext httpContext = this.server.createContext(key, context);
			if (this.filters != null) {
				httpContext.getFilters().addAll(this.filters);
			}
			if (this.authenticator != null) {
				httpContext.setAuthenticator(this.authenticator);
			}
		});
	}
	if (logger.isInfoEnabled()) {
		logger.info("Starting HttpServer at address " + address);
	}
	this.server.start();
}
 
Example #13
Source File: ContextInstanceDataConfigurationTest.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Test
void propertySource_enableInstanceDataWithCustomAttributeSeparator_propertySourceConfiguredAndUsesCustomAttributeSeparator()
		throws Exception {
	// @checkstyle:on
	// Arrange
	HttpServer httpServer = MetaDataServer.setupHttpServer();
	HttpContext httpContext = httpServer.createContext("/latest/user-data",
			new MetaDataServer.HttpResponseWriterHandler("a:b/c:d"));

	// Act
	this.context = new AnnotationConfigApplicationContext(
			ApplicationConfigurationWithCustomAttributeSeparator.class);

	// Assert
	assertThat(this.context.getEnvironment().getProperty("a")).isEqualTo("b");
	assertThat(this.context.getEnvironment().getProperty("c")).isEqualTo("d");

	httpServer.removeContext(httpContext);
}
 
Example #14
Source File: Deadlock.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #15
Source File: HttpEndpoint.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public void publish(Object serverContext) {
    if (serverContext instanceof javax.xml.ws.spi.http.HttpContext) {
        setHandler((javax.xml.ws.spi.http.HttpContext)serverContext);
        return;
    }
    if (serverContext instanceof HttpContext) {
        this.httpContext = (HttpContext)serverContext;
        setHandler(httpContext);
        return;
    }
    throw new ServerRtException(ServerMessages.NOT_KNOW_HTTP_CONTEXT_TYPE(
            serverContext.getClass(), HttpContext.class,
            javax.xml.ws.spi.http.HttpContext.class));
}
 
Example #16
Source File: Deadlock.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #17
Source File: HttpNegotiateServer.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and starts an HTTP or proxy server that requires
 * Negotiate authentication.
 * @param scheme "Negotiate" or "Kerberos"
 * @param principal the krb5 service principal the server runs with
 * @return the server
 */
public static HttpServer httpd(String scheme, boolean proxy,
        String principal, String ktab) throws Exception {
    MyHttpHandler h = new MyHttpHandler();
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    HttpContext hc = server.createContext("/", h);
    hc.setAuthenticator(new MyServerAuthenticator(
            proxy, scheme, principal, ktab));
    server.start();
    return server;
}
 
Example #18
Source File: BasicLongCredentials.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example #19
Source File: Deadlock.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #20
Source File: HttpEndpoint.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void publish(Object serverContext) {
    if (serverContext instanceof javax.xml.ws.spi.http.HttpContext) {
        setHandler((javax.xml.ws.spi.http.HttpContext)serverContext);
        return;
    }
    if (serverContext instanceof HttpContext) {
        this.httpContext = (HttpContext)serverContext;
        setHandler(httpContext);
        return;
    }
    throw new ServerRtException(ServerMessages.NOT_KNOW_HTTP_CONTEXT_TYPE(
            serverContext.getClass(), HttpContext.class,
            javax.xml.ws.spi.http.HttpContext.class));
}
 
Example #21
Source File: MultiAuthTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static HttpServer createServer(ExecutorService e, BasicAuthenticator sa) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 10);
    Handler h = new Handler();
    HttpContext serverContext = server.createContext("/test", h);
    serverContext.setAuthenticator(sa);
    server.setExecutor(e);
    server.start();
    return server;
}
 
Example #22
Source File: SimpleHttpServerJaxWsServiceExporter.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Build the HttpContext for the given endpoint.
 * @param endpoint the JAX-WS Provider Endpoint object
 * @param serviceName the given service name
 * @return the fully populated HttpContext
 */
protected HttpContext buildHttpContext(Endpoint endpoint, String serviceName) {
	String fullPath = calculateEndpointPath(endpoint, serviceName);
	HttpContext httpContext = this.server.createContext(fullPath);
	if (this.filters != null) {
		httpContext.getFilters().addAll(this.filters);
	}
	if (this.authenticator != null) {
		httpContext.setAuthenticator(this.authenticator);
	}
	return httpContext;
}
 
Example #23
Source File: Deadlock.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #24
Source File: BasicLongCredentials.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example #25
Source File: Deadlock.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #26
Source File: B8185898.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    ExecutorService exec = Executors.newCachedThreadPool();
    InetAddress loopback = InetAddress.getLoopbackAddress();

    try {
        InetSocketAddress addr = new InetSocketAddress(loopback, 0);
        server = HttpServer.create(addr, 100);
        HttpHandler handler = new Handler();
        HttpContext context = server.createContext("/", handler);
        server.setExecutor(exec);
        server.start();

        port = server.getAddress().getPort();
        System.out.println("Server on port: " + port);
        url = URIBuilder.newBuilder()
                .scheme("http")
                .loopback()
                .port(port)
                .path("/foo")
                .toURLUnchecked();
        System.out.println("URL: " + url);
        testMessageHeader();
        testMessageHeaderMethods();
        testURLConnectionMethods();
    } finally {
        server.stop(0);
        System.out.println("After server shutdown");
        exec.shutdown();
    }
}
 
Example #27
Source File: BasicLongCredentials.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example #28
Source File: HttpNegotiateServer.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and starts an HTTP or proxy server that requires
 * Negotiate authentication.
 * @param scheme "Negotiate" or "Kerberos"
 * @param principal the krb5 service principal the server runs with
 * @return the server
 */
public static HttpServer httpd(String scheme, boolean proxy,
        String principal, String ktab) throws Exception {
    MyHttpHandler h = new MyHttpHandler();
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    HttpContext hc = server.createContext("/", h);
    hc.setAuthenticator(new MyServerAuthenticator(
            proxy, scheme, principal, ktab));
    server.start();
    return server;
}
 
Example #29
Source File: Deadlock.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    Handler handler = new Handler();
    InetSocketAddress addr = new InetSocketAddress (0);
    HttpServer server = HttpServer.create(addr, 0);
    HttpContext ctx = server.createContext("/test", handler);
    BasicAuthenticator a = new BasicAuthenticator("[email protected]") {
        @Override
        public boolean checkCredentials (String username, String pw) {
            return "fred".equals(username) && pw.charAt(0) == 'x';
        }
    };

    ctx.setAuthenticator(a);
    ExecutorService executor = Executors.newCachedThreadPool();
    server.setExecutor(executor);
    server.start ();
    java.net.Authenticator.setDefault(new MyAuthenticator());

    System.out.print("Deadlock: " );
    for (int i=0; i<2; i++) {
        Runner t = new Runner(server, i);
        t.start();
        t.join();
    }
    server.stop(2);
    executor.shutdown();
    if (error) {
        throw new RuntimeException("test failed error");
    }

    if (count != 2) {
        throw new RuntimeException("test failed count = " + count);
    }
    System.out.println("OK");

}
 
Example #30
Source File: HttpNegotiateServer.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates and starts an HTTP or proxy server that requires
 * Negotiate authentication.
 * @param scheme "Negotiate" or "Kerberos"
 * @param principal the krb5 service principal the server runs with
 * @return the server
 */
public static HttpServer httpd(String scheme, boolean proxy,
        String principal, String ktab) throws Exception {
    MyHttpHandler h = new MyHttpHandler();
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    HttpContext hc = server.createContext("/", h);
    hc.setAuthenticator(new MyServerAuthenticator(
            proxy, scheme, principal, ktab));
    server.start();
    return server;
}