Java Code Examples for org.eclipse.jetty.security.ConstraintSecurityHandler#setLoginService()

The following examples show how to use org.eclipse.jetty.security.ConstraintSecurityHandler#setLoginService() . 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: CustomInitTest.java    From rest-utils with Apache License 2.0 6 votes vote down vote up
@Override
public void accept(final ServletContextHandler context) {
  final List<String> roles = config.getList(RestConfig.AUTHENTICATION_ROLES_CONFIG);
  final Constraint constraint = new Constraint();
  constraint.setAuthenticate(true);
  constraint.setRoles(roles.toArray(new String[0]));

  final ConstraintMapping constraintMapping = new ConstraintMapping();
  constraintMapping.setConstraint(constraint);
  constraintMapping.setMethod("*");
  constraintMapping.setPathSpec("/*");

  final ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
  securityHandler.addConstraintMapping(constraintMapping);
  securityHandler.setAuthenticator(new BasicAuthenticator());
  securityHandler.setLoginService(new TestLoginService());
  securityHandler.setRealmName("TestRealm");

 context.setSecurityHandler(securityHandler);
}
 
Example 2
Source File: InMemoryIdentityManager.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public InMemoryIdentityManager() {
	loginService = new HashLoginService();
	loginService.setName(realm);

	securityHandler = new ConstraintSecurityHandler();
	securityHandler.setAuthenticator(new BasicAuthenticator());
	securityHandler.setRealmName(realm);
	securityHandler.setLoginService(loginService);

	Constraint constraint = new Constraint();
	constraint.setName(Constraint.__BASIC_AUTH);
	//		constraint.setRoles(new String[] { "getRole", "postRole", "allRole" });
	constraint.setRoles(new String[]{Constraint.ANY_AUTH, "getRole", "postRole", "allRole"});
	constraint.setAuthenticate(true);

	ConstraintMapping cm = new ConstraintMapping();
	cm.setConstraint(constraint);
	cm.setPathSpec("/*");
	securityHandler.addConstraintMapping(cm);
}
 
Example 3
Source File: GatewayMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example 4
Source File: ManagerApiMicroService.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 * @throws Exception
 */
protected SecurityHandler createSecurityHandler() throws Exception {
    HashLoginService l = new HashLoginService();
    // UserStore is now separate store entity and must be added to HashLoginService
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);
    for (User user : Users.getUsers()) {
        userStore.addUser(user.getId(), Credential.getCredential(user.getPassword()), user.getRolesAsArray());
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example 5
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a basic auth security handler.
 */
private SecurityHandler createSecurityHandler() {
    HashLoginService l = new HashLoginService();
    UserStore userStore = new UserStore();
    l.setUserStore(userStore);

    for (String [] userInfo : TestUsers.USERS) {
        String user = userInfo[0];
        String pwd = userInfo[1];
        String[] roles = new String[] { "apiuser" };
        if (user.startsWith("admin")) {
            roles = new String[] { "apiuser", "apiadmin"};
        }
        userStore.addUser(user, Credential.getCredential(pwd), roles);
    }
    l.setName("apimanrealm");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("apimanrealm");
    csh.setLoginService(l);

    return csh;
}
 
Example 6
Source File: GerritRestClientTest.java    From gerrit-rest-java-client with Apache License 2.0 6 votes vote down vote up
private static SecurityHandler basicAuth(String username, String password, String realm) {
    HashLoginService loginService = new HashLoginService();
    loginService.putUser(username, Credential.getCredential(password), new String[]{"user"});
    loginService.setName(realm);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__DIGEST_AUTH);
    constraint.setRoles(new String[]{"user"});
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new BasicAuthenticator());
    csh.setRealmName("realm");
    csh.addConstraintMapping(constraintMapping);
    csh.setLoginService(loginService);
    return csh;
}
 
