org.eclipse.jetty.util.log.Log Java Examples

The following examples show how to use org.eclipse.jetty.util.log.Log. 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: Password.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * Get a password. A password is obtained by trying
 * <UL>
 * <LI>Calling <Code>System.getProperty(realm,dft)</Code>
 * <LI>Prompting for a password
 * <LI>Using promptDft if nothing was entered.
 * </UL>
 * 
 * @param realm The realm name for the password, used as a SystemProperty
 *                name.
 * @param dft The default password.
 * @param promptDft The default to use if prompting for the password.
 * @return Password
 */
public static Password getPassword(String realm, String dft, String promptDft)
{
    String passwd = System.getProperty(realm, dft);
    if (passwd == null || passwd.length() == 0)
    {
        try
        {
            System.out.print(realm + ((promptDft != null && promptDft.length() > 0) ? " [dft]" : "") + " : ");
            System.out.flush();
            byte[] buf = new byte[512];
            int len = System.in.read(buf);
            if (len > 0) passwd = new String(buf, 0, len).trim();
        }
        catch (IOException e)
        {
            LOG.warn(Log.EXCEPTION, e);
        }
        if (passwd == null || passwd.length() == 0) passwd = promptDft;
    }
    return new Password(passwd);
}
 
Example #2
Source File: Password.java    From IoTgo_Android_App with MIT License 6 votes vote down vote up
/**
 * Get a password. A password is obtained by trying
 * <UL>
 * <LI>Calling <Code>System.getProperty(realm,dft)</Code>
 * <LI>Prompting for a password
 * <LI>Using promptDft if nothing was entered.
 * </UL>
 * 
 * @param realm The realm name for the password, used as a SystemProperty
 *                name.
 * @param dft The default password.
 * @param promptDft The default to use if prompting for the password.
 * @return Password
 */
public static Password getPassword(String realm, String dft, String promptDft)
{
    String passwd = System.getProperty(realm, dft);
    if (passwd == null || passwd.length() == 0)
    {
        try
        {
            System.out.print(realm + ((promptDft != null && promptDft.length() > 0) ? " [dft]" : "") + " : ");
            System.out.flush();
            byte[] buf = new byte[512];
            int len = System.in.read(buf);
            if (len > 0) passwd = new String(buf, 0, len).trim();
        }
        catch (IOException e)
        {
            LOG.warn(Log.EXCEPTION, e);
        }
        if (passwd == null || passwd.length() == 0) passwd = promptDft;
    }
    return new Password(passwd);
}
 
Example #3
Source File: HttpServerExtension.java    From jphp with Apache License 2.0 6 votes vote down vote up
@Override
public void onRegister(CompileScope scope) {
    registerWrapperClass(scope, Session.class, PWebSocketSession.class);
    registerWrapperClass(scope, Part.class, PHttpPart.class);
    MemoryOperation.registerWrapper(WebSocketSession.class, PWebSocketSession.class);

    registerClass(scope, PHttpServer.class);
    registerClass(scope, PHttpServerRequest.class);
    registerClass(scope, PHttpServerResponse.class);
    registerClass(scope, PHttpAbstractHandler.class);
    registerClass(scope, PHttpRouteFilter.class);
    registerClass(scope, PHttpRouteHandler.class);
    registerClass(scope, PHttpRedirectHandler.class);
    registerClass(scope, PHttpDownloadFileHandler.class);
    registerClass(scope, PHttpResourceHandler.class);
    registerClass(scope, PHttpCORSFilter.class);
    registerClass(scope, PHttpGzipFilter.class);

    Log.setLog(new NoLogging());
}
 
Example #4
Source File: Timeout.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public void tick()
{
    final long expiry = _now-_duration;

    Task task=null;
    while (true)
    {
        try
        {
            synchronized (_lock)
            {
                task= _head._next;
                if (task==_head || task._timestamp>expiry)
                    break;
                task.unlink();
                task._expired=true;
                task.expire();
            }
            
            task.expired();
        }
        catch(Throwable th)
        {
            LOG.warn(Log.EXCEPTION,th);
        }
    }
}
 
