Java Code Examples for com.sun.net.httpserver.HttpServer#stop()

The following examples show how to use com.sun.net.httpserver.HttpServer#stop() . 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: ContentTypeTestCase.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@Test(groups = { "wso2.esb" }, description = "Test different content types", dataProvider = "contentTypeProvider")
public void testReturnContentType(String dataProviderContentType) throws Exception {

    contentType = dataProviderContentType;
    HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
    server.createContext("/gettest", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    String url = "http://localhost:8480/serviceTest/test";
    HttpGet httpGet = new HttpGet(url);
    HttpResponse response = null;
    try {
        response = httpclient.execute(httpGet);
    } catch (IOException e) {
        log.error("Error Occurred while sending http get request. ", e);
    }
    log.info(response.getEntity().getContentType());
    log.info(response.getStatusLine().getStatusCode());

    assertEquals(response.getFirstHeader("Content-Type").getValue(), contentType,
            "Expected content type doesn't match");
    assertEquals(response.getStatusLine().getStatusCode(), HTTP_STATUS_OK, "response code doesn't match");

    server.stop(5);
}
 
Example 2
Source File: TestClusterManager.java    From rubix with Apache License 2.0 6 votes vote down vote up
@Test
/*
 * Tests that the worker nodes returned are correctly handled by PrestoClusterManager and sorted list of hosts is returned
 */
public void testGetNodes()
        throws IOException
{
  HttpServer server = createServer("/v1/node", new MultipleWorkers(), "/v1/node/failed", new NoFailedNode());

  log.info("STARTED SERVER");

  ClusterManager clusterManager = getPrestoClusterManager();
  List<String> nodes = clusterManager.getNodes();
  log.info("Got nodes: " + nodes);

  assertTrue(nodes.size() == 2, "Should only have two nodes");
  assertTrue(nodes.get(0).equals("192.168.1.3") && nodes.get(1).equals("192.168.2.252"), "Wrong nodes data");

  server.stop(0);
}
 
Example 3
Source File: ChunkedEncodingTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void test() {
    HttpServer server = null;
    try {
        serverDigest = MessageDigest.getInstance("MD5");
        clientDigest = MessageDigest.getInstance("MD5");
        server = startHttpServer();

        int port = server.getAddress().getPort();
        out.println ("Server listening on port: " + port);
        client("http://localhost:" + port + "/chunked/");

        if (!MessageDigest.isEqual(clientMac, serverMac)) {
            throw new RuntimeException(
             "Data received is NOT equal to the data sent");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (server != null)
            server.stop(0);
    }
}
 
Example 4
Source File: NoCache.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    ResponseCache.setDefault(new ThrowingCache());

    HttpServer server = startHttpServer();
    try {
        URL url = new URL("http://" + InetAddress.getLocalHost().getHostAddress()
                      + ":" + server.getAddress().getPort() + "/NoCache/");
        URLConnection uc = url.openConnection();
        uc.setUseCaches(false);
        uc.getInputStream().close();
    } finally {
        server.stop(0);
        // clear the system-wide cache handler, samevm/agentvm mode
        ResponseCache.setDefault(null);
    }
}
 
Example 5
Source File: Mapper_MappingFile_URL_Test.java    From rmlmapper-java with MIT License 6 votes vote down vote up
@Test
public void testValid() throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
    server.createContext("/mappingFile", new ValidMappingFileHandler());
    server.createContext("/inputFile", new ValidInputFileHandler());
    server.setExecutor(null); // creates a default executor
    server.start();

    Main.main("-m http://localhost:8080/mappingFile -o ./generated_output.nq".split(" "));
    compareFiles(
            "./generated_output.nq",
            "MAPPINGFILE_URL_TEST_valid/target_output.nq",
            false
    );

    server.stop(0);

    File outputFile = Utils.getFile("./generated_output.nq");
    assertTrue(outputFile.delete());
}
 
Example 6
Source File: ChunkedEncodingTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void test() {
    HttpServer server = null;
    try {
        serverDigest = MessageDigest.getInstance("MD5");
        clientDigest = MessageDigest.getInstance("MD5");
        server = startHttpServer();

        int port = server.getAddress().getPort();
        out.println ("Server listening on port: " + port);
        client("http://localhost:" + port + "/chunked/");

        if (!MessageDigest.isEqual(clientMac, serverMac)) {
            throw new RuntimeException(
             "Data received is NOT equal to the data sent");
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (server != null)
            server.stop(0);
    }
}
 
Example 7
Source File: InfluxDbHttpSenderTest.java    From dropwizard-metrics-influxdb with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotThrowException() throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(10081), 0);
    try {
        server.createContext("/write", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
        InfluxDbHttpSender influxDbHttpSender = new InfluxDbHttpSender(
            "http",
            "localhost",
            10081,
            "testdb",
            "asdf",
            TimeUnit.MINUTES,
            1000,
            1000,
            ""
        );
        assertThat(influxDbHttpSender.writeData(new byte[0]) == 0);
    } catch (IOException e) {
        throw new IOException(e);
    } finally {
        server.stop(0);
    }
}
 
