Java Code Examples for org.eclipse.jetty.server.Server#start()

The following examples show how to use org.eclipse.jetty.server.Server#start() . 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: Demo_JettyWebSocketServer.java    From haxademic with MIT License 6 votes vote down vote up
protected void firstFrame() {
	server = new Server();
	
	ServerConnector connector = new ServerConnector(server);
	connector.setPort(8787);
	server.addConnector(connector);

	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
	context.setContextPath("/websocket");
	server.setHandler(context);

	try {
		ServerContainer wscontainer = WebSocketServerContainerInitializer.initialize(context);
		wscontainer.addEndpoint(WebsocketEndpoint.class);
		synchronized (server) {
			server.start();
		}
		
	} catch (Throwable t) {
		t.printStackTrace(System.err);
	}
}
 
Example 2
Source File: JavaNetReverseProxy.java    From jenkins-test-harness with MIT License 6 votes vote down vote up
public JavaNetReverseProxy(File cacheFolder) throws Exception {
    this.cacheFolder = cacheFolder;
    cacheFolder.mkdirs();
    QueuedThreadPool qtp = new QueuedThreadPool();
    qtp.setName("Jetty (JavaNetReverseProxy)");
    server = new Server(qtp);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    server.setHandler(contexts);

    ServletContextHandler root = new ServletContextHandler(contexts, "/", ServletContextHandler.SESSIONS);
    root.addServlet(new ServletHolder(this), "/");

    ServerConnector connector = new ServerConnector(server);
    server.addConnector(connector);
    server.start();

    localPort = connector.getLocalPort();
}
 
Example 3
Source File: WaltzStorage.java    From waltz with Apache License 2.0 6 votes vote down vote up
public void setJettyServer() throws Exception {
    Optional<Object> jettyPortOpt = config.getOpt(WaltzStorageConfig.STORAGE_JETTY_PORT);
    if (jettyPortOpt.isPresent()) {
        logger.info("JettyPort is : " + (int) jettyPortOpt.get());

        InetSocketAddress addr = new InetSocketAddress(InetAddress.getLocalHost(), (int) jettyPortOpt.get());
        jettyServer = new Server(addr);

        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        jettyServer.setHandler(context);

        context.addServlet(new ServletHolder(new PingServlet()), "/ping");
        context.addServlet(new ServletHolder(new BuildInfoServlet(Utils.getBuildInfoMap(this.getClass()))), "/buildinfo");
        context.addServlet(new ServletHolder(new MetricsServlet(MetricRegistry.getInstance())), "/metrics");

        HealthCheckRegistry healthCheckRegistry = registerHealthCheck(this);
        context.addServlet(new ServletHolder(new HealthCheckServlet(healthCheckRegistry)), "/health");

        jettyServer.start();
    } else {
        logger.warn("Jetty Server failed to start: " + WaltzStorageConfig.STORAGE_JETTY_PORT + " missing");
    }
}
 
Example 4
Source File: Application.java    From vk-java-sdk with MIT License 6 votes vote down vote up
private static void initServer(Properties properties) throws Exception {
    Integer port = Integer.valueOf(properties.getProperty("server.port"));
    String host = properties.getProperty("server.host");

    Integer clientId = Integer.valueOf(properties.getProperty("client.id"));
    String clientSecret = properties.getProperty("client.secret");

    HandlerCollection handlers = new HandlerCollection();

    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[]{"index.html"});
    resourceHandler.setResourceBase(Application.class.getResource("/static").getPath());

    VkApiClient vk = new VkApiClient(new HttpTransportClient());
    handlers.setHandlers(new Handler[]{resourceHandler, new RequestHandler(vk, clientId, clientSecret, host)});

    Server server = new Server(port);
    server.setHandler(handlers);

    server.start();
    server.join();
}
 
Example 5
Source File: Main.java    From idworker with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = new Server();

    SelectChannelConnector connector = new SelectChannelConnector();
    int port = Integer.parseInt(System.getProperty("port", "18001"));
    connector.setPort(port);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new IdWorkerServlet()), "/*");
    server.setHandler(context);

    server.start();
    server.join();

}
 
Example 6
Source File: BaseIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
/**
 * init and start a jetty server, remember to call server.stop when the task is finished
 */
protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception {
  server = new Server(PORT);

  ContextHandlerCollection contexts = new ContextHandlerCollection();
  contexts.setHandlers(handlers);

  server.setHandler(contexts);
  server.start();

  return server;
}
 