Example #5
Source File: WebSocket.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(CordovaInterface cordova, final CordovaWebView webView) {
    super.initialize(cordova, webView);
    _factory = new WebSocketClientFactory();
    _conn = new SparseArray<Connection>();
    _executor = Executors.newSingleThreadExecutor();
    _runner = new TaskRunner();
    _runner.setTask(CREATE_TASK, new ConnectionTask(_factory, _conn));
    _runner.setTask(SEND_TASK, new SendingTask(_conn));
    _runner.setTask(CLOSE_TASK, new DisconnectionTask(_conn));
    _runner.setTask(RESET_TASK, new ResetTask(_conn));
    _runner.setTask(DESTROY_TASK, new DestroyTask(_factory, _conn));
    _executor.execute(_runner);
    Log.setLogLevel(getLogLevel(this.preferences));
}
 
Example #6
Source File: WebSocket.java    From WebSocket-for-Android with Apache License 2.0 5 votes vote down vote up
private static int getLogLevel(CordovaPreferences preferences) {
   String logLevel = preferences.getString("LogLevel", "ERROR");

   if ("VERBOSE".equals(logLevel)) {
       return android.util.Log.VERBOSE;
   } else if ("DEBUG".equals(logLevel)) {
       return android.util.Log.DEBUG;
   } else if ("INFO".equals(logLevel)) {
       return android.util.Log.INFO;
   } else if ("WARN".equals(logLevel)) {
       return android.util.Log.WARN;
   } else {
       return android.util.Log.ERROR;
   }
}
 
Example #7
Source File: WebServer.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructs the web server
 */
public WebServer()
{
   SecurityActions.setSystemProperty("org.eclipse.jetty.util.log.class", JavaUtilLog.class.getName());
   Log.setLog(new JavaUtilLog());

   this.server = null;
   this.host = "localhost";
   this.port = 8080;
   this.mbeanServer = null;
   this.acceptQueueSize = 64;
   this.executorService = null;
   this.handlers = new HandlerList();
}
 
Example #8
Source File: UsernameFunctionProcessorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
private void testSetup(String username, Map<String,String> initParams ) throws Exception {
  String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();

  Log.setLog( new NoOpLogger() );

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter( username ) );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example #9
Source File: HttpdForTests.java    From buck with Apache License 2.0 5 votes vote down vote up
private HttpdForTests(boolean allowedScopedLinkLocal) throws SocketException {
  // Configure the logging for jetty. Which uses a singleton. Ho hum.
  Log.setLog(new JavaUtilLog());
  server = new Server();

  ServerConnector connector = new ServerConnector(server);
  connector.addConnectionFactory(new HttpConnectionFactory());
  // Choose a port randomly upon listening for socket connections.
  connector.setPort(0);
  server.addConnector(connector);

  handlerList = new HandlerList();
  localhost = getLocalhostAddress(allowedScopedLinkLocal).getHostAddress();
}
 
Example #10
Source File: OWLServerMetadataTest.java    From owltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected HttpUriRequest createRequest() throws URISyntaxException {
	URIBuilder uriBuilder = new URIBuilder()
		.setScheme("http")
		.setHost("localhost").setPort(9031)
		.setPath("/");
		
	URI uri = uriBuilder.build();
	Log.getLog().info("Getting URL="+uri);
	HttpUriRequest httpUriRequest = new HttpGet(uri);
	Log.getLog().info("Got URL="+uri);
	return httpUriRequest;
}
 
Example #11
Source File: Main.java    From passopolis-server with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void lifeCycleFailure(LifeCycle event, Throwable cause) {
  try {
    server.stop();
  } catch (Exception e) {
    Log.getLogger(Main.class).warn("Exception thrown while shutting down after failure ", e);
  }
}
 