Example 8
Source File: MissingTrailingSpace.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 {
        server.setExecutor(Executors.newFixedThreadPool(1));
        server.createContext(someContext, new HttpHandler() {
            @Override
            public void handle(HttpExchange msg) {
                try {
                    try {
                        msg.sendResponseHeaders(noMsgCode, -1);
                    } catch(IOException ioe) {
                        ioe.printStackTrace();
                    }
                } finally {
                    msg.close();
                }
            }
        });
        server.start();
        System.out.println("Server started at port "
                           + server.getAddress().getPort());

        runRawSocketHttpClient("localhost", server.getAddress().getPort());
    } finally {
        ((ExecutorService)server.getExecutor()).shutdown();
        server.stop(0);
    }
    System.out.println("Server finished.");
}
 
Example 9
Source File: HttpStreams.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
void test() throws Exception {
    HttpServer server = null;
    try {
        server = startHttpServer();
        String baseUrl = "http://localhost:" + server.getAddress().getPort() + "/";
        client(baseUrl +  "chunked/");
        client(baseUrl +  "fixed/");
        client(baseUrl +  "error/");
        client(baseUrl +  "chunkedError/");

        // Test with a response cache
        ResponseCache ch = ResponseCache.getDefault();
        ResponseCache.setDefault(new TrivialCacheHandler());
        try {
            client(baseUrl +  "chunked/");
            client(baseUrl +  "fixed/");
            client(baseUrl +  "error/");
            client(baseUrl +  "chunkedError/");
        } finally {
            ResponseCache.setDefault(ch);
        }
    } finally {
        if (server != null)
            server.stop(0);
    }

    System.out.println("passed: " + pass + ", failed: " + fail);
    if (fail > 0)
        throw new RuntimeException("some tests failed check output");
}
 