Example 7
Source File: OpenIdServer.java    From OpenID-Attacker with GNU General Public License v2.0 5 votes vote down vote up
public void start() throws OpenIdAttackerServerException {
       final int port = config.getServerListenPort();
final String host = config.getServerListenHost();
       newServer = new Server(new InetSocketAddress(host, port));
       newServer.setHandler(handler);
       try {
           newServer.start();
           Status oldStatus = status;
           status = Status.RUNNING;
           setServerStatusline(String.format("%s... Host: %s Port: %d", status, host, port));
           firePropertyChange(PROP_STATUS, oldStatus, status);
       } catch (Exception ex) {
           throw new OpenIdAttackerServerException("Could not start the server", ex);
       }
   }
 
Example 8
Source File: Main.java    From stepic_java_webserver with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    AllRequestsServlet allRequestsServlet = new AllRequestsServlet();

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(allRequestsServlet), "/*");

    Server server = new Server(8080);
    server.setHandler(context);

    server.start();
    server.join();
}
 
Example 9
Source File: JettyServer.java    From jsonrpc4j with MIT License 5 votes vote down vote up
public void startup() throws Exception {
	port = 10000 + new Random().nextInt(30000);
	jetty = new Server(port);
	ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
	context.setContextPath("/");
	jetty.setHandler(context);
	ServletHolder servlet = context.addServlet(JsonRpcTestServlet.class, "/" + SERVLET);
	servlet.setInitParameter("class", service.getCanonicalName());
	jetty.start();
}
 
Example 10
Source File: WebSocketServerInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  server = new Server(port);
  DefaultWebSocketServlet servlet = new DefaultWebSocketServlet();
  ServletHolder sh = new ServletHolder(servlet);
  ServletContextHandler contextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
  contextHandler.addServlet(sh, extension);

  try {
    server.start();
  } catch (Exception ex) {
    DTThrowable.rethrow(ex);
  }
}
 
Example 11
Source File: RedeployLeakIT.java    From flow with Apache License 2.0 5 votes vote down vote up
public void setup(int port) throws Exception {
    System.setProperty("java.awt.headless", "true");
    System.setProperty("org.eclipse.jetty.util.log.class",
            JavaUtilLog.class.getName());

    server = new Server();

    try (ServerConnector connector = new ServerConnector(server)) {
        connector.setPort(port);
        server.setConnectors(new ServerConnector[] { connector });
    }

    File[] warDirs = new File("target").listFiles(file -> file.getName()
            .matches("flow-test-memory-leaks-.*-SNAPSHOT"));
    String wardir = "target/" + warDirs[0].getName();

    context = new WebAppContext();
    context.setResourceBase(wardir);
    context.setContextPath("/");
    context.setConfigurations(
            new Configuration[] { new AnnotationConfiguration(),
                    new WebXmlConfiguration(), new WebInfConfiguration(),
                    // new TagLibConfiguration(),
                    new PlusConfiguration(), new MetaInfConfiguration(),
                    new FragmentConfiguration(), new EnvConfiguration() });
    server.setHandler(context);
    server.start();

    testReference = new WeakReference<>(
            Class.forName(testClass, true, context.getClassLoader()));
    Assert.assertNotNull(testReference.get());

}
 
Example 12
Source File: EtcdTimeoutTest.java    From etcd4j with MIT License 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws Exception {
    server = new Server(PORT);
    ServletContextHandler handler = new ServletContextHandler();
    handler.setContextPath("/");
    handler.addFilter(DelayFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD));
    handler.addServlet(TestServlet.class, "/*");
    server.setHandler(handler);
    server.start();
}
 
Example 13
Source File: ContainerStarter.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Method for starting the Jetty server with the ATS Agent webapp.
 * @return the started server.
 * @throws IOException
 */
private static Server startServer() throws IOException {

    addAppender();

    final int agentPort = getAgentDefaultPort();
    log.info("Starting ATS agent at port: " + agentPort);

    final String jettyHome = getJettyHome();

    logSystemInformation(jettyHome);

    // start the server
    Connector connector = new SelectChannelConnector();
    connector.setPort(agentPort);

    Server server = new Server();
    server.setConnectors(new Connector[]{ connector });

    WebAppContext webApp = new WebAppContext();
    webApp.setContextPath("/agentapp");
    webApp.setWar(jettyHome + "/webapp/agentapp.war");
    webApp.setAttribute("org.eclipse.jetty.webapp.basetempdir",
                        getJettyWorkDir(jettyHome));

    server.setHandler(webApp);
    server.setStopAtShutdown(true);

    setExtraClasspath(webApp, jettyHome);

    try {
        server.start();
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }

    log.info("ATS agent started");
    return server;
}
 