Example 7
Source File: DigestAuthSupplierJettyTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() {
    server = new Server(PORT);

    HashLoginService loginService = new HashLoginService();
    loginService.setName("My Realm");
    UserStore userStore = new UserStore();
    String[] roles = new String[] {"user"};
    userStore.addUser(USER, Credential.getCredential(PWD), roles);
    loginService.setUserStore(userStore);

    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__DIGEST_AUTH);
    constraint.setRoles(roles);
    constraint.setAuthenticate(true);

    ConstraintMapping cm = new ConstraintMapping();
    cm.setConstraint(constraint);
    cm.setPathSpec("/*");

    ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
    csh.setAuthenticator(new DigestAuthenticator());
    csh.addConstraintMapping(cm);
    csh.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setSecurityHandler(csh);
    context.setContextPath("/");
    server.setHandler(context);
    context.addServlet(new ServletHolder(new TestServlet()), "/*");

    try {
        server.start();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureForm(Configuration conf, Server server, String mode) {
  ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();

  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);
  securityHandler.setLoginService(loginService);

  FormAuthenticator authenticator = new FormAuthenticator("/login.html", "/login.html?error=true", true);
  securityHandler.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(authenticator, runtimeInfo, conf)));
  return securityHandler;
}
 
Example 9
Source File: WebServerTask.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private ConstraintSecurityHandler configureDigestBasic(Configuration conf, Server server, String mode) {
  LoginService loginService = getLoginService(conf, mode);
  server.addBean(loginService);

  ConstraintSecurityHandler security = new ConstraintSecurityHandler();
  switch (mode) {
    case "digest":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new DigestAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    case "basic":
      security.setAuthenticator(injectActivationCheck(new ProxyAuthenticator(
          new BasicAuthenticator(),
          runtimeInfo,
          conf
      )));
      break;
    default:
      // no action
      break;
  }
  security.setLoginService(loginService);
  return security;
}
 
Example 10
Source File: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public static SecurityHandler getBasicAuthHandler(HttpSourceConfigs httpCourceConf) {
  List<CredentialValueUserPassBean> basicAuthUsers = httpCourceConf.getBasicAuthUsers();

  HashLoginService loginService = new HashLoginService();
  UserStore userStore = new UserStore();

  boolean empty = true;
  for (CredentialValueUserPassBean userPassBean : basicAuthUsers) {
    String username = userPassBean.getUsername();
    String password = userPassBean.get();
    if(StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
      userStore.addUser(username, new Password(password), new String[]{"sdc"});
      empty = false;
    }
  }
  if(empty) {
    return null;
  }

  loginService.setUserStore(userStore);

  Constraint constraint = new Constraint(Constraint.__BASIC_AUTH,"sdc");
  constraint.setAuthenticate(true);

  ConstraintMapping mapping = new ConstraintMapping();
  mapping.setConstraint(constraint);
  mapping.setPathSpec("/*");

  ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
  handler.setAuthenticator(new BasicAuthenticator());
  handler.addConstraintMapping(mapping);
  handler.setLoginService(loginService);

  return handler;
}
 
Example 11
Source File: JettySecurity.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public static ConstraintSecurityHandler createSecurityHandler() {
    Constraint constraint = new Constraint("BASIC", "customer");
    constraint.setAuthenticate(true);

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setConstraint(constraint);
    mapping.setPathSpec("/*");

    ConstraintSecurityHandler handler = new ConstraintSecurityHandler();
    handler.addConstraintMapping(mapping);
    handler.setAuthenticator(new BasicAuthenticator());
    handler.setLoginService(new HashLoginService("RiderAutoParts", "src/main/resources/users.properties"));

    return handler;
}
 
Example 12
Source File: ClientJettyStreamITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    try {
        server.start();
    } catch (Exception e) {
        fail("Failed to start server: " + e);
    }
}
 
Example 13
Source File: JavaxServletSyncServerITest.java    From hawkular-apm with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void initClass() throws Exception {
    server = new Server(8180);

    LoginService loginService = new HashLoginService("MyRealm",
            "src/test/resources/realm.properties");
    server.addBean(loginService);

    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    server.setHandler(security);

    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });

    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);

    security.setConstraintMappings(Collections.singletonList(mapping));
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(loginService);

    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath("/");
    context.addServlet(EmbeddedServlet.class, "/hello");
    security.setHandler(context);

    server.start();
}
 
Example 14
Source File: KafkaCruiseControlApp.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void maybeSetSecurityHandler(ServletContextHandler contextHandler) throws ServletException {
  SecurityProvider securityProvider = null;
  if (_config.getBoolean(WebServerConfig.WEBSERVER_SECURITY_ENABLE_CONFIG)) {
    securityProvider = _config.getConfiguredInstance(WebServerConfig.WEBSERVER_SECURITY_PROVIDER_CONFIG, SecurityProvider.class);
  }
  if (securityProvider != null) {
    securityProvider.init(_config);
    ConstraintSecurityHandler securityHandler = new CruiseControlSecurityHandler();
    securityHandler.setConstraintMappings(securityProvider.constraintMappings());
    securityHandler.setAuthenticator(securityProvider.authenticator());
    securityHandler.setLoginService(securityProvider.loginService());
    securityHandler.setRoles(securityProvider.roles());
    contextHandler.setSecurityHandler(securityHandler);
  }
}
 