Example 10
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 11
Source File: FixedLengthInputStream.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 12
Source File: BasicLongCredentials.java    From TencentKona-8 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 13
Source File: BasicLongCredentials.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 {
    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 14
Source File: FixedLengthInputStream.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws IOException {
    HttpServer httpServer = startHttpServer();
    int port = httpServer.getAddress().getPort();
    try {
        URL url = new URL("http://localhost:" + port + "/flis/");
        HttpURLConnection uc = (HttpURLConnection)url.openConnection();
        uc.setDoOutput(true);
        uc.setRequestMethod("POST");
        uc.setFixedLengthStreamingMode(POST_SIZE);
        OutputStream os = uc.getOutputStream();

        /* create a 32K byte array with data to POST */
        int thirtyTwoK = 32 * 1024;
        byte[] ba = new byte[thirtyTwoK];
        for (int i =0; i<thirtyTwoK; i++)
            ba[i] = (byte)i;

        long times = POST_SIZE / thirtyTwoK;
        for (int i=0; i<times; i++) {
            os.write(ba);
        }

        os.close();
        InputStream is = uc.getInputStream();
        while(is.read(ba) != -1);
        is.close();

        pass();
    } finally {
        httpServer.stop(0);
    }
}
 
Example 15
Source File: CarBundlerTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void uploadToNexusV3(@TempDir final File temporaryFolder)
        throws IOException, InterruptedException, NoSuchMethodException {
    final String repoName = "releases";
    final String pathToJar = "foo/bar/dummy/1.2/dummy-1.2.jar";
    final File m2 = temporaryFolder;
    final File dep = createTempJar(m2, pathToJar);
    final byte[] expected;
    try (final InputStream in = new FileInputStream(dep)) {
        expected = IO.readBytes(in);
    }

    final CarBundler.Configuration configuration = createConfiguration(temporaryFolder, dep);

    final AtomicInteger serverCalls = new AtomicInteger(0);
    HttpServer server = createTestServerV3(serverCalls, expected, repoName, pathToJar);
    try {
        server.start();
        assertEquals(0, new ProcessBuilder(
                new File(System.getProperty("java.home"), "/bin/java" + (OS.WINDOWS.isCurrentOs() ? ".exe" : ""))
                        .getAbsolutePath(),
                "-jar", configuration.getOutput().getAbsolutePath(), "deploy-to-nexus", "--url",
                "http://localhost:" + server.getAddress().getPort(), "--repo", repoName, "--user", "admin",
                "--pass", "admin123", "--threads", "1", "--dir", m2.getAbsolutePath())
                        .inheritIO()
                        .start()
                        .waitFor());
    } finally {
        server.stop(0);
    }
    assertEquals(3, serverCalls.intValue());
}
 
Example 16
Source File: Deadlock.java    From openjdk-8 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: HttpClientFactoryImplTest.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void requestGenericWithNullPayload() throws IOException {
    final HttpServer server = createTestServer(HttpURLConnection.HTTP_OK);
    try {
        server.start();
        final GenericClient httpClient = newDefaultFactory().create(GenericClient.class, null);
        Response<byte[]> response = httpClient
                .execute(2000, 2000, "http://localhost:" + server.getAddress().getPort() + "/api/", "POST", null,
                        null, null);
        assertEquals("POST@Authorization=Basic ABCD/Connection=keep-alive@/api@", new String(response.body()));
    } finally {
        server.stop(0);
    }
}
 
Example 18
Source File: HttpOnly.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void test(String[] args) throws Exception {
    HttpServer server = startHttpServer();
    CookieHandler previousHandler = CookieHandler.getDefault();
    try {
        InetSocketAddress address = server.getAddress();
        URI uri = new URI("http://" + InetAddress.getLocalHost().getHostAddress()
                          + ":" + address.getPort() + URI_PATH);
        populateCookieStore(uri);
        doClient(uri);
    } finally {
        CookieHandler.setDefault(previousHandler);
        server.stop(0);
    }
}
 
Example 19
Source File: ClassLoad.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 {
     boolean error = true;

     // Start a dummy server to return 404
     HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
     HttpHandler handler = new HttpHandler() {
         public void handle(HttpExchange t) throws IOException {
             InputStream is = t.getRequestBody();
             while (is.read() != -1);
             t.sendResponseHeaders (404, -1);
             t.close();
         }
     };
     server.createContext("/", handler);
     server.start();

     // Client request
     try {
         URL url = new URL("http://localhost:" + server.getAddress().getPort());
         String name = args.length >= 2 ? args[1] : "foo.bar.Baz";
         ClassLoader loader = new URLClassLoader(new URL[] { url });
         System.out.println(url);
         Class c = loader.loadClass(name);
         System.out.println("Loaded class \"" + c.getName() + "\".");
     } catch (ClassNotFoundException ex) {
         System.out.println(ex);
         error = false;
     } finally {
         server.stop(0);
     }
     if (error)
         throw new RuntimeException("No ClassNotFoundException generated");
}
 
Example 20
Source File: TestHelper.java    From ant-ivy with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a HTTP server, backed by a local file system, which can be used as a repository to
 * serve Ivy module descriptors and artifacts. The context within the server will be backed by
 * {@code BASIC} authentication mechanism with {@code realm} as the realm and
 * {@code validCredentials} as the credentials that the server will recognize. The server will
 * allow access to resources, only if the credentials that are provided by the request, belong
 * to these credentials.
 * <p>
 * NOTE: This is supposed to be used only in test cases and only a limited functionality is
 * added in the handler(s) backing the server
 *
 * @param serverAddress           The address to which the server will be bound
 * @param webAppContext           The context root of the application which will be handling
 *                                the requests to the server
 * @param localFilesystemRepoRoot The path to the root directory containing the module
 *                                descriptors and artifacts
 * @param realm                   The realm to use for the {@code BASIC} auth mechanism
 * @param validCredentials        A {@link Map} of valid credentials, the key being the user
 *                                name and the value being the password, that the server will
 *                                use during the authentication process of the incoming requests
 * @return AutoCloseable
 * @throws IOException if something goes wrong
 */
public static AutoCloseable createBasicAuthHttpServerBackedRepo(final InetSocketAddress serverAddress, final String webAppContext,
                                                                final Path localFilesystemRepoRoot, final String realm,
                                                                final Map<String, String> validCredentials) throws IOException {
    final LocalFileRepoOverHttp handler = new LocalFileRepoOverHttp(webAppContext, localFilesystemRepoRoot);
    final HttpServer server = HttpServer.create(serverAddress, -1);
    // setup the handler
    final HttpContext context = server.createContext(webAppContext, handler);
    // setup basic auth on this context
    final com.sun.net.httpserver.Authenticator authenticator = new BasicAuthenticator(realm) {
        @Override
        public boolean checkCredentials(final String user, final String pass) {
            if (validCredentials == null || !validCredentials.containsKey(user)) {
                return false;
            }
            final String expectedPass = validCredentials.get(user);
            return expectedPass != null && expectedPass.equals(pass);
        }
    };
    context.setAuthenticator(authenticator);
    // setup a auth filter backed by the authenticator
    context.getFilters().add(new AuthFilter(authenticator));
    // start the server
    server.start();
    return new AutoCloseable() {
        @Override
        public void close() throws Exception {
            final int delaySeconds = 0;
            server.stop(delaySeconds);
        }
    };
}