Example #12
Source File: Resource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * Construct a resource from a url.
 * @param url the url for which to make the resource
 * @param useCaches true enables URLConnection caching if applicable to the type of resource
 * @return
 */
static Resource newResource(URL url, boolean useCaches)
{
    if (url==null)
        return null;

    String url_string=url.toExternalForm();
    if( url_string.startsWith( "file:"))
    {
        try
        {
            FileResource fileResource= new FileResource(url);
            return fileResource;
        }
        catch(Exception e)
        {
            LOG.debug(Log.EXCEPTION,e);
            return new BadResource(url,e.toString());
        }
    }
    else if( url_string.startsWith( "jar:file:"))
    {
        return new JarFileResource(url, useCaches);
    }
    else if( url_string.startsWith( "jar:"))
    {
        return new JarResource(url, useCaches);
    }

    return new URLResource(url,null,useCaches);
}
 
Example #13
Source File: FileResource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
@Override
public URL getAlias()
{
    if (__checkAliases && !_aliasChecked)
    {
        try
        {    
            String abs=_file.getAbsolutePath();
            String can=_file.getCanonicalPath();
            
            if (abs.length()!=can.length() || !abs.equals(can))
                _alias=Resource.toURL(new File(can));
            
            _aliasChecked=true;
            
            if (_alias!=null && LOG.isDebugEnabled())
            {
                LOG.debug("ALIAS abs="+abs);
                LOG.debug("ALIAS can="+can);
            }
        }
        catch(Exception e)
        {
            LOG.warn(Log.EXCEPTION,e);
            return getURL();
        }                
    }
    return _alias;
}
 
Example #14
Source File: Resource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
/**
 * Construct a resource from a url.
 * @param url the url for which to make the resource
 * @param useCaches true enables URLConnection caching if applicable to the type of resource
 * @return
 */
static Resource newResource(URL url, boolean useCaches)
{
    if (url==null)
        return null;

    String url_string=url.toExternalForm();
    if( url_string.startsWith( "file:"))
    {
        try
        {
            FileResource fileResource= new FileResource(url);
            return fileResource;
        }
        catch(Exception e)
        {
            LOG.debug(Log.EXCEPTION,e);
            return new BadResource(url,e.toString());
        }
    }
    else if( url_string.startsWith( "jar:file:"))
    {
        return new JarFileResource(url, useCaches);
    }
    else if( url_string.startsWith( "jar:"))
    {
        return new JarResource(url, useCaches);
    }

    return new URLResource(url,null,useCaches);
}
 
Example #15
Source File: FileResource.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
@Override
public URL getAlias()
{
    if (__checkAliases && !_aliasChecked)
    {
        try
        {    
            String abs=_file.getAbsolutePath();
            String can=_file.getCanonicalPath();
            
            if (abs.length()!=can.length() || !abs.equals(can))
                _alias=Resource.toURL(new File(can));
            
            _aliasChecked=true;
            
            if (_alias!=null && LOG.isDebugEnabled())
            {
                LOG.debug("ALIAS abs="+abs);
                LOG.debug("ALIAS can="+can);
            }
        }
        catch(Exception e)
        {
            LOG.warn(Log.EXCEPTION,e);
            return getURL();
        }                
    }
    return _alias;
}
 
Example #16
Source File: Timeout.java    From IoTgo_Android_App with MIT License 5 votes vote down vote up
public void tick()
{
    final long expiry = _now-_duration;

    Task task=null;
    while (true)
    {
        try
        {
            synchronized (_lock)
            {
                task= _head._next;
                if (task==_head || task._timestamp>expiry)
                    break;
                task.unlink();
                task._expired=true;
                task.expire();
            }
            
            task.expired();
        }
        catch(Throwable th)
        {
            LOG.warn(Log.EXCEPTION,th);
        }
    }
}
 
