Package com.sun.net.httpserver

Examples of com.sun.net.httpserver.HttpServer


   * @param args Command line
   */
  public static void main(String[] args) {
    try {
      // Create a EHS on the current machine on port 8123
      HttpServer ehs = HttpServer.create(new InetSocketAddress(InetAddress.getLocalHost(), 8123), 50);
      // Add a context associating a handler with a URI pattern
      // See URL below for details about handler and URI pattern :
      // http://java.sun.com/javase/6/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpServer.html
      HttpContext ctx = ehs.createContext("/jse6ehs", new SimpleHttpHandler());
      // Add a authenticator to the context
      ctx.setAuthenticator(new SimpleBasicAuthenticator("JSE6EHS Realm"));
      // Add filters to the context
      ctx.getFilters().add(new SimpleFilter("Filter01"));
      ctx.getFilters().add(new SimpleFilter("Filter02"));
      ctx.getFilters().add(new SimpleFilter("Filter03"));
      // Start the server
      ehs.start();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
View Full Code Here


        framework = new Framework();
        appConfig = framework.appConfig;

        long startTime = new Date().getTime();

        HttpServer server = null;
        Integer port = appConfig.getPort();
        if (port == null) {
            //
            // port auto の場合
            //
            port = 8081;
            for (int i = 0; i < SERACH_PORT_TIMES; i++) { // 空きポートを探す回数
                port += i;
                try {
                    server = HttpServer.create(new InetSocketAddress(
                            "localhost", port), 0);
                } catch (BindException e) {
                    continue;
                }
                break;
            }
        } else {
            server = HttpServer.create(
                    new InetSocketAddress("localhost", port), 0);
        }

        server.setExecutor(Executors.newCachedThreadPool());

        server.createContext("/", new HttpHandler() {
            public void handle(HttpExchange he) throws IOException {
                ActionContext context = new ActionContextImpl(he);
                String path = he.getRequestURI().getPath();
                // 拡張子なしをデフォルトでActionとして扱う。
                if (path.indexOf('.') == -1) {
                    framework.processDynamicResource(context);
                } else {
                    processStaticResource(context);
                }
                ActionContext.remove();
            }
        });

        server.start();
        logger.info("port: " + port);

        String browserInitPath = appConfig.getBrowserInitPath();
        if (browserInitPath != null) {
            String url = "http://localhost:" + port + browserInitPath;
View Full Code Here

        }
    }

    public static DomainHttpServer create(InetSocketAddress socket, int backlog, ModelController modelController,
            Executor executor, File serverTempDir) throws IOException {
        HttpServer server = HttpServer.create(socket, backlog);
        DomainHttpServer me = new DomainHttpServer(server, modelController, serverTempDir);
        server.createContext(DOMAIN_API_CONTEXT, me);
        server.setExecutor(executor);

        return new DomainHttpServer(server, modelController, serverTempDir);
    }
View Full Code Here

            if(factory == null) {
                s_logger.error("Unable to load HTTP server factory");
                System.exit(1);
            }
           
            HttpServer server = factory.createHttpServerInstance(httpListenPort);
            server.createContext("/getscreen", new ConsoleProxyThumbnailHandler());
            server.createContext("/resource/", new ConsoleProxyResourceHandler());
            server.createContext("/ajax", new ConsoleProxyAjaxHandler());
            server.createContext("/ajaximg", new ConsoleProxyAjaxImageHandler());
            server.setExecutor(new ThreadExecutor()); // creates a default executor
            server.start();
        } catch(Exception e) {
            s_logger.error(e.getMessage(), e);
            System.exit(1);
        }
    }
View Full Code Here

    }
   
    private static void startupHttpCmdPort() {
        try {
            s_logger.info("Listening for HTTP CMDs on port " + httpCmdListenPort);
            HttpServer cmdServer = HttpServer.create(new InetSocketAddress(httpCmdListenPort), 2);
            cmdServer.createContext("/cmd", new ConsoleProxyCmdHandler());
            cmdServer.setExecutor(new ThreadExecutor()); // creates a default executor
            cmdServer.start();
        } catch(Exception e) {
            s_logger.error(e.getMessage(), e);
            System.exit(1);
        }
    }
View Full Code Here

        Assert.assertEquals("keith", responseMsg.getContent(String.class));*/
    }

    @Test
    public void restGatewayReferenceTimeout() throws Exception {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10);
        httpServer.setExecutor(null); // creates a default executor
        httpServer.start();
        HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() {
            public void handle(HttpExchange exchange) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException ie) {
                        //Ignore
            }}});
        try {
            Message responseMsg = _consumerService2.operation("addGreeter").sendInOut("magesh");
        } catch (Exception e) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out"));
        }
        httpServer.stop(0);
    }
