Java 类com.sun.net.httpserver.HttpContext 实例源码

项目:NoraUi    文件:AuthUT.java   
public void start() {
    try {
        server = HttpServer.create(new InetSocketAddress(8000), 0);
    } catch (Exception e) {
        Assert.fail("Exception thrown: " + e.getMessage());
    }
    server.createContext("/unprotected", new TestHttpHandler());

    HttpContext protectedContext = server.createContext("/protected", new TestHttpHandler());
    protectedContext.setAuthenticator(new BasicAuthenticator("get") {

        @Override
        public boolean checkCredentials(String user, String pwd) {
            return user.equals("admin") && pwd.equals("admin");
        }

    });
    server.setExecutor(null);
    server.start();
}
项目:azure-libraries-for-java    文件:WebServerWithDelegatedCredentials.java   
/**
 * Main function which runs the actual sample.
 * @param authFile the auth file backing the web server
 * @return true if sample runs successfully
 * @throws Exception exceptions running the server
 */
public static boolean runSample(File authFile) throws Exception {
    final String redirectUrl = "http://localhost:8000";
    final ExecutorService executor = Executors.newCachedThreadPool();

    try {
        DelegatedTokenCredentials credentials = DelegatedTokenCredentials.fromFile(authFile, redirectUrl);

        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        HttpContext context = server.createContext("/", new MyHandler());
        context.getAttributes().put("credentials", credentials);
        server.setExecutor(Executors.newCachedThreadPool()); // creates a default executor
        server.start();

        // Use a browser to login within a minute
        Thread.sleep(60000);
        return true;
    } finally {
        executor.shutdown();
    }
}
项目:lams    文件:SimpleHttpServerFactoryBean.java   
@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();
}
项目:jdk8u-jdk    文件:HttpNegotiateServer.java   
/**
 * 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;
}
项目:openjdk-jdk10    文件:Security.java   
public static void initServer() throws Exception {
    String portstring = System.getProperty("port.number");
    port = portstring != null ? Integer.parseInt(portstring) : 0;
    portstring = System.getProperty("port.number1");
    proxyPort = portstring != null ? Integer.parseInt(portstring) : 0;

    Logger logger = Logger.getLogger("com.sun.net.httpserver");
    ConsoleHandler ch = new ConsoleHandler();
    logger.setLevel(Level.ALL);
    ch.setLevel(Level.ALL);
    logger.addHandler(ch);
    String root = System.getProperty ("test.src")+ "/docs";
    InetSocketAddress addr = new InetSocketAddress (port);
    s1 = HttpServer.create (addr, 0);
    if (s1 instanceof HttpsServer) {
        throw new RuntimeException ("should not be httpsserver");
    }
    HttpHandler h = new FileServerHandler (root);
    HttpContext c = s1.createContext ("/files", h);

    HttpHandler h1 = new RedirectHandler ("/redirect");
    HttpContext c1 = s1.createContext ("/redirect", h1);

    executor = Executors.newCachedThreadPool();
    s1.setExecutor (executor);
    s1.start();

    if (port == 0)
        port = s1.getAddress().getPort();
    else {
        if (s1.getAddress().getPort() != port)
            throw new RuntimeException("Error wrong port");
        System.out.println("Port was assigned by Driver");
    }
    System.out.println("HTTP server port = " + port);
    httproot = "http://127.0.0.1:" + port + "/files/";
    redirectroot = "http://127.0.0.1:" + port + "/redirect/";
    uri = new URI(httproot);
    fileuri = httproot + "foo.txt";
}
项目:openjdk-jdk10    文件:ProxyTest.java   
static HttpServer createHttpsServer() throws IOException, NoSuchAlgorithmException {
    HttpsServer server = com.sun.net.httpserver.HttpsServer.create();
    HttpContext context = server.createContext(PATH);
    context.setHandler(new HttpHandler() {
        @Override
        public void handle(HttpExchange he) throws IOException {
            he.getResponseHeaders().add("encoding", "UTF-8");
            he.sendResponseHeaders(200, RESPONSE.length());
            he.getResponseBody().write(RESPONSE.getBytes(StandardCharsets.UTF_8));
            he.close();
        }
    });

    server.setHttpsConfigurator(new Configurator(SSLContext.getDefault()));
    server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
    return server;
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
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;
}
项目:openjdk-jdk10    文件:HTTPTestServer.java   
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;
}
项目:openjdk-jdk10    文件:SimpleHttpServer.java   
public void start() {
    MyHttpHandler handler = new MyHttpHandler(_docroot);
    InetSocketAddress addr = new InetSocketAddress(_port);
    try {
        _httpserver = HttpServer.create(addr, 0);
    } catch (IOException ex) {
        throw new RuntimeException("cannot create httpserver", ex);
    }

    //TestHandler is mapped to /test
    HttpContext ctx = _httpserver.createContext(_context, handler);

    _executor = Executors.newCachedThreadPool();
    _httpserver.setExecutor(_executor);
    _httpserver.start();

    _address = "http://localhost:" + _httpserver.getAddress().getPort();
}
项目:iotplatform    文件:RestApiCallDemoClient.java   
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();
}
项目:spring4-understanding    文件:SimpleHttpServerFactoryBean.java   
@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();
}
项目:my-spring-cache-redis    文件:SimpleHttpServerFactoryBean.java   
@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();
}
项目:openbravo-pos    文件:JettyHttpExchange.java   
public JettyHttpExchange(HttpContext context, HttpServletRequest req,
        HttpServletResponse resp)
{
    this._context = context;
    this._req = req;
    this._resp = resp;
    try
    {
        this._is = req.getInputStream();
        this._os = resp.getOutputStream();
    }
    catch (IOException ex)
    {
        throw new RuntimeException(ex);
    }
}
项目:spring    文件:SimpleHttpServerFactoryBean.java   
@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();
}
项目:switchyard    文件:RESTEasyGatewayTest.java   
@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() {
        @Override
        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);
}
项目:switchyard    文件:SOAPGatewayTest.java   
@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);
}
项目:gvod    文件:JwHttpServer.java   
public static synchronized void startOrUpdate(InetSocketAddress addr, String filename,
            HttpHandler handler)
            throws IOException {
        if (addr == null) {
            throw new IllegalArgumentException("InetSocketAddress was null for HttpServer");
        }
        if (filename == null) {
            throw new IllegalArgumentException("filename was null for HttpServer");
        }
        boolean toStart = false;
        if (instance == null) {
            instance = new JwHttpServer();
            JwHttpServer.addr = addr;

            server = HttpServer.create(addr,
                    /*system default backlog for TCP connections*/ 0);
