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

The following examples show how to use org.eclipse.jetty.server.Server#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: JettyService.java    From armeria with Apache License 2.0 6 votes vote down vote up
void stop() {
    final Server server = this.server;
    this.server = null;
    connector = null;

    if (server == null || !startedServer) {
        return;
    }

    try {
        logger.info("Stopping an embedded Jetty: {}", server);
        server.stop();
    } catch (Exception e) {
        logger.warn("Failed to stop an embedded Jetty: {}", server, e);
    }

    postStopTask.accept(server);
}
 
Example 2
Source File: ResolverTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void startServer() throws Throwable {
    Server server = new org.eclipse.jetty.server.Server(Integer.parseInt(PORT));

    WebAppContext webappcontext = new WebAppContext();
    webappcontext.setContextPath("/resolver");
    webappcontext.setBaseResource(Resource.newClassPathResource("/resolver"));

    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] {webappcontext, new DefaultHandler()});
    server.setHandler(handlers);
    server.start();
    Throwable e = webappcontext.getUnavailableException();
    if (e != null) {
        throw e;
    }
    server.stop();
}
 
Example 3
Source File: IdleTimeoutConfigTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void testIdleTimeoutConfigIsApplied() throws Exception {

  // given
  long expectedIdleTimeout = 1000;

  // when
  Map<String, Object> props = new HashMap<>();
  props.put(RestConfig.IDLE_TIMEOUT_MS_CONFIG, String.valueOf(expectedIdleTimeout));
  RestConfig config = new RestConfig(RestConfig.baseConfigDef(), props);

  Server server = new TestApp(config).createServer();
  server.start();
  // then
  Assert.assertEquals(expectedIdleTimeout, server.getConnectors()[0].getIdleTimeout());
  server.stop();
}
 
Example 4
Source File: JettyHandlerIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    Server server = new Server(0);
    server.setHandler(new HelloHandler());
    server.start();
    int port = server.getConnectors()[0].getLocalPort();
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + "/hello")
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
    server.stop();
}
 
Example 5
Source File: SpringWebMvcAgentRuleITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
  assertNull("If this is 'false', it means SpecialAgent set this to 'false', because no deferrers were found", System.getProperty("sa.init.defer"));
  final Server server = startServer();
  final int port = ((ServerConnector)server.getConnectors()[0]).getLocalPort();
  final String url = "http://localhost:" + port;
  final ResponseEntity<String> responseEntity = new RestTemplate().getForEntity(url, String.class);
  assertEquals("test", responseEntity.getBody());
  assertNull(System.getProperty("sa.init.defer"));
  server.stop();
  server.join();
}
 
Example 6
Source File: WebServerDemo.java    From phoebus with Eclipse Public License 1.0 5 votes vote down vote up
public static void main(String[] args) throws Exception
{
    final Server server = new Server(8080);
    server.setHandler(new WebServerDemo());
    server.start();

    System.out.println("Running web server, check http://localhost:8080");
    do
        System.out.println("Main thread could do other things while web server is running...");
    while (! done.await(5, TimeUnit.SECONDS));
    server.stop();
    server.join();
    System.out.println("Done.");
}
 
Example 7
Source File: TestStatsCollectorTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttp() throws Exception {
  Server server = new Server(0);
  ServletContextHandler context = new ServletContextHandler();
  Servlet servlet = new UsageServlet();
  context.addServlet(new ServletHolder(servlet), AbstractStatsCollectorTask.USAGE_PATH_DEFAULT);
  context.setContextPath("/");
  server.setHandler(context);
  try {
    server.start();

    BuildInfo buildInfo = Mockito.mock(BuildInfo.class);
    Mockito.when(buildInfo.getVersion()).thenReturn("v1");

    RuntimeInfo runtimeInfo = mockRuntimeInfo(UUID.randomUUID().toString(), null);

    Configuration config = new Configuration();

    AbstractStatsCollectorTask collector = mockStatsCollectorTask(buildInfo, runtimeInfo, config, null, true);

    List<StatsBean> list = Arrays.asList(new StatsBean());

    Assert.assertTrue(collector.reportStats(list));

  } finally {
    server.stop();
  }
}
 