View Full Code Here

        assertEquals(1,result.getComplete().size());
    }


    public HttpServer createHttpServer() throws IOException {
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8069), 0);

        // create and register our handler
        httpServer.createContext("/bucketname/standard-key.txt",new HttpHandler() {
            public void handle(HttpExchange exchange) throws IOException {
                byte[] response = "loaded=true".getBytes("UTF-8");
                    // RFC 2616 says HTTP headers are case-insensitive - but the
                // Amazon S3 client will crash if ETag has a different
                // capitalisation. And this HttpServer normalises the names
                // of headers using "ETag"->"Etag" if you use put, add or
                // set. But not if you use 'putAll' so that's what I use.
                Map<String, List<String>> responseHeaders = new HashMap();
                responseHeaders.put("ETag", Collections.singletonList("\"TEST-ETAG\""));
                responseHeaders.put("Content-Type", Collections.singletonList("text/plain"));
                exchange.getResponseHeaders().putAll(responseHeaders);
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
                exchange.getResponseBody().write(response);
                exchange.close();
            }
        });

        httpServer.createContext("/bucketname/404.txt",new HttpHandler() {
            public void handle(HttpExchange exchange) throws IOException {
                byte[] response = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                        "<Error>\n" +
                        "  <Code>NoSuchKey</Code>\n" +
                        "  <Message>The resource you requested does not exist</Message>\n" +
                        "  <Resource>/bucketname/404.txt</Resource> \n" +
                        "</Error>").getBytes("UTF-8");
                exchange.sendResponseHeaders(HttpURLConnection.HTTP_NOT_FOUND,response.length);
                exchange.getResponseBody().write(response);
                exchange.close();
            }
        });

        httpServer.start();
        return httpServer;
    }
View Full Code Here

    @Test
    public void soapGatewayReferenceTimeout() throws Exception {
        Element input = SOAPUtil.parseAsDom("<test:sayHello xmlns:test=\"urn:switchyard-component-soap:test-ws:1.0\">"
                     + "   <arg0>Hello</arg0>"
                     + "</test:sayHello>").getDocumentElement();
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8090), 10);
        httpServer.setExecutor(null); // creates a default executor
        httpServer.start();
        HttpContext httpContext = httpServer.createContext("/forever", new HttpHandler() {
            public void handle(HttpExchange exchange) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException ie) {
                        //Ignore
            }}});
        try {
            Message responseMsg = _consumerService3.operation("sayHello").sendInOut(input);
        } catch (Exception e) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            e.printStackTrace(new PrintStream(baos));
            Assert.assertTrue(baos.toString().contains("SocketTimeoutException: Read timed out"));
        }
        httpServer.stop(0);
    }
View Full Code Here

     * it uses that server to create a context. Otherwise, it creates a new
     * HTTP server. This sever is added to servers Map.
     */
    /*package*/ HttpContext createContext(String address) {
        try {
            HttpServer server;
            ServerState state;
            URL url = new URL(address);
            int port = url.getPort();
            if (port == -1) {
                port = url.getDefaultPort();
            }
            InetSocketAddress inetAddress = new InetSocketAddress(url.getHost(),
                port);
            synchronized(servers) {
                state = servers.get(inetAddress);
                if (state == null) {
                    logger.fine("Creating new HTTP Server at "+inetAddress);
                    server = HttpServer.create(inetAddress, 5);
                    server.setExecutor(Executors.newCachedThreadPool());
                    String path = url.toURI().getPath();
                    logger.fine("Creating HTTP Context at = "+path);
                    HttpContext context = server.createContext(path);
                    server.start();
                    logger.fine("HTTP server started = "+inetAddress);
                    state = new ServerState(server);
                    servers.put(inetAddress, state);
                    return context;
                }
            }
            server = state.getServer();
            logger.fine("Creating HTTP Context at = "+url.getPath());
            HttpContext context = server.createContext(url.getPath());
            state.oneMoreContext();
            return context;
        } catch(Exception e) {
            throw new ServerRtException("server.rt.err",e );
        }
View Full Code Here

    public static void main(String[] args) throws Exception
    {
        String host="localhost";
        int port = 8080;
       
        HttpServer server = new JettyHttpServerProvider().createHttpServer(new
                InetSocketAddress(host, port), 10);
        server.start();
       
        final HttpContext httpContext = server.createContext("/",
                new HttpHandler()
        {

            public void handle(HttpExchange exchange) throws IOException
            {
View Full Code Here

TOP

Related Classes of com.sun.net.httpserver.HttpServer

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.