Example 14
Source File: BaseSecurityTest.java    From atlas with Apache License 2.0 5 votes vote down vote up
protected void startEmbeddedServer(Server server) throws Exception {
    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setWar(getWarPath());
    server.setHandler(webapp);

    server.start();
}
 
Example 15
Source File: Main.java    From backstopper with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server server = createServer(Integer.parseInt(System.getProperty(PORT_SYSTEM_PROP_KEY, "8080")));

    try {
        server.start();
        server.join();
    }
    finally {
        server.destroy();
    }
}
 
Example 16
Source File: TestHttpClient.java    From nifi with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    // Create embedded Jetty server
    // Use less threads to mitigate Gateway Timeout (504) with proxy test
    // Minimum thread pool size = (acceptors=2 + selectors=8 + request=1), defaults to max=200
    final QueuedThreadPool threadPool = new QueuedThreadPool(50);
    server = new Server(threadPool);

    final ContextHandlerCollection handlerCollection = new ContextHandlerCollection();

    final ServletContextHandler contextHandler = new ServletContextHandler();
    contextHandler.setContextPath("/nifi-api");

    final ServletContextHandler wrongPathContextHandler = new ServletContextHandler();
    wrongPathContextHandler.setContextPath("/wrong/nifi-api");

    handlerCollection.setHandlers(new Handler[]{contextHandler, wrongPathContextHandler});

    server.setHandler(handlerCollection);

    final ServletHandler servletHandler = new ServletHandler();
    contextHandler.insertHandler(servletHandler);

    final ServletHandler wrongPathServletHandler = new ServletHandler();
    wrongPathContextHandler.insertHandler(wrongPathServletHandler);

    final SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath("src/test/resources/certs/keystore.jks");
    sslContextFactory.setKeyStorePassword("passwordpassword");
    sslContextFactory.setKeyStoreType("JKS");
    sslContextFactory.setProtocol(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    sslContextFactory.setExcludeProtocols("TLS", "TLSv1", "TLSv1.1");

    httpConnector = new ServerConnector(server);

    final HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());
    sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https));
    logger.info("SSL Connector: " + sslConnector.dump());

    server.setConnectors(new Connector[] { httpConnector, sslConnector });

    wrongPathServletHandler.addServletWithMapping(WrongSiteInfoServlet.class, "/site-to-site");

    servletHandler.addServletWithMapping(SiteInfoServlet.class, "/site-to-site");
    servletHandler.addServletWithMapping(PeersServlet.class, "/site-to-site/peers");

    servletHandler.addServletWithMapping(PortTransactionsAccessDeniedServlet.class, "/data-transfer/input-ports/input-access-denied-id/transactions");
    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-running-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/input-ports/input-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/input-ports/input-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(InputPortTransactionServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/input-ports/input-timeout-data-ex-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-running-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesServlet.class, "/data-transfer/output-ports/output-running-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutServlet.class, "/data-transfer/output-ports/output-timeout-id/transactions/transaction-id/flow-files");

    servletHandler.addServletWithMapping(PortTransactionsServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions");
    servletHandler.addServletWithMapping(OutputPortTransactionServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id");
    servletHandler.addServletWithMapping(FlowFilesTimeoutAfterDataExchangeServlet.class, "/data-transfer/output-ports/output-timeout-data-ex-id/transactions/transaction-id/flow-files");

    server.start();

    logger.info("Starting server on port {} for HTTP, and {} for HTTPS", httpConnector.getLocalPort(), sslConnector.getLocalPort());

    startProxyServer();
    startProxyServerWithAuth();
}
 
Example 17
Source File: ApplicationTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
/**
 * Test of getApplication method, of class Application.
 */
@Test
public void testGetApplication() throws Exception
{
  Configuration conf = new Configuration(false);
  conf.addResource("dt-site-mobile.xml");
  Server server = new Server(0);
  Servlet servlet = new SamplePubSubWebSocketServlet();
  ServletHolder sh = new ServletHolder(servlet);
  ServletContextHandler contextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
  contextHandler.addServlet(sh, "/pubsub");
  contextHandler.addServlet(sh, "/*");
  server.start();
  Connector[] connector = server.getConnectors();
  conf.set("dt.attr.GATEWAY_CONNECT_ADDRESS", "localhost:" + connector[0].getLocalPort());
  URI uri = PubSubHelper.getURI("localhost:" + connector[0].getLocalPort());

  PubSubWebSocketOutputOperator<Object> outputOperator = new PubSubWebSocketOutputOperator<Object>();
  outputOperator.setUri(uri);
  outputOperator.setTopic(conf.get("dt.application.MobileExample.operator.QueryLocation.topic"));

  PubSubWebSocketInputOperator<Map<String, String>> inputOperator = new PubSubWebSocketInputOperator<Map<String, String>>();
  inputOperator.setUri(uri);
  inputOperator.setTopic(conf.get("dt.application.MobileExample.operator.LocationResults.topic"));

  CollectorTestSink<Object> sink = new CollectorTestSink<Object>();
  inputOperator.outputPort.setSink(sink);

  Map<String, String> data = new HashMap<String, String>();
  data.put("command", "add");
  data.put("phone", "5559990");

  Application app = new Application();
  LocalMode lma = LocalMode.newInstance();
  lma.prepareDAG(app, conf);
  LocalMode.Controller lc = lma.getController();
  lc.setHeartbeatMonitoringEnabled(false);
  lc.runAsync();
  Thread.sleep(5000);
  inputOperator.setup(null);
  outputOperator.setup(null);
  inputOperator.activate(null);
  outputOperator.beginWindow(0);
  outputOperator.input.process(data);
  outputOperator.endWindow();
  inputOperator.beginWindow(0);
  int timeoutMillis = 5000;
  while (sink.collectedTuples.size() < 5 && timeoutMillis > 0) {
    inputOperator.emitTuples();
    timeoutMillis -= 20;
    Thread.sleep(20);
  }
  inputOperator.endWindow();
  lc.shutdown();
  inputOperator.teardown();
  outputOperator.teardown();
  server.stop();
  Assert.assertTrue("size of output is 5 ", sink.collectedTuples.size() == 5);
  for (Object obj : sink.collectedTuples) {
    Assert.assertEquals("Expected phone number", "5559990", ((Map<String, String>)obj).get("phone"));
  }
}
 
Example 18
Source File: JettyLauncher.java    From JobX with Apache License 2.0 4 votes vote down vote up
@Override
public void start(boolean devMode, int port) throws Exception {

    Server server = new Server(new QueuedThreadPool(Constants.WEB_THREADPOOL_SIZE));

    WebAppContext appContext = new WebAppContext();
    String resourceBasePath = "";
    //开发者模式
    if (devMode) {
        String artifact = MavenUtils.get(Thread.currentThread().getContextClassLoader()).getArtifactId();
        resourceBasePath = artifact + "/src/main/webapp";
    }
    appContext.setDescriptor(resourceBasePath + "WEB-INF/web.xml");
    appContext.setResourceBase(resourceBasePath);
    appContext.setExtractWAR(true);

    //init param
    appContext.setInitParameter("org.eclipse.jetty.servlet.Default.dirAllowed", "false");
    if (CommonUtils.isWindows()) {
        appContext.setInitParameter("org.eclipse.jetty.servlet.Default.useFileMappedBuffer", "false");
    }

    //for jsp support
    appContext.addBean(new JettyJspParser(appContext));
    appContext.addServlet(JettyJspServlet.class, "*.jsp");

    appContext.setContextPath("/");
    appContext.getServletContext().setExtendedListenerTypes(true);
    appContext.setParentLoaderPriority(true);
    appContext.setThrowUnavailableOnStartupException(true);
    appContext.setConfigurationDiscovered(true);
    appContext.setClassLoader(Thread.currentThread().getContextClassLoader());


    ServerConnector connector = new ServerConnector(server);
    connector.setHost("localhost");
    connector.setPort(port);

    server.setConnectors(new Connector[]{connector});
    server.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", 1024 * 1024 * 1024);
    server.setDumpAfterStart(false);
    server.setDumpBeforeStop(false);
    server.setStopAtShutdown(true);
    server.setHandler(appContext);
    logger.info("[JobX] JettyLauncher starting...");
    server.start();
}
 
Example 19
Source File: Runtime.java    From incubator-heron with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"IllegalCatch", "RegexpSinglelineJava"})
public static void main(String[] args) throws Exception {
  final Options options = createOptions();
  final Options helpOptions = constructHelpOptions();

  CommandLineParser parser = new DefaultParser();

  // parse the help options first.
  CommandLine cmd = parser.parse(helpOptions, args, true);
  if (cmd.hasOption(Flag.Help.name)) {
    usage(options);
    return;
  }

  try {
    cmd = parser.parse(options, args);
  } catch (ParseException pe) {
    System.err.println(pe.getMessage());
    usage(options);
    return;
  }

  final boolean verbose = isVerbose(cmd);
  // set and configure logging level
  Logging.setVerbose(verbose);
  Logging.configure(verbose);

  LOG.debug("API server overrides:\n {}", cmd.getOptionProperties(Flag.Property.name));

  final String toolsHome = getToolsHome();

  // read command line flags
  final String cluster = cmd.getOptionValue(Flag.Cluster.name);
  final String heronConfigurationDirectory = getConfigurationDirectory(toolsHome, cmd);
  final String heronDirectory = getHeronDirectory(cmd);
  final String releaseFile = getReleaseFile(toolsHome, cmd);
  final String configurationOverrides = loadOverrides(cmd);
  final int port = getPort(cmd);
  final String downloadHostName = getDownloadHostName(cmd);
  final String heronCorePackagePath = getHeronCorePackagePath(cmd);

  final Config baseConfiguration =
      ConfigUtils.getBaseConfiguration(heronDirectory,
          heronConfigurationDirectory,
          releaseFile,
          configurationOverrides);

  final ResourceConfig config = new ResourceConfig(Resources.get());
  final Server server = new Server(port);

  final ServletContextHandler contextHandler =
      new ServletContextHandler(ServletContextHandler.NO_SESSIONS);
  contextHandler.setContextPath("/");

  LOG.info("using configuration path: {}", heronConfigurationDirectory);

  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CLUSTER, cluster);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION, baseConfiguration);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_DIRECTORY,
      heronConfigurationDirectory);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_CONFIGURATION_OVERRIDE_PATH,
      configurationOverrides);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_PORT,
      String.valueOf(port));
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_DOWNLOAD_HOSTNAME,
      Utils.isNotEmpty(downloadHostName)
          ? String.valueOf(downloadHostName) : null);
  contextHandler.setAttribute(HeronResource.ATTRIBUTE_HERON_CORE_PACKAGE_PATH,
      Utils.isNotEmpty(heronCorePackagePath)
          ? String.valueOf(heronCorePackagePath) : null);

  server.setHandler(contextHandler);

  final ServletHolder apiServlet =
      new ServletHolder(new ServletContainer(config));

  contextHandler.addServlet(apiServlet, API_BASE_PATH);

  try {
    server.start();

    LOG.info("Heron API server started at {}", server.getURI());

    server.join();
  } catch (Exception ex) {
    final String message = getErrorMessage(server, port, ex);
    LOG.error(message);
    System.err.println(message);
    System.exit(1);
  } finally {
    server.destroy();
  }
}
 