Example 15
Source File: WebServerTestCase.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the web server delivering response from the provided connection.
 * @param mockConnection the sources for responses
 * @throws Exception if a problem occurs
 */
protected void startWebServer(final MockWebConnection mockConnection) throws Exception {
    if (STATIC_SERVER_ == null) {
        final Server server = buildServer(PORT);

        final WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setResourceBase("./");

        if (isBasicAuthentication()) {
            final Constraint constraint = new Constraint();
            constraint.setName(Constraint.__BASIC_AUTH);
            constraint.setRoles(new String[]{"user"});
            constraint.setAuthenticate(true);

            final ConstraintMapping constraintMapping = new ConstraintMapping();
            constraintMapping.setConstraint(constraint);
            constraintMapping.setPathSpec("/*");

            final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler();
            handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties"));
            handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping});
        }

        context.addServlet(MockWebConnectionServlet.class, "/*");
        server.setHandler(context);

        tryStart(PORT, server);
        STATIC_SERVER_ = server;
    }
    MockWebConnectionServlet.setMockconnection(mockConnection);
}
 
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: HttpReceiverServerPush.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public static SecurityHandler getSpnegoAuthHandler(HttpSourceConfigs httpCourceConf, Stage.Context context) throws StageException {
  String domainRealm = httpCourceConf.getSpnegoConfigBean().getKerberosRealm();
  String principal = httpCourceConf.getSpnegoConfigBean().getSpnegoPrincipal();
  String keytab = httpCourceConf.getSpnegoConfigBean().getSpnegoKeytabFilePath();

  File f = new File(context.getResourcesDirectory()+"/spnego.conf");
  try {
    PrintWriter pw = new PrintWriter(f);
    pw.println(String.format(JGSS_INITITATE ,principal,keytab) +"\n"+ String.format(JGSS_ACCEPT,principal,keytab));
    pw.close();
  } catch (IOException e) {
    throw new StageException(Errors.HTTP_36, e);
  }

  System.setProperty(JAVAX_SECURITY_AUTH_USE_SUBJECT_CREDS_ONLY, "false");
  System.setProperty(JAVA_SECURITY_AUTH_LOGIN_CONFIG, context.getResourcesDirectory()+"/spnego.conf");

  Constraint constraint = new Constraint();
  constraint.setName(Constraint.__SPNEGO_AUTH);
  constraint.setRoles(new String[]{domainRealm});
  constraint.setAuthenticate(true);

  ConstraintMapping cm = new ConstraintMapping();
  cm.setConstraint(constraint);
  cm.setPathSpec("/*");

  SpnegoLoginService loginService = new SpnegoLoginService(){
    @Override
    protected void doStart() throws Exception {
      // Override the parent implementation to set the targetName without having
      // an extra .properties file.
      final Field targetNameField = SpnegoLoginService.class.getDeclaredField(TARGET_NAME_FIELD_NAME);
      targetNameField.setAccessible(true);
      targetNameField.set(this, principal);
    }
  };
  loginService.setName(domainRealm);

  ConstraintSecurityHandler csh = new ConstraintSecurityHandler();
  csh.setAuthenticator(new SpnegoAuthenticator());
  csh.setLoginService(loginService);
  csh.setConstraintMappings(new ConstraintMapping[]{cm});
  csh.setRealmName(domainRealm);

  return csh;
}
 
Example 18
Source File: EmissaryServer.java    From emissary with Apache License 2.0 4 votes vote down vote up
/**
 * Creates and starts a server that is bound into the local Namespace using DEFAULT_NAMESPACE_NAME and returned
 *
 * 
 */