Example #17
Source File: JettyHttpServer.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static void initializeJettyLogging() {
    // Note: Jetty is logging stderr if no logger is explicitly configured.
    try {
        Log.setLog(new JavaUtilLog());
    } catch (Exception e) {
        throw new RuntimeException("Unable to initialize logging framework for Jetty");
    }
}
 
Example #18
Source File: JettyComposer.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
public static void compose(Server server) {
    //Servlets + Guice
    ServletContextHandler servletContextHandler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addFilter(GuiceFilter.class, "/*", EnumSet.allOf(DispatcherType.class));
    servletContextHandler.addServlet(DefaultServlet.class, "/");

    //JMX stuff...
    MBeanContainer mbContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
    server.addEventListener(mbContainer);
    server.addBean(mbContainer);
    server.addBean(Log.getLog());
}
 
Example #19
Source File: ITServletContainer.java    From brave with Apache License 2.0 4 votes vote down vote up
protected ITServletContainer(ServerController serverController) {
  Log.setLog(new Log4J2Log());
  this.serverController = serverController;
}
 
Example #20
Source File: ITSparkTracing.java    From brave with Apache License 2.0 4 votes vote down vote up
public ITSparkTracing() {
  Log.setLog(new Log4J2Log());
}
 
Example #21
Source File: HttpdForTests.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an HTTPS server that requires client authentication (though doesn't validate the chain)
 *
 * @param caPath The path to a CA certificate to put in the keystore.
 * @param certificatePath The path to a pem encoded x509 certificate
 * @param keyPath The path to a pem encoded PKCS#8 certificate
 * @throws IOException Any of the keys could not be read
 * @throws KeyStoreException There's a problem writing the key into the keystore
 * @throws CertificateException The certificate was not valid
 * @throws NoSuchAlgorithmException The algorithm used by the certificate/key are invalid
 */
public HttpdForTests(Path caPath, Path certificatePath, Path keyPath)
    throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

  // Configure the logging for jetty. Which uses a singleton. Ho hum.
  Log.setLog(new JavaUtilLog());
  server = new Server();

  String password = "super_sekret";

  ImmutableList<X509Certificate> caCerts =
      ClientCertificateHandler.parseCertificates(Optional.of(caPath), true);
  ClientCertificateHandler.CertificateInfo certInfo =
      ClientCertificateHandler.parseCertificateChain(Optional.of(certificatePath), true).get();
  PrivateKey privateKey =
      ClientCertificateHandler.parsePrivateKey(
              Optional.of(keyPath), certInfo.getPrimaryCert(), true)
          .get();

  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, password.toCharArray());
  for (int i = 0; i < caCerts.size(); i++) {
    ks.setCertificateEntry(String.format("ca%d", i), caCerts.get(i));
  }
  ks.setKeyEntry(
      "private",
      privateKey,
      password.toCharArray(),
      new Certificate[] {certInfo.getPrimaryCert()});

  SslContextFactory sslFactory = new SslContextFactory();
  sslFactory.setKeyStore(ks);
  sslFactory.setKeyStorePassword(password);
  sslFactory.setCertAlias("private");
  sslFactory.setTrustStore(ks);
  sslFactory.setTrustStorePassword(password);
  // *Require* a client cert, but don't validate it (getting TLS auth working properly was a
  // bit of a pain). We'll store peers' certs in the handler, and validate the certs manually
  // in our tests.
  sslFactory.setNeedClientAuth(true);
  sslFactory.setTrustAll(true);

  HttpConfiguration https_config = new HttpConfiguration();
  https_config.setSecurePort(0);
  https_config.setSecureScheme("https");
  https_config.addCustomizer(new SecureRequestCustomizer());

  ServerConnector sslConnector =
      new ServerConnector(
          server,
          new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.toString()),
          new HttpConnectionFactory(https_config));
  server.addConnector(sslConnector);

  handlerList = new HandlerList();
  localhost = getLocalhostAddress(false).getHostAddress();
}
 
