Tabnine Logo
HttpServer
Code IndexAdd Tabnine to your IDE (free)

How to use
HttpServer
in
com.sun.net.httpserver

Best Java code snippets using com.sun.net.httpserver.HttpServer (Showing top 20 results out of 1,179)

Refine searchRefine arrow

  • InetSocketAddress
  • Executors
origin: Netflix/eureka

public SimpleEurekaHttpServer(EurekaHttpClient requestHandler, EurekaTransportEventListener eventListener) throws IOException {
  this.requestHandler = requestHandler;
  this.eventListener = eventListener;
  this.httpServer = HttpServer.create(new InetSocketAddress(0), 1);
  httpServer.createContext("/v2", createEurekaV2Handle());
  httpServer.setExecutor(null);
  httpServer.start();
}
origin: spring-projects/spring-framework

@Override
public void destroy() {
  logger.info("Stopping HttpServer");
  this.server.stop(this.shutdownDelay);
}
origin: Netflix/eureka

public int getServerPort() {
  return httpServer.getAddress().getPort();
}
origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() throws Exception {
  if (this.server == null) {
    InetSocketAddress address = (this.hostname != null ?
        new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
    HttpServer server = HttpServer.create(address, this.backlog);
    if (logger.isInfoEnabled()) {
      logger.info("Starting HttpServer at address " + address);
    }
    server.start();
    this.server = server;
    this.localServer = true;
  }
  super.afterPropertiesSet();
}
origin: jersey/jersey

@Override
public void start() {
  if (started.compareAndSet(false, true)) {
    LOGGER.log(Level.FINE, "Starting JdkHttpServerTestContainer...");
    server.start();
    if (baseUri.getPort() == 0) {
      baseUri = UriBuilder.fromUri(baseUri)
          .port(server.getAddress().getPort())
          .build();
      LOGGER.log(Level.INFO, "Started JdkHttpServerTestContainer at the base URI " + baseUri);
    }
  } else {
    LOGGER.log(Level.WARNING, "Ignoring start request - JdkHttpServerTestContainer is already started.");
  }
}
origin: rhuss/jolokia

/**
 * Create the HttpServer to use. Can be overridden if a custom or already existing HttpServer should be
 * used
 *
 * @return HttpServer to use
 * @throws IOException if something fails during the initialisation
 */
private HttpServer createHttpServer(JolokiaServerConfig pConfig) throws IOException {
  int port = pConfig.getPort();
  InetAddress address = pConfig.getAddress();
  InetSocketAddress socketAddress = new InetSocketAddress(address,port);
  HttpServer server = pConfig.useHttps() ?
          createHttpsServer(socketAddress, pConfig) :
          HttpServer.create(socketAddress, pConfig.getBacklog());
  // Thread factory which creates only daemon threads
  ThreadFactory daemonThreadFactory = new DaemonThreadFactory(pConfig.getThreadNamePrefix());
  // Prepare executor pool
  Executor executor;
  String mode = pConfig.getExecutor();
  if ("fixed".equalsIgnoreCase(mode)) {
    executor = Executors.newFixedThreadPool(pConfig.getThreadNr(), daemonThreadFactory);
  } else if ("cached".equalsIgnoreCase(mode)) {
    executor = Executors.newCachedThreadPool(daemonThreadFactory);
  } else {
    executor = Executors.newSingleThreadExecutor(daemonThreadFactory);
  }
  server.setExecutor(executor);
  return server;
}
origin: apache/incubator-pinot

private HttpServer startServer(int port, HttpHandler handler)
  throws IOException {
 final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
 server.createContext(URI_PATH, handler);
 new Thread(new Runnable() {
  @Override
  public void run() {
   server.start();
  }
 }).start();
 return server;
}
origin: prometheus/client_java

/**
 * Start a HTTP server serving Prometheus metrics from the given registry.
 */
public HTTPServer(InetSocketAddress addr, CollectorRegistry registry, boolean daemon) throws IOException {
  server = HttpServer.create();
  server.bind(addr, 3);
  HttpHandler mHandler = new HTTPMetricHandler(registry);
  server.createContext("/", mHandler);
  server.createContext("/metrics", mHandler);
  executorService = Executors.newFixedThreadPool(5, NamedDaemonThreadFactory.defaultThreadFactory(daemon));
  server.setExecutor(executorService);
  start(daemon);
}
origin: apache/ignite

/**
 * Returns base server url in the form <i>protocol://serverHostName:serverPort</i>.
 *
 * @return Base server url.
 */
public String getBaseUrl() {
  return proto + "://" + httpSrv.getAddress().getHostName() + ":" + httpSrv.getAddress().getPort();
}
origin: rhuss/jolokia

private String detectAgentUrl(HttpServer pServer, JolokiaServerConfig pConfig, String pContextPath) {
  serverAddress= pServer.getAddress();
  InetAddress realAddress;
  int port;
  if (serverAddress != null) {
    realAddress = serverAddress.getAddress();
    if (realAddress.isAnyLocalAddress()) {
      try {
        realAddress = NetworkUtil.getLocalAddress();
      } catch (IOException e) {
        try {
          realAddress = InetAddress.getLocalHost();
        } catch (UnknownHostException e1) {
          // Ok, ok. We take the original one
          realAddress = serverAddress.getAddress();
        }
      }
    }
    port = serverAddress.getPort();
  } else {
    realAddress = pConfig.getAddress();
    port = pConfig.getPort();
  }
  return String.format("%s://%s:%d%s",
             pConfig.getProtocol(),realAddress.getHostAddress(),port, pContextPath);
}
origin: mpusher/alloc

@Override
public void init() {
  int port = CC.mp.net.cfg.getInt("alloc-server-port");
  boolean https = "https".equals(CC.mp.net.cfg.getString("alloc-server-protocol"));
  this.httpServer = HttpServerCreator.createServer(port, https);
  this.allocHandler = new AllocHandler();
  this.pushHandler = new PushHandler();
  httpServer.setExecutor(Executors.newCachedThreadPool());//设置线程池,由于是纯内存操作,不需要队列
  httpServer.createContext("/", allocHandler);//查询mpush机器
  httpServer.createContext("/push", pushHandler);//模拟发送push
  httpServer.createContext("/index.html", new IndexPageHandler());//查询mpush机器
}
origin: com.github.martinpaljak/apdu4j

public void start(InetSocketAddress address) throws IOException {
  server = HttpServer.create(address, Integer.parseInt(System.getProperty(BACKLOG, "10")));
  // threadpool!
  server.setExecutor(Executors.newWorkStealingPool(Integer.parseInt(System.getProperty(HTTPPOOL, "10"))));
  // Only two handlers.
  server.createContext("/", new MsgHandler());
  server.createContext("/status", new StatusHandler());
  logger.info("Server started on {} ", server.getAddress());
  // Starts in separate thread.
  server.start();
}
origin: apache/cloudstack

private static void startupHttpMain() {
  try {
    ConsoleProxyServerFactory factory = getHttpServerFactory();
    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);
  }
}
origin: googleapis/google-cloud-java