//            server.setExecutor(Executors.newCachedThreadPool());
            toStart = true;
        }
        HttpContext context = server.createContext(filename, handler);
        context.getFilters().add(new ParameterFilter());
        if (toStart) {
            server.start();
        }
    }
项目:RipplePower    文件:RpcHandler.java   
/**
 * 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);
    }
}
项目:class-guard    文件:SimpleHttpServerFactoryBean.java   
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();
}
项目:trap    文件:ListenerHttpTransport.java   
public void unregister(ServerHttpTransport serverHttpTransport, HttpContext httpContext)
{
    try
    {
        this.server.removeContext(httpContext);
    }
    catch (Exception e)
    {
        try
        {
            this.server.removeContext(serverHttpTransport.getPath());
        }
        catch (Exception e1)
        {

        }
    }
}
项目:spring-cloud-aws    文件:ContextInstanceDataAutoConfigurationTest.java   
@Test
public void placeHolder_noExplicitConfiguration_createInstanceDataResolverForAwsEnvironment() throws Exception {
    // Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));

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

    // Act
    this.context.refresh();

    // Assert
    assertTrue(this.context.containsBean("AmazonEc2InstanceDataPropertySourcePostProcessor"));

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataAutoConfigurationTest.java   
@Test
public 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
    assertFalse(this.context.containsBean("AmazonEc2InstanceDataPropertySourcePostProcessor"));

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataAutoConfigurationTest.java   
@Test
public void placeHolder_noExplicitConfiguration_createInstanceDataResolverThatResolvesWithDefaultAttributes() throws Exception {
    // Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
    HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a:b;c:d"));

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

    // Act
    this.context.refresh();

    // Assert
    assertEquals("b", this.context.getEnvironment().getProperty("a"));
    assertEquals("d", this.context.getEnvironment().getProperty("c"));

    httpServer.removeContext(instanceIdHttpContext);
    httpServer.removeContext(userDataHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataAutoConfigurationTest.java   
@Test
public void placeHolder_customValueSeparator_createInstanceDataResolverThatResolvesWithCustomValueSeparator() throws Exception {
    // Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
    HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a=b;c=d"));

    this.context = new AnnotationConfigApplicationContext();

    TestPropertyValues.of("cloud.aws.instance.data.valueSeparator:=").applyTo(this.context);

    this.context.register(ContextInstanceDataAutoConfiguration.class);

    // Act
    this.context.refresh();

    // Assert
    assertEquals("b", this.context.getEnvironment().getProperty("a"));
    assertEquals("d", this.context.getEnvironment().getProperty("c"));

    httpServer.removeContext(instanceIdHttpContext);
    httpServer.removeContext(userDataHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataAutoConfigurationTest.java   
@Test
public void placeHolder_customAttributeSeparator_createInstanceDataResolverThatResolvesWithCustomAttribute() throws Exception {
    // Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
    HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a:b/c:d"));

    this.context = new AnnotationConfigApplicationContext();

    TestPropertyValues.of("cloud.aws.instance.data.attributeSeparator:/").applyTo(this.context);

    this.context.register(ContextInstanceDataAutoConfiguration.class);

    // Act
    this.context.refresh();

    // Assert
    assertEquals("b", this.context.getEnvironment().getProperty("a"));
    assertEquals("d", this.context.getEnvironment().getProperty("c"));

    httpServer.removeContext(instanceIdHttpContext);
    httpServer.removeContext(userDataHttpContext);
}
项目:spring-cloud-aws    文件:ContextStackAutoConfigurationTest.java   
@Test
public void stackRegistry_autoConfigurationEnabled_returnsAutoConfiguredStackRegistry() throws Exception {
    //Arrange
    this.context = new AnnotationConfigApplicationContext();
    this.context.register(AutoConfigurationStackRegistryTestConfiguration.class);
    this.context.register(ContextStackAutoConfiguration.class);
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext httpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("test"));

    //Act
    this.context.refresh();

    //Assert
    assertNotNull(this.context.getBean(StackResourceRegistry.class));

    httpServer.removeContext(httpContext);
    MetaDataServer.shutdownHttpServer();
}
项目:spring-cloud-aws    文件:ElastiCacheAutoConfigurationTest.java   
@Test
public void cacheManager_configuredMultipleCachesWithStack_configuresCacheManager() throws Exception {
    //Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));

    this.context = new AnnotationConfigApplicationContext();
    this.context.register(MockCacheConfigurationWithStackCaches.class);
    this.context.register(ElastiCacheAutoConfiguration.class);

    //Act
    this.context.refresh();

    //Assert
    CacheManager cacheManager = this.context.getBean(CachingConfigurer.class).cacheManager();
    assertTrue(cacheManager.getCacheNames().contains("sampleCacheOneLogical"));
    assertTrue(cacheManager.getCacheNames().contains("sampleCacheTwoLogical"));
    assertEquals(2, cacheManager.getCacheNames().size());

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ElastiCacheAutoConfigurationTest.java   
@Test
public void cacheManager_configuredNoCachesWithNoStack_configuresNoCacheManager() throws Exception {
    //Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));

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

    //Act
    this.context.refresh();

    //Assert
    CacheManager cacheManager = this.context.getBean(CachingConfigurer.class).cacheManager();
    assertEquals(0, cacheManager.getCacheNames().size());

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ContextStackConfigurationTest.java   
@Test
public 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);
    assertNotNull(stackResourceRegistry);
    assertEquals("testStack", stackResourceRegistry.getStackName());

    httpServer.removeContext(httpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataPropertySourceBeanDefinitionParserTest.java   
@Test
public void parseInternal_singleElementDefined_beanDefinitionCreated() throws Exception {
    //Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);

    //Act
    reader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));

    //Assert
    BeanFactoryPostProcessor postProcessor = beanFactory.getBean("AmazonEc2InstanceDataPropertySourcePostProcessor", BeanFactoryPostProcessor.class);
    assertNotNull(postProcessor);
    assertEquals(1, beanFactory.getBeanDefinitionCount());

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataPropertySourceBeanDefinitionParserTest.java   
@Test
public void parseInternal_missingAwsCloudEnvironment_missingBeanDefinition() throws Exception {
    //Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler(null));
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);

    //Act
    reader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-context.xml", getClass()));

    //Assert
    assertFalse(beanFactory.containsBean("AmazonEc2InstanceDataPropertySourcePostProcessor"));

    httpServer.removeContext(instanceIdHttpContext);
}
项目:spring-cloud-aws    文件:ContextInstanceDataPropertySourceBeanDefinitionParserTest.java   
@Test
public void parseInternal_singleElementWithCustomAttributeAndValueSeparator_postProcessorCreatedWithCustomAttributeAndValueSeparator() throws Exception {
    //Arrange
    HttpServer httpServer = MetaDataServer.setupHttpServer();
    HttpContext instanceIdHttpContext = httpServer.createContext("/latest/meta-data/instance-id", new MetaDataServer.HttpResponseWriterHandler("testInstanceId"));
    HttpContext userDataHttpContext = httpServer.createContext("/latest/user-data", new MetaDataServer.HttpResponseWriterHandler("a=b/c=d"));

    GenericApplicationContext applicationContext = new GenericApplicationContext();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(applicationContext);

    //Act
    reader.loadBeanDefinitions(new ClassPathResource(getClass().getSimpleName() + "-customAttributeAndValueSeparator.xml", getClass()));

    applicationContext.refresh();

    //Assert
    assertEquals("b", applicationContext.getEnvironment().getProperty("a"));
    assertEquals("d", applicationContext.getEnvironment().getProperty("c"));

    httpServer.removeContext(instanceIdHttpContext);
    httpServer.removeContext(userDataHttpContext);
}
项目:OpenbravoPOS    文件:JettyHttpExchange.java   
public JettyHttpExchange(HttpContext context, HttpServletRequest req,
        HttpServletResponse resp)
{
    this._context = context;
    this._req = req;
    this._resp = resp;
    try
    {
        this._is = req.getInputStream();
        this._os = resp.getOutputStream();
    }
    catch (IOException ex)
    {
        throw new RuntimeException(ex);
    }
}
项目:pi    文件:SimpleHttpServerFactoryBean.java   
public void afterPropertiesSet() throws IOException {
    InetSocketAddress address = this.hostname != null ? new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port);
    this.server = getInitializedServer(address);
    if (server == null) {
        LOG.warn("Unable to create server");
        return;
    }

    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 (LOG.isInfoEnabled()) {
        LOG.info("Starting HttpServer at address " + address);
    }
    this.server.start();
}
项目:loadr    文件:HttpService.java   
public static HttpServer startServer(String path, Supplier<String> request, Consumer<String> response) throws IOException {
    HttpServer httpServer = HttpServer.create(new InetSocketAddress(4221), 0);
    HttpContext context = httpServer.createContext(path);
    context.setHandler((he) -> {
        final byte[] bytes = request.get().getBytes();
        he.sendResponseHeaders(200, bytes.length);
        final OutputStream output = he.getResponseBody();
        InputStream input = he.getRequestBody();
        response.accept(read(input));
        output.write(bytes);
        output.flush();
        he.close();
    });
    httpServer.start();
    return httpServer;
}
项目:Equella    文件:Main.java   
private void createContext(HttpServer server, String path, HttpHandler handler, Authenticator auth)
{
    final HttpContext context = server.createContext(path, handler);
    if( auth != null )
    {
        context.setAuthenticator(auth);
    }
    context.getFilters().addAll(filters);
}
项目:lams    文件:SimpleHttpServerJaxWsServiceExporter.java   
/**
 * 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;
}
项目:accs-psm-cli-docker    文件:Bootstrap.java   
public static void main(String[] args) throws IOException {

    String host = System.getenv().getOrDefault("HOSTNAME", "localhost");
    int port = Integer.valueOf(System.getenv().getOrDefault("PORT", "9090"));

    HttpServer server = HttpServer.create(new InetSocketAddress(host,port), 0);

    HttpContext context = server.createContext("/");
    context.setHandler((he) -> {
        he.sendResponseHeaders(200, 0);
        final OutputStream output = he.getResponseBody();
        String address = he.getRemoteAddress().getAddress().getHostAddress();
        output.write(("Hello @ "+ new Date().toString() + " from "+ address).getBytes());
        output.flush();
        he.close();
    });

    server.start();
    System.out.println("server started");

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            server.stop(0);
        }
    });


}
项目:OpenJSharp    文件:HttpEndpoint.java   
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));
}
项目:OpenJSharp    文件:ServerMgr.java   
void removeContext(HttpContext context) {
    InetSocketAddress inetAddress = context.getServer().getAddress();
    synchronized(servers) {
        ServerState state = servers.get(inetAddress);
        int instances = state.noOfContexts();
        if (instances < 2) {
            ((ExecutorService)state.getServer().getExecutor()).shutdown();
            state.getServer().stop(0);
            servers.remove(inetAddress);
        } else {
            state.getServer().removeContext(context);
            state.oneLessContext(context.getPath());
        }
    }
}