Example #22
Source File: JettyServer.java    From selenium with Apache License 2.0 4 votes vote down vote up
public JettyServer(BaseServerOptions options, HttpHandler handler) {
  this.handler = Require.nonNull("Handler", handler);
  int port = options.getPort() == 0 ? PortProber.findFreePort() : options.getPort();

  String host = options.getHostname().orElseGet(() -> {
    try {
      return new NetworkUtils().getNonLoopbackAddressOfThisMachine();
    } catch (WebDriverException ignored) {
      return "localhost";
    }
  });

  try {
    this.url = new URL("http", host, port, "");
  } catch (MalformedURLException e) {
    throw new UncheckedIOException(e);
  }

  Log.setLog(new JavaUtilLog());
  this.server = new org.eclipse.jetty.server.Server(
      new QueuedThreadPool(options.getMaxServerThreads()));

  this.servletContextHandler = new ServletContextHandler(ServletContextHandler.SECURITY);
  ConstraintSecurityHandler
      securityHandler =
      (ConstraintSecurityHandler) servletContextHandler.getSecurityHandler();

  Constraint disableTrace = new Constraint();
  disableTrace.setName("Disable TRACE");
  disableTrace.setAuthenticate(true);
  ConstraintMapping disableTraceMapping = new ConstraintMapping();
  disableTraceMapping.setConstraint(disableTrace);
  disableTraceMapping.setMethod("TRACE");
  disableTraceMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(disableTraceMapping);

  Constraint enableOther = new Constraint();
  enableOther.setName("Enable everything but TRACE");
  ConstraintMapping enableOtherMapping = new ConstraintMapping();
  enableOtherMapping.setConstraint(enableOther);
  enableOtherMapping.setMethodOmissions(new String[]{"TRACE"});
  enableOtherMapping.setPathSpec("/");
  securityHandler.addConstraintMapping(enableOtherMapping);

  // Allow CORS: Whether the Selenium server should allow web browser connections from any host
  if (options.getAllowCORS()) {
    FilterHolder
        filterHolder = servletContextHandler.addFilter(CrossOriginFilter.class, "/*", EnumSet
        .of(DispatcherType.REQUEST));
    filterHolder.setInitParameter("allowedMethods", "GET,POST,PUT,DELETE,HEAD");

    // Warning user
    LOG.warning("You have enabled CORS requests from any host. "
                + "Be careful not to visit sites which could maliciously "
                + "try to start Selenium sessions on your machine");
  }

  server.setHandler(servletContextHandler);

  HttpConfiguration httpConfig = new HttpConfiguration();
  httpConfig.setSecureScheme("https");

  ServerConnector http = new ServerConnector(server, new HttpConnectionFactory(httpConfig));
  options.getHostname().ifPresent(http::setHost);
  http.setPort(getUrl().getPort());

  http.setIdleTimeout(500000);

  server.setConnectors(new Connector[]{http});
}
 
Example #23
Source File: JettyRunner.java    From appengine-java-vm-runtime with Apache License 2.0 4 votes vote down vote up
public void waitForStarted(long timeout,TimeUnit units) throws InterruptedException {
  if (!started.await(timeout, units) || !server.isStarted())
    throw new IllegalStateException("server state="+server.getState());

  Log.getLogger(Server.class).info("Waited!");
}
 
