org.jboss.arquillian.container.spi.Container Java Examples

The following examples show how to use org.jboss.arquillian.container.spi.Container. 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: Registry.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private Container domainContainer(ServiceLoader loader, ContainerDef definition) {
    for (Container container : containers) {
        String adapterImplClassValue = container.getContainerConfiguration().getContainerProperties()
                .get(ADAPTER_IMPL_CONFIG_STRING);

        if (isServiceLoaderClassAssignableFromAdapterImplClass(loader, adapterImplClassValue.trim())) {
            try {
                return addContainer((Container) injector.inject(
                        new ContainerImpl(
                                definition.getContainerName(),
                                (DeployableContainer) loader.onlyOne(DeployableContainer.class),
                                definition)));
            } catch (Exception ex) {
                throw new ContainerCreationException(
                        "Could not create Container " + definition.getContainerName(), ex);
            }
        }
    }
    return null;
}
 
Example #2
Source File: KeycloakContainerEventsController.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Copy keycloak-add-user.json only if it is jboss container (has jbossHome property).
 */
private void copyKeycloakAddUserFile() {
    for (Container c: containerRegistry.get().getContainers()) {
        log.tracef("Copy keycloak-add-user.json for container [%s]", c.getName());
        ContainerDef conf = c.getContainerConfiguration();
        String jbossHome = conf.getContainerProperty("jbossHome");
        if (jbossHome != null && !jbossHome.isEmpty()) {
            File originalUserAddJsonFile = new File("target/test-classes/keycloak-add-user.json");
            File userAddJsonFile = new File(conf.getContainerProperty("jbossHome")
                    + "/standalone/configuration/keycloak-add-user.json");
            try {
                FileUtils.copyFile(originalUserAddJsonFile, userAddJsonFile);
                log.infof("original user file (%s) has been copied to (%s)",
                        originalUserAddJsonFile.getAbsolutePath(), userAddJsonFile.getAbsolutePath());
            } catch (IOException e) {
                log.warnf(e, "Problem: keycloak-add-user.json file not copied to %s.", userAddJsonFile.getAbsolutePath());
            }
        }
    }
}
 
Example #3
Source File: Registry.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Container create(ContainerDef definition, ServiceLoader loader) {
    Validate.notNull(definition, "Definition must be specified");

    try {
        logger.log(Level.FINE, "Registering container: {0}", definition.getContainerName());

        @SuppressWarnings("rawtypes")
        Collection<DeployableContainer> containerAdapters = loader.all(DeployableContainer.class);

        DeployableContainer<?> dcService = null;

        if (containerAdapters.size() == 1) {
            // just one container on cp
            dcService = containerAdapters.iterator().next();
        } else {
            Container domainContainer = domainContainer(loader, definition);
            if (domainContainer != null) {
                return domainContainer;
            }
            if (dcService == null) {
                dcService = getContainerAdapter(getAdapterImplClassValue(definition), containerAdapters);
            }
            if (dcService == null) {
                throw new ConfigurationException("Unable to get container adapter from Arquillian configuration.");
            }
        }

        // before a Container is added to a collection of containers, inject into its injection point
        return addContainer(injector.inject(
                new ContainerImpl(definition.getContainerName(), dcService, definition)));

    } catch (ConfigurationException e) {
        throw new ContainerCreationException("Could not create Container " + definition.getContainerName(), e);
    }
}
 
Example #4
Source File: LoadBalancerControllerProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Object lookup(ArquillianResource resource, Annotation... qualifiers) {
    String balancerName = null;

    // Check for the presence of possible qualifiers
    for (Annotation a : qualifiers) {
        Class<? extends Annotation> annotationType = a.annotationType();

        if (annotationType.equals(LoadBalancer.class)) {
            balancerName = ((LoadBalancer) a).value();
        }
    }

    ContainerRegistry reg = registry.get();
    Container container = null;
    if (balancerName == null || "".equals(balancerName.trim())) {
        if (reg.getContainers().size() == 1) {
            container = reg.getContainers().get(0);
        } else {
            throw new IllegalArgumentException("Invalid load balancer configuration request - need to specify load balancer name in @LoadBalancerController");
        }
    } else {
        container = reg.getContainer(balancerName);
    }

    if (container == null) {
        throw new IllegalArgumentException("Invalid load balancer configuration - load balancer not found: '" + balancerName + "'");
    }
    if (! (container.getDeployableContainer() instanceof LoadBalancerController)) {
        throw new IllegalArgumentException("Invalid load balancer configuration - container " + container.getName() + " is not a load balancer");
    }

    return container.getDeployableContainer();
}
 