Example 20
Source File: OWLServerMetadataTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
	public void testServerCommunication() throws Exception {
		g = loadOntology("../OWLTools-Sim/src/test/resources/sim/mp-subset-1.obo");
		
		// set sim
		OwlSimFactory owlSimFactory = new SimpleOwlSimFactory();
		OwlSim sos = owlSimFactory.createOwlSim(g.getSourceOntology());
//		SimPreProcessor pproc = new NullSimPreProcessor();
//		pproc.setInputOntology(g.getSourceOntology());
//		pproc.setOutputOntology(g.getSourceOntology());
//		if (sos instanceof SimpleOwlSim)
//			((SimpleOwlSim) sos).setSimPreProcessor(pproc);
		sos.createElementAttributeMapFromOntology();
		// TODO	attributeAllByAllOld(opts);
		
		// create server
		Server server = new Server(9031);
		server.setHandler(new OWLServer(g, sos));
		try {
			server.start();

			// create a client
			HttpClient httpclient = new DefaultHttpClient();

			// prepare a request
			//final HttpUriRequest httpUriRequest = createRequest(200);
			HttpUriRequest httppost = createRequest();

			// run request
			Log.getLog().info("Executing="+httppost);
			//HttpResponse response = httpclient.execute(httpUriRequest);
			HttpResponse response = httpclient.execute(httppost);
			Log.getLog().info("Executed="+httpclient);
			
			// check response
			HttpEntity entity = response.getEntity();
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() == 200) {
				String responseContent = EntityUtils.toString(entity);
				handleResponse(responseContent);
			}
			else {
				Log.getLog().info("Status="+statusLine.getStatusCode());
				EntityUtils.consumeQuietly(entity);
			}

		}
		finally {
			// clean up
			server.stop();

//			if (pproc != null) {
//				pproc.dispose();
//			}
		}
	}