Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2014 Red Hat, Inc. and/or its affiliates.
   *
   * Licensed under the Eclipse Public License version 1.0, available at
   * http://www.eclipse.org/legal/epl-v10.html
   */
  package org.jboss.forge.arquillian.impl;
  
  import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import  org.jboss.arquillian.container.spi.client.deployment.DeploymentDescription;
 import  org.jboss.arquillian.container.spi.client.deployment.TargetDescription;
 import  org.jboss.arquillian.container.spi.client.protocol.ProtocolDescription;
 import  org.jboss.arquillian.container.test.api.Deployment;
 import  org.jboss.arquillian.container.test.api.OverProtocol;
 import  org.jboss.arquillian.container.test.api.ShouldThrowException;
 import  org.jboss.arquillian.container.test.api.TargetsContainer;
 import  org.jboss.arquillian.container.test.spi.client.deployment.DeploymentScenarioGenerator;
 import  org.jboss.arquillian.test.spi.TestClass;
 import  org.jboss.shrinkwrap.api.Archive;
 import  org.jboss.shrinkwrap.api.ShrinkWrap;
 import  org.jboss.shrinkwrap.descriptor.api.Descriptor;

Creates DeploymentDescription instances from annotated test cases - handles AddonDeployments and AddonDependencies.

Author(s):
Lincoln Baxter, III
 
 @SuppressWarnings("deprecation")
 public class FurnaceDeploymentScenarioGenerator implements DeploymentScenarioGenerator
 {
 
    @Override
    public List<DeploymentDescription> generate(TestClass testClass)
    {
       List<DeploymentDescription> deployments = new ArrayList<DeploymentDescription>();
       Method[] deploymentMethods = testClass.getMethods(Deployment.class);
       for (Method deploymentMethod : deploymentMethods)
       {
          validate(deploymentMethod);
          DeploymentDescription primaryDeployment = null;
          try
          {
             primaryDeployment = generateDeployment(deploymentMethod);
 
             if (deploymentMethod.isAnnotationPresent(AddonDeployments.class)
                      || deploymentMethod.isAnnotationPresent(AddonDependencies.class)
                      || deploymentMethod.isAnnotationPresent(Dependencies.class))
             {
                deployments.addAll(generateAnnotatedDeployments(primaryDeploymenttestClass.getJavaClass(),
                         deploymentMethod));
             }
          }
          catch (Exception e)
          {
             throw new RuntimeException("Could not generate @Deployment for " + testClass.getName() + "."
                      + deploymentMethod.getName() + "()"e);
          }
 
         deployments.add(primaryDeployment);
      }
      for (AddonDeploymentScenarioEnhancer enhancer : ServiceLoader.load(AddonDeploymentScenarioEnhancer.class))
      {
         deployments = enhancer.enhance(testClassdeployments);
         Assert.notNull(deployments,
                  String.format("Cannot return a null deployment. Check %s for more details",
                           enhancer.getClass()));
      }
      return deployments;
   }
   private Collection<DeploymentDescription> generateAnnotatedDeployments(DeploymentDescription primaryDeployment,
            Class<?> classUnderTestMethod deploymentMethod)
   {
      Collection<DeploymentDescription> deployments = new ArrayList<DeploymentDescription>();
      Annotation[] annotations = deploymentMethod.getAnnotations();
      for (Annotation annotation : annotations)
      {
         if (annotation instanceof AddonDeployments)
         {
            AddonDeployments addonDeployments = (AddonDeploymentsannotation;
            if (addonDeployments.value() != null)
            {
               for (AddonDeployment addonDeployment : addonDeployments.value())
               {
                  createAnnotatedDeployment(primaryDeployment,
                           classUnderTest,
                           deploymentMethod,
                           deployments,
                           addonDeployment.name(),
                           addonDeployment.version(),
                           AddonDeployment.class.getSimpleName(),
                           addonDeployment.imported(),
                           addonDeployment.exported(),
                           addonDeployment.optional(),
                           addonDeployment.listener(),
                           addonDeployment.timeout(),
                           addonDeployment.timeoutUnit(),
                           addonDeployment.shouldThrowException());
               }
            }
         }
         else if (annotation instanceof AddonDependencies)
         {
            AddonDependencies addonDependencies = (AddonDependenciesannotation;
            if (addonDependencies.value().length > 0)
            {
               for (AddonDependency addonDependency : addonDependencies.value())
               {
                  createAnnotatedDeployment(primaryDeployment,
                           classUnderTest,
                           deploymentMethod,
                           deployments,
                           addonDependency.name(),
                           addonDependency.version(),
                           AddonDependency.class.getSimpleName(),
                           addonDependency.imported(),
                           addonDependency.exported(),
                           addonDependency.optional(),
                           addonDependency.listener(),
                           addonDependency.timeout(),
                           addonDependency.timeoutUnit(),
                           addonDependency.shouldThrowException());
               }
            }
            else if (addonDependencies.automatic())
            {
               addAutomaticDependencies(primaryDeploymentclassUnderTestdeploymentMethoddeployments);
            }
         }
         else if (annotation instanceof Dependencies)
         {
            Dependencies addonDependencies = (Dependenciesannotation;
            if (addonDependencies.value() != null)
            {
               for (AddonDependency addonDependency : addonDependencies.value())
               {
                  createAnnotatedDeployment(primaryDeployment,
                           classUnderTest,
                           deploymentMethod,
                           deployments,
                           addonDependency.name(),
                           addonDependency.version(),
                           AddonDependency.class.getSimpleName(),
                           addonDependency.imported(),
                           addonDependency.exported(),
                           addonDependency.optional(),
                           addonDependency.listener(),
                           addonDependency.timeout(),
                           addonDependency.timeoutUnit(),
                           addonDependency.shouldThrowException());
               }
            }
         }
      }
      return deployments;
   }
   @SuppressWarnings("unchecked")
   private void addAutomaticDependencies(DeploymentDescription primaryDeploymentClass<?> classUnderTest,
            Method deploymentMethodCollection<DeploymentDescription> deployments)
   {
      for (AddonDependencyEntry dependency : getAddonSet(classUnderTest))
      {
         createAnnotatedDeployment(primaryDeployment,
                  classUnderTest,
                  deploymentMethod,
                  deployments,
                  dependency.getName(),
                  dependency.getVersionRange().toString(),
                  AddonDependency.class.getSimpleName(),
                  true,
                  dependency.isExported(),
                  dependency.isOptional(),
                  new Class[0],
                  10000,
                  .,
                  NullException.class);
      }
   }
   private Set<AddonDependencyEntrygetAddonSet(Class<?> classUnderTest)
   {
      if ( == null)
         buildDependencyMaps(classUnderTest);
      return ;
   }
   private void createAnnotatedDeployment(DeploymentDescription primaryDeploymentClass<?> classUnderTest,
            Method deploymentMethodCollection<DeploymentDescription> deploymentsString addonName,
            String addonVersionString annotationSimpleNameboolean importedboolean exportedboolean optional,
            Class<? extends DeploymentListener>[] listenerClassesint timeoutQuantityTimeUnit timeoutUnit,
            Class<? extends ExceptionexpectedException)
   {
      /*
       * Resolve version of annotated deployment (if possible)f
       */
      String version;
      if (addonVersion.isEmpty())
      {
         version = resolveVersionFromPOM(classUnderTestaddonName);
         if (version == null)
         {
            throw new IllegalStateException("Could not resolve the version for [" + addonName
                     + "]. Either specify the version for this @" + annotationSimpleName
                     + " in [" + classUnderTest.getName() + "] or add it to pom.xml located at ["
                     + getPomFileFor(classUnderTest) + "]");
         }
      }
      else
      {
         version = addonVersion;
      }
      AddonId id = AddonId.from(addonNameversion);
      AddonDeploymentArchive archive = ShrinkWrap.create(AddonDeploymentArchive.class).setAddonId(id);
      /*
       * Configure deploymenet timeout
       */
      archive.setDeploymentTimeoutUnit(timeoutUnit);
      archive.setDeploymentTimeoutQuantity(timeoutQuantity);
      /*
       * Configure target repository
       */
      if (Annotations.isAnnotationPresent(deploymentMethodDeployToRepository.class))
      {
         archive.setAddonRepository(Annotations.getAnnotation(deploymentMethodDeployToRepository.class)
                  .value());
      }
      /*
       * Configure automatic dependency registration to parent Archive
       */
      if (imported)
      {
         AddonDependencyEntry dependency = AddonDependencyEntry.create(addonNameaddonVersionexportedoptional);
         ((AddonArchiveBase<?>) primaryDeployment.getArchive()).addAsAddonDependencies(dependency);
      }
      /*
       * Configure deployment listeners
       */
      for (Class<? extends DeploymentListenerlistenerClass : listenerClasses)
      {
         if (DeploymentListener.class.equals(listenerClass))
            continue// do nothing for the default
         try
         {
            archive.addDeploymentListener(listenerClass.newInstance());
         }
         catch (Exception e)
         {
            throw new RuntimeException("Could not instantiate " + DeploymentListener.class.getSimpleName()
                     + " of type " + listenerClass.getName(), e);
         }
      }
      DeploymentDescription deploymentDescription = new DeploymentDescription(id.toCoordinates(), archive);
      /*
       * Don't package supporting test classes in annotation deployments
       */
      deploymentDescription.shouldBeTestable(false);
      /*
       * Configure expected deployment exception
       */
      if (!NullException.class.isAssignableFrom(expectedException))
         deploymentDescription.setExpectedException(expectedException);
      deployments.add(deploymentDescription);
   }
   private void validate(Method deploymentMethod)
   {
      if (!Modifier.isStatic(deploymentMethod.getModifiers()))
      {
         throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName() + " is not static. "
                  + deploymentMethod);
      }
      if (!Archive.class.isAssignableFrom(deploymentMethod.getReturnType())
               && !Descriptor.class.isAssignableFrom(deploymentMethod.getReturnType()))
      {
         throw new IllegalArgumentException(
                  "Method annotated with " + Deployment.class.getName() +
                           " must have return type " + Archive.class.getName() + " or " + Descriptor.class.getName()
                           + ". " + deploymentMethod);
      }
      if (deploymentMethod.getParameterTypes().length != 0)
      {
         throw new IllegalArgumentException("Method annotated with " + Deployment.class.getName()
                  + " can not accept parameters. " + deploymentMethod);
      }
      String name = deploymentMethod.getAnnotation(Deployment.class).name();
      try
      {
         if (!Strings.isNullOrEmpty(name) && !"_DEFAULT_".equals(name))
            AddonId.fromCoordinates(name);
      }
      catch (IllegalArgumentException e)
      {
         throw new IllegalArgumentException("@" + Deployment.class.getName()
                  + " requires name in the format \"name,version\", but was \"" + name + "\". ");
      }
   }
   private DeploymentDescription generateDeployment(Method deploymentMethod)
   {
      TargetDescription target = generateTarget(deploymentMethod);
      ProtocolDescription protocol = generateProtocol(deploymentMethod);
      Deployment deploymentAnnotation = deploymentMethod.getAnnotation(Deployment.class);
      DeploymentDescription description = null;
      if (Archive.class.isAssignableFrom(deploymentMethod.getReturnType()))
      {
         Archive<?> archive = invoke(Archive.classdeploymentMethod);
         if (archive instanceof RepositoryLocationAware)
         {
            if (Annotations.isAnnotationPresent(deploymentMethodDeployToRepository.class))
               ((RepositoryLocationAware<?>) archive).setAddonRepository(Annotations.getAnnotation(deploymentMethod,
                        DeployToRepository.class).value());
         }
         description = new DeploymentDescription(deploymentAnnotation.name(), archive);
         description.shouldBeTestable(deploymentAnnotation.testable());
      }
      else if (Descriptor.class.isAssignableFrom(deploymentMethod.getReturnType()))
      {
         description = new DeploymentDescription(deploymentAnnotation.name(),
                  invoke(Descriptor.classdeploymentMethod));
      }
      description.shouldBeManaged(deploymentAnnotation.managed());
      description.setOrder(deploymentAnnotation.order());
      if (target != null)
      {
         description.setTarget(target);
      }
      if (protocol != null)
      {
         description.setProtocol(protocol);
      }
      if (deploymentMethod.isAnnotationPresent(ShouldThrowException.class))
      {
         description.setExpectedException(deploymentMethod.getAnnotation(ShouldThrowException.class).value());
      }
      return description;
   }
   private TargetDescription generateTarget(Method deploymentMethod)
   {
      if (deploymentMethod.isAnnotationPresent(TargetsContainer.class))
      {
         return new TargetDescription(deploymentMethod.getAnnotation(TargetsContainer.class).value());
      }
      return TargetDescription.DEFAULT;
   }
   private ProtocolDescription generateProtocol(Method deploymentMethod)
   {
      if (deploymentMethod.isAnnotationPresent(OverProtocol.class))
      {
         return new ProtocolDescription(deploymentMethod.getAnnotation(OverProtocol.class).value());
      }
      return new FurnaceProtocolDescription();
   }
   private <T> T invoke(Class<T> typeMethod deploymentMethod)
   {
      try
      {
         return type.cast(deploymentMethod.invoke(null));
      }
      catch (Exception e)
      {
         throw new RuntimeException("Could not invoke deployment method: " + deploymentMethode);
      }
   }

   
Read the pom.xml of the project containing the class under test
   private String resolveVersionFromPOM(Class<?> classUnderTestString name)
   {
      if ( == null)
      {
         buildDependencyMaps(classUnderTest);
      }
      return .get(name);
   }
   private void buildDependencyMaps(Class<?> classUnderTest)
   {
      ProjectHelper projectHelper = new ProjectHelper();
       = new LinkedHashSet<>();
       = new HashMap<StringString>();
      File pomFile = getPomFileFor(classUnderTest);
      try
      {
         // Needed for single-project addons
         Model model = projectHelper.loadPomFromFile(pomFile);
         String thisAddonName = (model.getGroupId() == null) ? model.getParent().getGroupId() : model.getGroupId()
                  + ":" + model.getArtifactId();
         String thisVersion = model.getVersion();
         if (projectHelper.isAddon(model))
         {
            .add(AddonDependencyEntry.create(thisAddonNamethisVersiontruefalse));
         }
         .put(thisAddonNamethisVersion);
         Map<AddonDependencyEntryStringcontainerScope = new HashMap<>();
         List<Dependencydependencies = projectHelper.resolveDependenciesFromPOM(pomFile);
         for (Dependency dependency : dependencies)
         {
            Artifact artifact = dependency.getArtifact();
            String addonName = artifact.getGroupId() + ":" + artifact.getArtifactId();
            String version = artifact.getBaseVersion();
            String scope = dependency.getScope();
            boolean optional = dependency.isOptional();
            .put(addonNameversion);
            {
               AddonDependencyEntry entry = AddonDependencyEntry.create(addonNameversion,
                        MavenAddonDependencyResolver.isExported(scope), optional);
               if (MavenAddonDependencyResolver.isFurnaceContainer(artifact))
               {
                  containerScope.put(entryscope);
               }
               .add(entry);
            }
         }
         // If there are more than one container set and at least one container set in test scope
         if (containerScope.size() > 1 && containerScope.containsValue(.))
         {
            // Remove non-test scoped containers
            for (Entry<AddonDependencyEntryStringentry : containerScope.entrySet())
            {
               if (!..equals(entry.getValue()))
               {
                  .remove(entry.getKey());
               }
            }
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }
   private File getPomFileFor(Class<?> classUnderTest)
   {
      URL resource = classUnderTest.getClassLoader().getResource("");
      if (resource == null)
      {
         throw new IllegalStateException("Could not find the pom.xml for class " + classUnderTest.getName());
      }
      String directory = resource.getFile();
      File pomFile = findBuildDescriptor(directory);
      return pomFile;
   }
   private File findBuildDescriptor(String classLocation)
   {
      File pom = null;
      File dir = new File(classLocation);
      while (dir != null)
      {
         File testPom = new File(dir"pom.xml");
         if (testPom.isFile())
         {
            pom = testPom;
            break;
         }
         dir = dir.getParentFile();
      }
      return pom;
   }
New to GrepCode? Check out our FAQ X