Example #5
Source File: Registry.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Container findMatchingContainer(String name) {
    for (Container container : containers) {
        if (container.getName().equals(name)) {
            return container;
        }
    }
    return null;
}
 
Example #6
Source File: Registry.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Container findDefaultContainer() {
    if (containers.size() == 1) {
        return containers.get(0);
    }
    for (Container container : containers) {
        if (container.getContainerConfiguration().isDefault()) {
            return container;
        }
    }
    return null;
}
 
Example #7
Source File: Registry.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Container getContainer(TargetDescription target) {
    Validate.notNull(target, "Target must be specified");
    if (TargetDescription.DEFAULT.equals(target)) {
        return findDefaultContainer();
    }
    return findMatchingContainer(target.getName());
}
 
Example #8
Source File: KeycloakContainerDeployController.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void forEachDeployment(List<Deployment> deployments, ContainerDeployController.Operation<Container, Deployment> operation)
    throws Exception {
    injector.get().inject(operation);
    ContainerRegistry containerRegistry = this.containerRegistry.get();
    if (containerRegistry == null) {
        return;
    }
    for (Deployment deployment : deployments) {
        Container container = containerRegistry.getContainer(deployment.getDescription().getTarget());
        operation.perform(container, deployment);
    }
}
 
Example #9
Source File: KeycloakContainerDeployController.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void forEachManagedDeployment(ContainerDeployController.Operation<Container, Deployment> operation) throws Exception {
    DeploymentScenario scenario = this.deploymentScenario.get();
    if (scenario == null) {
        return;
    }
    forEachDeployment(scenario.managedDeploymentsInDeployOrder(), operation);
}
 
Example #10
Source File: KeycloakContainerDeployController.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void deployManaged(DeployManagedDeployments event) throws Exception {
    forEachManagedDeployment(new ContainerDeployController.Operation<Container, Deployment>() {
        @Inject
        private Event<DeploymentEvent> event;

        @Override
        public void perform(Container container, Deployment deployment) throws Exception {
            if (runOnServerDeploymentOnRemote(deployment)) return;
            if (container.getState().equals(Container.State.STARTED)) {
                event.fire(new DeployDeployment(container, deployment));
            }
        }
    });
}
 
Example #11
Source File: KeycloakContainerEventsController.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove keycloak-add-user.json file from server config if exists.
 * It should be removed by previous successful start of the server.
 * This method is there just to make sure it is removed.
 */
private void removeKeycloakAddUserFile() {
    for (Container c: containerRegistry.get().getContainers()) {
        ContainerDef conf = c.getContainerConfiguration();
        String jbossHome = conf.getContainerProperty("jbossHome");
        if (jbossHome != null && !jbossHome.isEmpty()) {
            File adminUserJsonFile = new File(jbossHome
                    + "/standalone/configuration/keycloak-add-user.json");
            if (log.isTraceEnabled()) {
                log.tracef("File %s exists=%s", adminUserJsonFile.getAbsolutePath(), adminUserJsonFile.exists());
            }
            adminUserJsonFile.delete();
        }
    }
}
 
Example #12
Source File: CacheStatisticsControllerEnricher.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Supplier<MBeanServerConnection> getJmxServerConnection(JmxInfinispanChannelStatistics annotation) throws MalformedURLException {
    final String host;
    final int port;

    if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1) {
        ContainerInfo node = suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex());
        Container container = node.getArquillianContainer();
        if (container.getDeployableContainer() instanceof KeycloakOnUndertow) {
            return () -> ManagementFactory.getPlatformMBeanServer();
        }
        host = "localhost";
        port = container.getContainerConfiguration().getContainerProperties().containsKey("managementPort")
          ? Integer.valueOf(container.getContainerConfiguration().getContainerProperties().get("managementPort"))
          : 9990;
    } else {
        host = annotation.host().isEmpty()
          ? System.getProperty((annotation.hostProperty().isEmpty()
            ? "keycloak.connectionsInfinispan.remoteStoreServer"
            : annotation.hostProperty()))
          : annotation.host();

        port = annotation.managementPort() == -1
          ? Integer.valueOf(System.getProperty((annotation.managementPortProperty().isEmpty()
            ? "cache.server.management.port"
            : annotation.managementPortProperty())))
          : annotation.managementPort();
    }

    JMXServiceURL url = new JMXServiceURL("service:jmx:remote+http://" + host + ":" + port);
    return () -> {
        try {
            return jmxConnectorRegistry.get().getConnection(url).getMBeanServerConnection();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    };
}
 