Example 8
Source File: WebServletShiroTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws Exception
{
    int port = FreePortFinder.findFreePortOnLoopback();
    Server server = new Server( port );
    try {

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath( "/" );

        context.setInitParameter( "shiroConfigLocations", "classpath:web-shiro.ini" );
        context.addEventListener( new EnvironmentLoaderListener() );

        context.addFilter( ShiroFilter.class, "/*", EnumSet.of( REQUEST, FORWARD, INCLUDE, ERROR ) );

        server.setHandler( context );
        server.start();

        // HttpClient client = new DefaultHttpClient();
        // String result = client.execute( new HttpGet( "http://127.0.0.1:" + port + "/" ), new BasicResponseHandler() );

    } finally {
        server.stop();
    }

}
 
Example 9
Source File: ServletTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
        throws Exception
{
    int port = FreePortFinder.findFreePortOnLoopback();
    Server server = new Server( port );
    try {

        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath( "/" );
        context.addEventListener( new FooServletContextListener() );
        context.addServlet( FooServlet.class, "/*" );

        server.setHandler( context );
        server.start();

        try( CloseableHttpClient client = HttpClientBuilder.create().build() )
        {
            String result = client.execute( new HttpGet( "http://127.0.0.1:" + port + "/" ),
                                            new BasicResponseHandler() );
            Assert.assertEquals( APP_NAME, result.trim() );
        }

    } finally {
        server.stop();
    }
}
 
Example 10
Source File: StartSolrJetty.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
public static void main( String[] args )
  {
    //System.setProperty("solr.solr.home", "../../../example/solr");

    Server server = new Server();
    ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
    // Set some timeout options to make debugging easier.
    connector.setIdleTimeout(1000 * 60 * 60);
    connector.setPort(8983);
    server.setConnectors(new Connector[] { connector });

    WebAppContext bb = new WebAppContext();
    bb.setServer(server);
    bb.setContextPath("/solr");
    bb.setWar("webapp/web");

//    // START JMX SERVER
//    if( true ) {
//      MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
//      MBeanContainer mBeanContainer = new MBeanContainer(mBeanServer);
//      server.getContainer().addEventListener(mBeanContainer);
//      mBeanContainer.start();
//    }

    server.setHandler(bb);

    try {
      System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
      server.start();
      while (System.in.available() == 0) {
        Thread.sleep(5000);
      }
      server.stop();
      server.join();
    }
    catch (Exception e) {
      e.printStackTrace();
      System.exit(100);
    }
  }
 
Example 11
Source File: ReplicatorTestCase.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * Stops the given HTTP Server instance. This method does its best to guarantee
 * that no threads will be left running following this method.
 */
public static void stopHttpServer(Server httpServer) throws Exception {
  httpServer.stop();
  httpServer.join();
}
 
Example 12
Source File: HttpJsonChunksInputOperatorTest.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testHttpInputModule() throws Exception
{

  final List<String> receivedMessages = new ArrayList<String>();
  Handler handler = new AbstractHandler()
  {
    int responseCount = 0;

    @Override
    public void handle(String string, Request rq, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
      ByteArrayOutputStream bos = new ByteArrayOutputStream();
      IOUtils.copy(request.getInputStream(), bos);
      receivedMessages.add(new String(bos.toByteArray()));
      response.setContentType("application/json");
      response.setStatus(HttpServletResponse.SC_OK);
      response.setHeader("Transfer-Encoding", "chunked");
      try {
        JSONObject json = new JSONObject();
        json.put("responseId", "response" + ++responseCount);
        byte[] bytes = json.toString().getBytes();
        response.getOutputStream().println(bytes.length);
        response.getOutputStream().write(bytes);
        response.getOutputStream().println();
        response.getOutputStream().println(0);
        response.getOutputStream().flush();
      } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating response: " + e.toString());
      }

      ((Request)request).setHandled(true);
    }
  };

  Server server = new Server(0);
  server.setHandler(handler);
  server.start();

  String url = "http://localhost:" + server.getConnectors()[0].getLocalPort() + "/somecontext";
  final AbstractHttpInputOperator operator = new HttpJsonChunksInputOperator();

  CollectorTestSink sink = new CollectorTestSink();

  operator.outputPort.setSink(sink);
  operator.setUrl(new URI(url));

  operator.setup(null);
  operator.activate(null);

  int timeoutMillis = 3000;
  while (sink.collectedTuples.isEmpty() && timeoutMillis > 0) {
    operator.emitTuples();
    timeoutMillis -= 20;
    Thread.sleep(20);
  }

  Assert.assertTrue("tuple emitted", sink.collectedTuples.size() > 0);

  Map<String, String> tuple = (Map<String, String>)sink.collectedTuples.get(0);
  Assert.assertEquals("", tuple.get("responseId"), "response1");

  operator.deactivate();
  operator.teardown();
  server.stop();

}
 