/** Starts the thread that runs the Resource Manager server. */
public void start() {
 server.start();
}
origin: jersey/jersey

@Override
public HttpContext createContext(final String s) {
  return delegate.createContext(s);
}
origin: jersey/jersey

@Override
public void setExecutor(final Executor executor) {
  delegate.setExecutor(executor);
}
origin: jersey/jersey

  @Override
  public InetSocketAddress getAddress() {
    return delegate.getAddress();
  }
};
origin: org.springframework/spring-web

@Override
public void afterPropertiesSet() throws Exception {
  if (this.server == null) {
    InetSocketAddress address = (this.hostname != null ?
        new InetSocketAddress(this.hostname, this.port) : new InetSocketAddress(this.port));
    HttpServer server = HttpServer.create(address, this.backlog);
    if (logger.isInfoEnabled()) {
      logger.info("Starting HttpServer at address " + address);
    }
    server.start();
    this.server = server;
    this.localServer = true;
  }
  super.afterPropertiesSet();
}
origin: apache/incubator-pinot

private HttpServer startServer(int port, HttpHandler handler)
  throws IOException {
 final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
 server.createContext(URI_PATH, handler);
 new Thread(new Runnable() {
  @Override
  public void run() {
   server.start();
  }
 }).start();
 servers.add(server);
 return server;
}
origin: io.prometheus/simpleclient_httpserver