Example #24
Source File: FrontendFunctionProcessorTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private void testSetup(String username, Map<String, String> initParams, Attributes attributes) throws Exception {
  ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();

  GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
  EasyMock.expect( mockGatewayServices.getService(ServiceType.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();

  EasyMock.replay( mockServiceRegistry, mockGatewayServices );

  String descriptorUrl = TestUtils.getResourceUrl( FrontendFunctionProcessorTest.class, "rewrite.xml" ).toExternalForm();

  Log.setLog( new NoOpLogger() );

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );

  if( attributes != null ) {
    server.getContext().setAttributes( attributes );
  }
  server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
  server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter( username ) );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example #25
Source File: ServiceRegistryFunctionsTest.java    From knox with Apache License 2.0 4 votes vote down vote up
private void testSetup(String username, Map<String,String> initParams ) throws Exception {
  ServiceRegistry mockServiceRegistry = EasyMock.createNiceMock( ServiceRegistry.class );
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "NAMENODE" ) ).andReturn( "test-nn-scheme://test-nn-host:411" ).anyTimes();
  EasyMock.expect( mockServiceRegistry.lookupServiceURL( "test-cluster", "JOBTRACKER" ) ).andReturn( "test-jt-scheme://test-jt-host:511" ).anyTimes();

  GatewayServices mockGatewayServices = EasyMock.createNiceMock( GatewayServices.class );
  EasyMock.expect( mockGatewayServices.getService(ServiceType.SERVICE_REGISTRY_SERVICE) ).andReturn( mockServiceRegistry ).anyTimes();

  EasyMock.replay( mockServiceRegistry, mockGatewayServices );

  String descriptorUrl = getTestResource( "rewrite.xml" ).toExternalForm();

  Log.setLog( new NoOpLogger() );

  server = new ServletTester();
  server.setContextPath( "/" );
  server.getContext().addEventListener( new UrlRewriteServletContextListener() );
  server.getContext().setInitParameter(
      UrlRewriteServletContextListener.DESCRIPTOR_LOCATION_INIT_PARAM_NAME, descriptorUrl );
  server.getContext().setAttribute( GatewayServices.GATEWAY_CLUSTER_ATTRIBUTE, "test-cluster" );
  server.getContext().setAttribute( GatewayServices.GATEWAY_SERVICES_ATTRIBUTE, mockGatewayServices );

  FilterHolder setupFilter = server.addFilter( SetupFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  setupFilter.setFilter( new SetupFilter( username ) );
  FilterHolder rewriteFilter = server.addFilter( UrlRewriteServletFilter.class, "/*", EnumSet.of( DispatcherType.REQUEST ) );
  if( initParams != null ) {
    for( Map.Entry<String,String> entry : initParams.entrySet() ) {
      rewriteFilter.setInitParameter( entry.getKey(), entry.getValue() );
    }
  }
  rewriteFilter.setFilter( new UrlRewriteServletFilter() );

  interactions = new ArrayDeque<>();

  ServletHolder servlet = server.addServlet( MockServlet.class, "/" );
  servlet.setServlet( new MockServlet( "mock-servlet", interactions ) );

  server.start();

  interaction = new MockInteraction();
  request = HttpTester.newRequest();
  response = null;
}
 
Example #26
Source File: ProxyServlet.java    From logbook-kai with MIT License 4 votes vote down vote up
/**
 * @return a logger instance with a name derived from this servlet's name.
 */
protected Logger createLogger() {
    String name = this.getServletConfig().getServletName();
    name = name.replace('-', '.');
    return Log.getLogger(name);
}
 
Example #27
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();
//			}
		}
	}
 
Example #28
Source File: WebAPI.java    From Web-API with MIT License 4 votes vote down vote up
@Listener
public void onInitialization(GameInitializationEvent event) {
    Timings.STARTUP.startTiming();

    logger.info(Constants.NAME + " v" + Constants.VERSION + " is starting...");

    logger.info("Setting up jetty logger...");
    Log.setLog(new JettyLogger());

    // Main init function, that is also called when reloading the plugin
    init(null);

    logger.info(Constants.NAME + " ready");

    Timings.STARTUP.stopTiming();
}
 
Example #29
Source File: JettyFactory.java    From kumuluzee with MIT License 3 votes vote down vote up
public Server create() {

        Log.setLog(new JavaUtilLog());

        Server server = new Server(createThreadPool());

        server.addBean(createClassList());
        server.setStopAtShutdown(true);
        server.setConnectors(createConnectors(server));

        return server;
    }