Example 13
Source File: ProxyIsAHttpProxyTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@Test
public void testStreaming() throws Exception {
    LinkedBlockingQueue<String> dataQueue = new LinkedBlockingQueue<>();
    Server streamingServer = new Server(0);
    streamingServer.setHandler(newStreamingHandler(dataQueue));
    streamingServer.start();

    Properties props = new Properties();
    props.setProperty("httpOutputBufferSize", "1");
    props.setProperty("httpReverseProxy.foobar.path", "/stream");
    props.setProperty("httpReverseProxy.foobar.proxyTo", streamingServer.getURI().toString());
    props.setProperty("servicePort", "0");
    props.setProperty("webServicePort", "0");

    ProxyConfiguration proxyConfig = PulsarConfigurationLoader.create(props, ProxyConfiguration.class);
    AuthenticationService authService = new AuthenticationService(
            PulsarConfigurationLoader.convertFrom(proxyConfig));

    WebServer webServer = new WebServer(proxyConfig, authService);
    ProxyServiceStarter.addWebServerHandlers(webServer, proxyConfig, null,
                                             new BrokerDiscoveryProvider(proxyConfig, mockZooKeeperClientFactory));
    webServer.start();

    HttpClient httpClient = new HttpClient();
    httpClient.start();
    try {
        LinkedBlockingQueue<Byte> responses = new LinkedBlockingQueue<>();
        CompletableFuture<Result> promise = new CompletableFuture<>();
        httpClient.newRequest(webServer.getServiceUri()).path("/stream")
            .onResponseContent((response, content) -> {
                    while (content.hasRemaining()) {
                        try {
                            responses.put(content.get());
                        } catch (Exception e) {
                            log.error("Error reading response", e);
                            promise.completeExceptionally(e);
                        }
                    }
                })
            .send((result) -> {
                    log.info("Response complete");
                    promise.complete(result);
                });

        dataQueue.put("Some data");
        assertEventuallyTrue(() -> responses.size() == "Some data".length());
        Assert.assertEquals("Some data", drainToString(responses));
        Assert.assertFalse(promise.isDone());

        dataQueue.put("More data");
        assertEventuallyTrue(() -> responses.size() == "More data".length());
        Assert.assertEquals("More data", drainToString(responses));
        Assert.assertFalse(promise.isDone());

        dataQueue.put("DONE");
        assertEventuallyTrue(() -> promise.isDone());
        Assert.assertTrue(promise.get().isSucceeded());
    } finally {
        webServer.stop();
        httpClient.stop();
        streamingServer.stop();
    }
}
 
Example 14
Source File: App.java    From jersey-streaming with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Server httpServer = startServer();
    System.out.println(String.format("Jersey app started with WADL available at %sapplication.wadl\nHit enter to stop it...", BASE_URI, BASE_URI));
    System.in.read();
    httpServer.stop();
}
 
Example 15
Source File: ScanUploadTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
public void scanToDirectory(EmoConfiguration config, String ddlConfigPath, File configFile, File dir, HostAndPort hostAndPort, ValidatorFactory validatorFactory, MetricRegistry metricRegistry) throws Exception {
    // Run the ScanUploadCommand in process.  To do this we need to create a DropWizard Environment.
    Environment environment = new Environment("emodb", Jackson.newObjectMapper(), validatorFactory.getValidator(),
            metricRegistry, ClassLoader.getSystemClassLoader());

    Server server = null;
    try {
        // Start the server
        EmoService emoService = new EmoService(ddlConfigPath, configFile);
        emoService.initialize(new Bootstrap<>(emoService));
        emoService.run(config, environment);
        server = config.getServerFactory().build(environment);
        server.start();

        String scanId = String.format("scan%d", System.currentTimeMillis());

        // Use the API to start the scan and upload
        Client client = new JerseyClientBuilder(environment).build("scanUploadTest");
        ScanStatus scanStatus = client.resource(String.format("http://localhost:%d/stash/1/job/%s", hostAndPort.getPort(), scanId))
                .queryParam("placement", "ugc_global:ugc")
                .queryParam("dest", dir.toURI().toString())
                .accept(MediaType.APPLICATION_JSON_TYPE)
                .post(ScanStatus.class, null);

        assertNotNull(scanStatus);
        assertEquals(scanStatus.getScanId(), scanId);

        // Continuously poll the API until the upload is complete
        boolean complete = false;
        while (!complete) {
            Thread.sleep(5000);

            scanStatus = client.resource(URI.create(String.format("http://localhost:%d/stash/1/job/%s", hostAndPort.getPort(), scanId)))
                    .accept(MediaType.APPLICATION_JSON_TYPE)
                    .get(ScanStatus.class);

            complete = scanStatus.isDone();
        }
    } finally {
        if (server != null) {
            try {
                server.stop();
            } catch (Exception e) {
                _log.warn("Failed to stop server", e);
            }
        }
    }
}
 