/**
 * Start a HTTP server serving Prometheus metrics from the given registry.
 */
public HTTPServer(InetSocketAddress addr, CollectorRegistry registry, boolean daemon) throws IOException {
  server = HttpServer.create();
  server.bind(addr, 3);
  HttpHandler mHandler = new HTTPMetricHandler(registry);
  server.createContext("/", mHandler);
  server.createContext("/metrics", mHandler);
  executorService = Executors.newFixedThreadPool(5, DaemonThreadFactory.defaultThreadFactory(daemon));
  server.setExecutor(executorService);
  start(daemon);
}
com.sun.net.httpserverHttpServer

Javadoc

This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.

One or more HttpHandler objects must be associated with a server in order to process requests. Each such HttpHandler is registered with a root URI path which represents the location of the application or service on this server. The mapping of a handler to a HttpServer is encapsulated by a HttpContext object. HttpContexts are created by calling #createContext(String,HttpHandler). Any request for which no handler can be found is rejected with a 404 response. Management of threads can be done external to this object by providing a java.util.concurrent.Executor object. If none is provided a default implementation is used.

Mapping request URIs to HttpContext paths

When a HTTP request is received, the appropriate HttpContext (and handler) is located by finding the context whose path is the longest matching prefix of the request URI's path. Paths are matched literally, which means that the strings are compared case sensitively, and with no conversion to or from any encoded forms. For example. Given a HttpServer with the following HttpContexts configured.

ContextContext path
ctx1"/"
ctx2"/apps/"
ctx3"/apps/foo/"

the following table shows some request URIs and which, if any context they would match with.

Request URIMatches context
"http://foo.com/apps/foo/bar"ctx3
"http://foo.com/apps/Foo/bar"no match, wrong case
"http://foo.com/apps/app1"ctx2
"http://foo.com/foo"ctx1

Note about socket backlogs

When binding to an address and port number, the application can also specify an integer backlog parameter. This represents the maximum number of incoming TCP connections which the system will queue internally. Connections are queued while they are waiting to be accepted by the HttpServer. When the limit is reached, further connections may be rejected (or possibly ignored) by the underlying TCP implementation. Setting the right backlog value is a compromise between efficient resource usage in the TCP layer (not setting it too high) and allowing adequate throughput of incoming requests (not setting it too low).

Most used methods

  • createContext
    Creates a HttpContext. A HttpContext represents a mapping from a URI path to a exchange handler on t
  • start
    Starts this server in a new background thread. The background thread inherits the priority, thread g
  • create
    Create a HttpServer instance which will bind to the specified java.net.InetSocketAddress (IP address
  • stop
    stops this server by closing the listening socket and disallowing any new exchanges from being proce
  • setExecutor
    sets this server's java.util.concurrent.Executor object. An Executor must be established before #sta
  • getAddress
    returns the address this server is listening on
  • removeContext
    Removes the context identified by the given path from the server. Removing a context does not affect
  • bind
    Binds a currently unbound HttpServer to the given address and port number. A maximum backlog can als
  • getExecutor
    returns this server's Executor object if one was specified with #setExecutor(Executor), or null if n

Popular in Java

  • Creating JSON documents from java classes using gson
  • getOriginalFilename (MultipartFile)
    Return the original filename in the client's filesystem.This may contain path information depending
  • getExternalFilesDir (Context)
  • addToBackStack (FragmentTransaction)
  • Window (java.awt)
    A Window object is a top-level window with no borders and no menubar. The default layout for a windo
  • ServerSocket (java.net)
    This class represents a server-side socket that waits for incoming client connections. A ServerSocke
  • SocketTimeoutException (java.net)
    This exception is thrown when a timeout expired on a socket read or accept operation.
  • Dictionary (java.util)
    Note: Do not use this class since it is obsolete. Please use the Map interface for new implementatio
  • JComboBox (javax.swing)
  • Logger (org.slf4j)
    The org.slf4j.Logger interface is the main user entry point of SLF4J API. It is expected that loggin
  • Top Sublime Text plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now