Example #13
Source File: CacheStatisticsControllerEnricher.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Supplier<MBeanServerConnection> getJmxServerConnection(JmxInfinispanCacheStatistics annotation) throws MalformedURLException {
    final String host;
    final int port;

    if (annotation.dc() != DC.UNDEFINED && annotation.dcNodeIndex() != -1) {
        ContainerInfo node = suiteContext.get().getAuthServerBackendsInfo(annotation.dc().getDcIndex()).get(annotation.dcNodeIndex());
        Container container = node.getArquillianContainer();
        if (container.getDeployableContainer() instanceof KeycloakOnUndertow) {
            return () -> ManagementFactory.getPlatformMBeanServer();
        }
        host = "localhost";
        port = container.getContainerConfiguration().getContainerProperties().containsKey("managementPort")
          ? Integer.valueOf(container.getContainerConfiguration().getContainerProperties().get("managementPort"))
          : 9990;
    } else {
        host = annotation.host().isEmpty()
          ? System.getProperty((annotation.hostProperty().isEmpty()
            ? "keycloak.connectionsInfinispan.remoteStoreServer"
            : annotation.hostProperty()))
          : annotation.host();

        port = annotation.managementPort() == -1
          ? Integer.valueOf(System.getProperty((annotation.managementPortProperty().isEmpty()
            ? "cache.server.management.port"
            : annotation.managementPortProperty())))
          : annotation.managementPort();
    }


    JMXServiceURL url = new JMXServiceURL("service:jmx:remote+http://" + host + ":" + port);
    return () -> {
        try {
            return jmxConnectorRegistry.get().getConnection(url).getMBeanServerConnection();
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    };
}
 
Example #14
Source File: ArquillianSuiteExtension.java    From appengine-tck with Apache License 2.0 5 votes vote down vote up
private Container findContainer(ContainerRegistry registry, DeployableContainer<?> deployable) {
    for (Container container : registry.getContainers()) {
        if (container.getDeployableContainer() == deployable) {
            return container;
        }
    }
    return null;
}
 
Example #15
Source File: SwarmURLResourceProvider.java    From thorntail with Apache License 2.0 4 votes vote down vote up
@Override
public Object doLookup(ArquillianResource resource, Annotation... __) {

    Container container = containerInstance.get();
    String javaVmArguments = null;
    String portDefinedInProperties = null;
    String offsetDefinedInProperties = null;
    if (container != null) {
        javaVmArguments = container.getContainerConfiguration().getContainerProperties().get("javaVmArguments");
    }
    if (javaVmArguments != null) {
        if (javaVmArguments.contains(SwarmProperties.HTTP_PORT) || javaVmArguments.contains(SwarmProperties.PORT_OFFSET)) {
            String[] properties = javaVmArguments.split("=| |\n");

            for (int i = 0; i < properties.length; i++) {
                if (properties[i].contains(SwarmProperties.HTTP_PORT)) {
                    portDefinedInProperties = properties[i + 1];
                }
                if (properties[i].contains(SwarmProperties.PORT_OFFSET)) {
                    offsetDefinedInProperties = properties[i + 1];
                }
            }
        }
    }
    // first cut - try to get the data from the sysprops
    // this will fail if the user sets any of these via code
    String host = System.getProperty(SwarmProperties.BIND_ADDRESS);
    if (host == null || host.equals("0.0.0.0")) {
        host = "localhost";
    }

    int port = 8080;

    final String portString = portDefinedInProperties != null ? portDefinedInProperties : System.getProperty(SwarmProperties.HTTP_PORT);
    final String portOffset = offsetDefinedInProperties != null ? offsetDefinedInProperties : System.getProperty(SwarmProperties.PORT_OFFSET);
    if (portString != null) {
        port = Integer.parseInt(portString);
    }
    if (portOffset != null) {
        port = port + Integer.parseInt(portOffset);
    }

    String contextPath = System.getProperty(SwarmProperties.CONTEXT_PATH);
    DeploymentContext deploymentContext = this.deploymentContext.get();
    if (deploymentContext != null && deploymentContext.isActive()) {
        if (deploymentContext.getObjectStore().get(ContextRoot.class) != null) {
            contextPath = deploymentContext.getObjectStore().get(ContextRoot.class).context();
        }
    }

    if (contextPath == null) {
        contextPath = "/";
    }

    if (!contextPath.startsWith("/")) {
        contextPath = "/" + contextPath;
    }

    try {
        return new URI("http", null, host, port, contextPath, null, null).toURL();
    } catch (MalformedURLException | URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: Registry.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public List<Container> getContainers() {
    return Collections.unmodifiableList(new ArrayList<>(containers));
}
 
Example #17
Source File: Registry.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Container addContainer(Container container) {
    containers.add(container);
    return container;
}
 
Example #18
Source File: MicroProfileJWTTCKArchiveProcessor.java    From tomee with Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Archive<?> applicationArchive, final TestClass testClass) {
    if (!(applicationArchive instanceof WebArchive)) {
        return;
    }
    final WebArchive war = WebArchive.class.cast(applicationArchive);

    // Add Required Libraries
    war.addAsLibrary(JarLocation.jarLocation(TokenUtils.class))
       .addAsLibrary(JarLocation.jarLocation(JWSSigner.class))
       .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");

    // Provide keys required for tests (vendor specific way)
    war.addClass(JWTAuthContextInfoProvider.class);

    // Spec says that vendor specific ways to load the keys take precedence, so we need to remove it in test
    // cases that use the Config approach.
    Stream.of(
            PublicKeyAsPEMTest.class,
            PublicKeyAsPEMLocationTest.class,
            PublicKeyAsFileLocationURLTest.class,
            PublicKeyAsJWKTest.class,
            PublicKeyAsBase64JWKTest.class,
            PublicKeyAsJWKLocationTest.class,
            PublicKeyAsJWKLocationURLTest.class,
            PublicKeyAsJWKSTest.class,
            PublicKeyAsJWKSLocationTest.class,
            IssValidationTest.class,
            ExpClaimValidationTest.class,
            ExpClaimAllowMissingExpValidationTest.class,
            org.apache.tomee.microprofile.tck.jwt.config.PublicKeyAsPEMLocationTest.class,
            org.apache.tomee.microprofile.tck.jwt.config.PublicKeyAsJWKLocationURLTest.class)
          .filter(c -> c.equals(testClass.getJavaClass()))
          .findAny()
          .ifPresent(c -> war.deleteClass(JWTAuthContextInfoProvider.class));

    // MP Config in wrong place - See https://github.com/eclipse/microprofile/issues/46.
    final Map<ArchivePath, Node> content = war.getContent(object -> object.get().matches(".*META-INF/.*"));
    content.forEach((archivePath, node) -> war.addAsResource(node.getAsset(), node.getPath()));

    // Rewrite the correct server port in configuration
    final Container container = containerRegistry.get().getContainer(TargetDescription.DEFAULT);
    if (container.getDeployableContainer() instanceof RemoteTomEEContainer) {
        final RemoteTomEEContainer remoteTomEEContainer =
                (RemoteTomEEContainer) container.getDeployableContainer();
        final RemoteTomEEConfiguration configuration = remoteTomEEContainer.getConfiguration();
        final String httpPort = configuration.getHttpPort() + "";

        final Map<ArchivePath, Node> microprofileProperties = war.getContent(
                object -> object.get().matches(".*META-INF/microprofile-config\\.properties"));
        microprofileProperties.forEach((archivePath, node) -> {
            try {
                final Properties properties = new Properties();
                properties.load(node.getAsset().openStream());
                properties.replaceAll((key, value) -> ((String) value).replaceAll("8080", httpPort + "/" + "KeyEndpoint.war".replaceAll("\\.war", "")));
                final StringWriter stringWriter = new StringWriter();
                properties.store(stringWriter, null);
                war.delete(archivePath);
                war.add(new StringAsset(stringWriter.toString()), node.getPath());
            } catch (final IOException e) {
                e.printStackTrace();
            }
        });
    }

    System.out.println(war.toString(true));
}
 
Example #19
Source File: Registry.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Container getContainer(String name) {
    return findMatchingContainer(name);
}
 
Example #20
Source File: ContainerInfo.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public ContainerInfo(Container arquillianContainer) {
    if (arquillianContainer == null) {
        throw new IllegalArgumentException();
    }
    this.arquillianContainer = arquillianContainer;
}
 
Example #21
Source File: ContainerInfo.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Container getArquillianContainer() {
    return arquillianContainer;
}
 
Example #22
Source File: ReporterLifecycleObserver.java    From arquillian-recorder with Apache License 2.0 3 votes vote down vote up
public void observeBeforeStart(@Observes Container event) {
    ContainerReport containerReport = new ContainerReport();

    containerReport.setQualifier(event.getName());
    containerReport.setConfiguration(event.getContainerConfiguration().getContainerProperties());

    reporter.get().getLastTestSuiteReport().getContainerReports().add(containerReport);
    reporter.get().setContainerReport(containerReport);

}