Example 16
Source File: TestWebServicesFetcher.java    From datacollector with Apache License 2.0 4 votes vote down vote up
protected void runServer(int port, boolean serverSsl, boolean clientSsl, String httpAuth, Callable<Void> test)
    throws Exception {
  Server server = createServer(port, serverSsl, clientSsl);

  ServletContextHandler contextHandler = new ServletContextHandler();
  if (!httpAuth.equals("none")) {
    File realmFile = new File(getConfDir(), httpAuth + ".properties");
    LoginService loginService = new HashLoginService(httpAuth, realmFile.getAbsolutePath());
    server.addBean(loginService);
    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    switch (httpAuth) {
      case "basic":
        securityHandler.setAuthenticator(new BasicAuthenticator());
        break;
      case "digest":
        securityHandler.setAuthenticator(new DigestAuthenticator());
        break;
    }
    securityHandler.setLoginService(loginService);
    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[]{"user"});
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    securityHandler.addConstraintMapping(mapping);
    contextHandler.setSecurityHandler(securityHandler);
  }

  MockCyberArkServlet servlet = new MockCyberArkServlet();
  contextHandler.addServlet(new ServletHolder(servlet), "/AIMWebService/api/Accounts");
  contextHandler.setContextPath("/");
  server.setHandler(contextHandler);
  try {
    server.start();
    test.call();
  } finally {
    server.stop();
  }
}
 