public Server startServer() {
    // do what StartJetty and then JettyServer did to start
    try {
        // Resource.setDefaultUseCaches(false);

        // needs to be loaded first into the server as it setups up Emissary stuff
        ContextHandler emissaryHandler = buildEmissaryHandler();
        // TODO: rework this, no need for it be set with a context path but if this
        // is left out, it matches / and nothing works correctly
        emissaryHandler.setContextPath("/idontreallyservecontentnowdoi");
        ContextHandler lbConfigHandler = buildLogbackConfigHandler();
        lbConfigHandler.setContextPath("/lbConfig");
        ContextHandler apiHandler = buildApiHandler();
        apiHandler.setContextPath("/api");
        ContextHandler mvcHandler = buildMVCHandler();
        mvcHandler.setContextPath("/emissary");
        // needs to be loaded last into the server so other contexts can match or fall through
        ContextHandler staticHandler = buildStaticHandler();
        staticHandler.setContextPath("/");

        LoginService loginService = buildLoginService();
        ConstraintSecurityHandler security = buildSecurityHandler();
        security.setLoginService(loginService);

        // secure some of the contexts
        final HandlerList securedHandlers = new HandlerList();
        securedHandlers.addHandler(lbConfigHandler);
        securedHandlers.addHandler(apiHandler);
        securedHandlers.addHandler(mvcHandler);
        securedHandlers.addHandler(staticHandler);
        security.setHandler(securedHandlers);

        final HandlerList handlers = new HandlerList();
        handlers.addHandler(emissaryHandler); // not secured, no endpoints and must be loaded first
        handlers.addHandler(security);

        Server server = configureServer();
        server.setHandler(handlers);
        server.addBean(loginService);
        server.setStopAtShutdown(true);
        server.setStopTimeout(10000l);
        if (this.cmd.shouldDumpJettyBeans()) {
            server.dump(System.out);
        }
        this.server = server;
        bindServer(); // emissary specific

        server.start();
        // server.join(); // don't join so we can shutdown

        String serverLocation = cmd.getScheme() + "://" + cmd.getHost() + ":" + cmd.getPort();

        // write out env.sh file here
        Path envsh = Paths.get(ConfigUtil.getProjectBase() + File.separator + "env.sh");
        if (Files.exists(envsh)) {
            LOG.debug("Removing old {}", envsh.toAbsolutePath());
            Files.delete(envsh);
        }
        String envURI = serverLocation + "/api/env.sh";
        EmissaryResponse er = new EmissaryClient().send(new HttpGet(envURI));
        String envString = er.getContentString();
        Files.createFile(envsh);
        Files.write(envsh, envString.getBytes());
        LOG.info("Wrote {}", envsh.toAbsolutePath());
        LOG.debug(" with \n{}", envString);

        if (cmd.isPause()) {
            pause(true);
        } else {
            unpause(true);
        }

        LOG.info("Started EmissaryServer at {}", serverLocation);
        return server;
    } catch (Throwable t) {
        t.printStackTrace(System.err);
        throw new RuntimeException("Emissary server didn't start", t);
    }
}
 
Example 19
Source File: JettyHttpServer.java    From everrest with Eclipse Public License 2.0 4 votes vote down vote up
public void start() throws Exception {
    RequestLogHandler handler = new RequestLogHandler();

    if (context == null) {
        context = new ServletContextHandler(handler, "/", ServletContextHandler.SESSIONS);
    }

    context.setEventListeners(new EventListener[]{new EverrestInitializedListener()});
    ServletHolder servletHolder = new ServletHolder(new EverrestServlet());

    context.addServlet(servletHolder, UNSECURE_PATH_SPEC);
    context.addServlet(servletHolder, SECURE_PATH_SPEC);

    //set up security
    Constraint constraint = new Constraint();
    constraint.setName(Constraint.__BASIC_AUTH);
    constraint.setRoles(new String[]{"cloud-admin", "users", "user", "temp_user"});
    constraint.setAuthenticate(true);

    ConstraintMapping constraintMapping = new ConstraintMapping();
    constraintMapping.setConstraint(constraint);
    constraintMapping.setPathSpec(SECURE_PATH_SPEC);

    ConstraintSecurityHandler securityHandler = new ConstraintSecurityHandler();
    securityHandler.addConstraintMapping(constraintMapping);

    HashLoginService loginService = new HashLoginService();

    UserStore userStore = new UserStore();

    userStore.addUser(ADMIN_USER_NAME, new Password(ADMIN_USER_PASSWORD),
                         new String[]{"cloud-admin",
                                      "users",
                                      "user",
                                      "temp_user",
                                      "developer",
                                      "admin",
                                      "workspace/developer",
                                      "workspace/admin",
                                      "account/owner",
                                      "account/member",
                                      "system/admin",
                                      "system/manager"
                         });
    userStore.addUser(MANAGER_USER_NAME, new Password(MANAGER_USER_PASSWORD), new String[]{"cloud-admin",
                                                                                              "user",
                                                                                              "temp_user",
                                                                                              "users"});
    loginService.setUserStore(userStore);

    securityHandler.setLoginService(loginService);
    securityHandler.setAuthenticator(new BasicAuthenticator());

    context.setSecurityHandler(securityHandler);

    server.setHandler(handler);

    server.start();
    ResourceBinder binder =
            (ResourceBinder)context.getServletContext().getAttribute(ResourceBinder.class.getName());
    DependencySupplier dependencies =
            (DependencySupplier)context.getServletContext().getAttribute(DependencySupplier.class.getName());
    GroovyResourcePublisher groovyPublisher = new GroovyResourcePublisher(binder, dependencies);
    context.getServletContext().setAttribute(GroovyResourcePublisher.class.getName(), groovyPublisher);

}
 