Example 17
Source File: LittlePhoneBookMain.java    From classreloading with MIT License 4 votes vote down vote up
public static ServerControl startWebServer(Properties config) throws Exception {
	int port = Integer.parseInt(config.getProperty("web.port"));

	// Create the connection pool in the persisted area
	DbPool dbPool = initDatabase(config);

	ServletContextHandler servletContext = new ServletContextHandler(ServletContextHandler.SESSIONS);
       servletContext.setContextPath("/");

	ReloadingWebContext contextLoader = new ReloadingWebContext(
			"qj.blog.classreloading.example5.reloadable.Context",
			() -> ( development ?
					// During development, the dynamic class loader will be used
					new ExceptingClassLoader(
						(className) -> className.startsWith("qj.util"),
						"target/classes"
					) :
					
					// During production, the default class loader will be used
					LittlePhoneBookMain.class.getClassLoader()
			),
			development ? 
					// During development, each time a GET to root URL "/", the dynamic context will be reloaded
					(req) -> req.getMethod().equalsIgnoreCase("GET") && req.getRequestURI().equals("/") : 
					null
	);
	
	// Fields to be set each time the context is reloaded
	contextLoader.setField("development", development);
	contextLoader.setField("buildVersion", version);
	contextLoader.setField("connF", dbPool.connF);
	
	// Method "init" will be called with param "data/example5/web" each time the context is reloaded
	contextLoader.initWith("init", "data/example5/web");
	
	// Method "close" will be called each time context is un-linked ( to create and link to newer context, with 
	// newer classes)
	contextLoader.beforeClose("close");
	
	// The "stubServlet" method will provide "stub" servlets which will retrieve real servlets in the reloaded 
	// context each time a request is served
	servletContext.addServlet( new ServletHolder(contextLoader.stubServlet("jade")), "/");

	servletContext.addServlet( new ServletHolder(wrapServlet(contextLoader.stubServlet("contact"), dbPool.closeThreadConn)),
			"/contact");

	servletContext.addServlet( new ServletHolder(contextLoader.stubServlet("jade")), "*.jade");

	// Serve resources
	ResourceFilter resourceFilter = resourceFilter("data/example5/web");
	servletContext.addFilter(
			new FilterHolder(resourceFilter),
			"/*", EnumSet.<DispatcherType>of(DispatcherType.REQUEST));

	final Server server = new Server(port);
	server.setHandler(servletContext);

	server.start();
	System.out.println("Server started on port " + port);

	final Runnable closeF = () -> {
		System.out.print("Stopping box server...");
		try {
			server.stop();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		dbPool.closePool.e();
		System.out.print(" done.");
	};
	return new ServerControl(closeF);
}
 
Example 18
Source File: AbstractRestCommandJob2Test.java    From gerrit-events with MIT License 4 votes vote down vote up
/**
 * Tests a standard run with a Jetty Server accepting the request.
 *
 * @throws Exception if so.
 */
@Test
public void testRun() throws Exception {
    PatchsetCreated event = new PatchsetCreated();
    Change change = new Change();
    change.setId("oneIdToRuleThemAll");
    change.setProject("project");
    change.setBranch("mastah");
    event.setChange(change);
    PatchSet patchSet = new PatchSet();
    patchSet.setRevision("theOneAndOnly");
    event.setPatchset(patchSet);

    System.out.println("Creating server");
    final Server server = new Server(0);


    final String assertTarget = "/a/changes/project~mastah~oneIdToRuleThemAll/revisions/theOneAndOnly/review";
    final String expectedMessage = "Hello Gerrit";
    final String expectedLabelName = "code-review";
    final int expectedLabelValue = 1;

    TestHandler handler = new TestHandler(assertTarget);
    server.setHandler(handler);
    System.out.println("Starting server");
    server.start();

    AbstractRestCommandJob2 job = setupRestCommandJob2(server, event,
            expectedMessage, expectedLabelName, expectedLabelValue);
    try {
        System.out.println("Running job");
        String response = job.call();
        assertTrue("Invalid target: " + handler.actualTarget, handler.targetOk);

        JSONObject json = JSONObject.fromObject(handler.requestContent);
        System.out.println("JSON: " + json.toString());
        System.out.println("RESPONSE: " + response);
        assertEquals(expectedMessage, json.getString("message"));
        JSONObject labels = json.getJSONObject("labels");
        assertEquals("Bad label value", expectedLabelValue, labels.getInt(expectedLabelName));
    } finally {
        server.stop();
    }
}
 
Example 19
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 20
Source File: SampleBlazegraphCustomFunctionRemoteTest.java    From blazegraph-samples with GNU General Public License v2.0 2 votes vote down vote up
@Test
public void testCustomFunctionRemote() throws Exception{
	
	final String namespace = "test";
	
	final Properties journalProperties = new Properties();
       {
           journalProperties.setProperty(Journal.Options.BUFFER_MODE,
                   BufferMode.MemStore.name());
           
       }
       
       Journal m_indexManager = new Journal(journalProperties);
		
	Server nss = NanoSparqlServer.newInstance(9999, "jettyMavenTest.xml", m_indexManager, null);
	
	final RemoteRepositoryManager m_repo = new RemoteRepositoryManager(
			SampleBlazegraphCustomFunctionRemote.serviceURL , false /* useLBS */);
	
	try {
		
		nss.start();
		
		m_repo.createRepository(namespace, journalProperties);
		
		final String resource = "/data.n3";
		SampleBlazegraphCustomFunctionRemote.loadDataFromResource(m_repo, namespace, resource);

		// execute query
		final TupleQueryResult result = m_repo.getRepositoryForNamespace(namespace)
				.prepareTupleQuery(SampleBlazegraphCustomFunctionRemote.QUERY)
				.evaluate();
		
		int countResults = 0;
		String expected = "http://www.example.com/document1";
		String actual = null;
		
		while(result.hasNext()){
			
			BindingSet bs = result.next();
		
			actual = bs.getBinding("doc").getValue().stringValue();
			
			countResults++;

		}
		
		result.close();
		
		Assert.assertEquals(1, countResults);
		
		Assert.assertEquals(expected, actual);
		
		
		
		
	} finally {
		
		nss.stop();
		
	}
	
}