Example 20
Source File: WebDriverTestCase.java    From htmlunit with Apache License 2.0 4 votes vote down vote up
/**
 * Starts the web server delivering response from the provided connection.
 * @param mockConnection the sources for responses
 * @param serverCharset the {@link Charset} at the server side
 * @throws Exception if a problem occurs
 */
protected void startWebServer(final MockWebConnection mockConnection, final Charset serverCharset)
        throws Exception {
    if (Boolean.FALSE.equals(LAST_TEST_UsesMockWebConnection_)) {
        stopWebServers();
    }

    LAST_TEST_UsesMockWebConnection_ = Boolean.TRUE;
    if (STATIC_SERVER_ == null) {
        final Server server = buildServer(PORT);

        final WebAppContext context = new WebAppContext();
        context.setContextPath("/");
        context.setResourceBase("./");

        if (isBasicAuthentication()) {
            final Constraint constraint = new Constraint();
            constraint.setName(Constraint.__BASIC_AUTH);
            constraint.setRoles(new String[]{"user"});
            constraint.setAuthenticate(true);

            final ConstraintMapping constraintMapping = new ConstraintMapping();
            constraintMapping.setConstraint(constraint);
            constraintMapping.setPathSpec("/*");

            final ConstraintSecurityHandler handler = (ConstraintSecurityHandler) context.getSecurityHandler();
            handler.setLoginService(new HashLoginService("MyRealm", "./src/test/resources/realm.properties"));
            handler.setConstraintMappings(new ConstraintMapping[]{constraintMapping});
        }

        context.addServlet(MockWebConnectionServlet.class, "/*");
        if (serverCharset != null) {
            AsciiEncodingFilter.CHARSET_ = serverCharset;
            context.addFilter(AsciiEncodingFilter.class, "/*",
                    EnumSet.of(DispatcherType.INCLUDE, DispatcherType.REQUEST));
        }
        server.setHandler(context);
        WebServerTestCase.tryStart(PORT, server);

        STATIC_SERVER_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServerStarter"));
        STATIC_SERVER_ = server;
    }
    MockWebConnectionServlet.MockConnection_ = mockConnection;

    if (STATIC_SERVER2_ == null && needThreeConnections()) {
        final Server server2 = buildServer(PORT2);
        final WebAppContext context2 = new WebAppContext();
        context2.setContextPath("/");
        context2.setResourceBase("./");
        context2.addServlet(MockWebConnectionServlet.class, "/*");
        server2.setHandler(context2);
        WebServerTestCase.tryStart(PORT2, server2);

        STATIC_SERVER2_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer2Starter"));
        STATIC_SERVER2_ = server2;

        final Server server3 = buildServer(PORT3);
        final WebAppContext context3 = new WebAppContext();
        context3.setContextPath("/");
        context3.setResourceBase("./");
        context3.addServlet(MockWebConnectionServlet.class, "/*");
        server3.setHandler(context3);
        WebServerTestCase.tryStart(PORT3, server3);

        STATIC_SERVER3_STARTER_ = ExceptionUtils.getStackTrace(new Throwable("StaticServer3Starter"));
        STATIC_SERVER3_ = server3;
        /*
         * The mock connection servlet call sit under both servers, so long as tests
         * keep the URLs distinct.
         */
    }
}