private static Collection<String> collectProfilesIds(List<Profile> profiles) {
   Collection<String> result = new THashSet<String>();
   for (Profile each : profiles) {
     if (each.getId() != null) {
       result.add(each.getId());
     }
   }
   return result;
 }
Esempio n. 2
0
  @Test
  public void testSetupCommand() throws Exception {
    Project project = initializeJavaProject();
    getShell().execute("jacoco setup");
    MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
    Model pom = facet.getPOM();
    Profile jacocoProfile = pom.getProfiles().get(0);
    assertEquals("jacoco", jacocoProfile.getId());

    Plugin jacocoPlugin = jacocoProfile.getBuild().getPlugins().get(0);
    assertEquals("jacoco-maven-plugin", jacocoPlugin.getArtifactId());

    PluginExecution exec = jacocoPlugin.getExecutions().get(0);
    assertEquals("prepare-agent", exec.getGoals().get(0));
  }
  private void loadProfile() {

    if (null == profile) {

      @SuppressWarnings("unchecked")
      final List<Profile> profiles = project.getActiveProfiles();

      for (String entry : ENVIRONMENTS) {
        for (Profile p : profiles) {
          if (null != p && null != p.getId() && p.getId().equals(entry)) {
            profile = p.getId();
            return;
          }
        }
      }
    }
  }
  /** For each project in the current build set, reset the version if using project.version */
  @Override
  public Set<Project> applyChanges(final List<Project> projects, final ManipulationSession session)
      throws ManipulationException {
    final ProjectVersionEnforcingState state = session.getState(ProjectVersionEnforcingState.class);
    if (!session.isEnabled()
        || !session.anyStateEnabled(State.activeByDefault)
        || state == null
        || !state.isEnabled()) {
      logger.debug("Project version enforcement is disabled.");
      return Collections.emptySet();
    }

    final Set<Project> changed = new HashSet<Project>();

    for (final Project project : projects) {
      final Model model = project.getModel();

      if (model.getPackaging().equals("pom")) {
        enforceProjectVersion(project, model.getDependencies(), changed);

        if (model.getDependencyManagement() != null) {
          enforceProjectVersion(
              project, model.getDependencyManagement().getDependencies(), changed);
        }

        final List<Profile> profiles = model.getProfiles();
        if (profiles != null) {
          for (final Profile profile : model.getProfiles()) {
            enforceProjectVersion(project, profile.getDependencies(), changed);
            if (profile.getDependencyManagement() != null) {
              enforceProjectVersion(
                  project, profile.getDependencyManagement().getDependencies(), changed);
            }
          }
        }
      }
    }
    if (changed.size() > 0) {
      logger.warn(
          "Using ${project.version} in pom files may lead to unexpected errors with inheritance.");
    }
    return changed;
  }
  @Override
  public boolean install() {
    if (super.install()) {
      // Set main profile to be active by default
      final MavenFacet coreFacet = getProject().getFacet(MavenFacet.class);
      final Model pom = coreFacet.getModel();
      Profile profile = MavenModelUtil.getProfileById(MAIN_PROFILE, pom.getProfiles());
      if (profile == null) {
        profile = new Profile();
        profile.setId(MAIN_PROFILE);
        pom.addProfile(profile);
      }
      if (profile.getActivation() == null) profile.setActivation(new Activation());
      profile.getActivation().setActiveByDefault(true);
      coreFacet.setModel(pom);

      return true;
    } else {
      return false;
    }
  }
Esempio n. 6
0
  @Test
  public void installContainerWithDownload() throws Exception {
    Project project = initializeJavaProject();

    MavenCoreFacet coreFacet = project.getFacet(MavenCoreFacet.class);

    List<Profile> profiles = coreFacet.getPOM().getProfiles();
    for (Profile profile : profiles) {
      System.out.println(profile.getId());
    }
    assertThat(profiles.size(), is(0));

    queueInputLines("JBOSS_AS_MANAGED_4.2.X", "", "19", "10", "", "", "", "", "y", "");
    getShell().execute("arquillian setup");

    assertThat(coreFacet.getPOM().getProfiles().size(), is(1));
    Profile profile = coreFacet.getPOM().getProfiles().get(0);

    assertThat(
        profile.getDependencies(),
        hasItems(
            new DependencyMatcher("arquillian-jbossas-managed-4.2"),
            new DependencyMatcher("jboss-server-manager"),
            new DependencyMatcher("dom4j"),
            new DependencyMatcher("jbossall-client")));

    assertThat(profile.getBuild().getPlugins().size(), is(1));
    assertThat(
        profile.getBuild().getPlugins().get(0).getArtifactId(), is("maven-dependency-plugin"));
  }
  @Override
  public List<Profile> getActiveProfiles(
      Collection<Profile> profiles,
      ProfileActivationContext context,
      ModelProblemCollector problems) {

    List<Profile> activeProfiles = new ArrayList<Profile>();

    for (Profile p : profiles) {
      String id = p.getId();
      if (p.getId() != null
          && context.getActiveProfileIds().contains(id)
          && !context.getInactiveProfileIds().contains(id)) {
        activeProfiles.add(p);
      }
      if (p.getActivation() != null
          && p.getActivation().isActiveByDefault()
          && !context.getInactiveProfileIds().contains(p.getId())) {
        activeProfiles.add(p);
        break;
      }
      for (ProfileActivator activator : activators) {
        if (activator.isActive(p, context, problems)) {
          activeProfiles.add(p);
          break;
        }
      }
    }

    return activeProfiles;
  }
Esempio n. 8
0
  private void installContainer(String container, List<DependencyMatcher> dependencies)
      throws Exception {
    Project project = initializeJavaProject();

    MavenCoreFacet coreFacet = project.getFacet(MavenCoreFacet.class);

    List<Profile> profiles = coreFacet.getPOM().getProfiles();
    for (Profile profile : profiles) {
      System.out.println(profile.getId());
    }
    assertThat(profiles.size(), is(0));

    queueInputLines(
        container, "19", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "",
        "");
    getShell().execute("arquillian setup");

    assertThat(coreFacet.getPOM().getProfiles().size(), is(1));
    Profile profile = coreFacet.getPOM().getProfiles().get(0);

    for (DependencyMatcher dependency : dependencies) {
      assertThat(profile.getDependencies(), hasItem(dependency));
    }
  }
Esempio n. 9
0
  @Test
  public void configureContainer() throws Exception {
    Project project = initializeJavaProject();

    MavenCoreFacet coreFacet = project.getFacet(MavenCoreFacet.class);

    List<Profile> profiles = coreFacet.getPOM().getProfiles();
    for (Profile profile : profiles) {
      System.out.println(profile.getId());
    }
    assertThat(profiles.size(), is(0));

    queueInputLines("JBOSS_AS_MANAGED_6.X", "", "19", "10", "", "", "", "8", "");
    getShell().execute("arquillian setup");

    queueInputLines("JBOSS_AS_MANAGED_6.X", "2", "8000");
    getShell().execute("arquillian configure-container");

    ResourceFacet facet = project.getFacet(ResourceFacet.class);
    FileResource<?> arquillianXML = facet.getTestResource("arquillian.xml");

    assertThat(arquillianXML, is(notNullValue()));
    assertThat(arquillianXML.exists(), is(true));
  }
 /**
  * Adds information about defined profile.
  *
  * @param pomDescriptor The descriptor for the current POM.
  * @param model The Maven Model.
  * @param scannerContext The scanner context.
  */
 private void addProfiles(
     MavenPomDescriptor pomDescriptor, Model model, ScannerContext scannerContext) {
   List<Profile> profiles = model.getProfiles();
   Store store = scannerContext.getStore();
   for (Profile profile : profiles) {
     MavenProfileDescriptor mavenProfileDescriptor = store.create(MavenProfileDescriptor.class);
     pomDescriptor.getProfiles().add(mavenProfileDescriptor);
     mavenProfileDescriptor.setId(profile.getId());
     addProperties(mavenProfileDescriptor, profile.getProperties(), store);
     addModules(mavenProfileDescriptor, profile.getModules(), store);
     addPlugins(mavenProfileDescriptor, profile.getBuild(), scannerContext);
     addManagedPlugins(mavenProfileDescriptor, profile.getBuild(), scannerContext);
     addManagedDependencies(
         mavenProfileDescriptor,
         profile.getDependencyManagement(),
         scannerContext,
         ProfileManagesDependencyDescriptor.class);
     addProfileDependencies(mavenProfileDescriptor, profile.getDependencies(), scannerContext);
     addActivation(mavenProfileDescriptor, profile.getActivation(), store);
   }
 }
  public static ProfileApplicationResult applyProfiles(
      MavenModel model,
      File basedir,
      Collection<String> explicitProfiles,
      Collection<String> alwaysOnProfiles)
      throws RemoteException {
    Model nativeModel = MavenModelConverter.toNativeModel(model);

    List<Profile> activatedPom = new ArrayList<Profile>();
    List<Profile> activatedExternal = new ArrayList<Profile>();
    List<Profile> activeByDefault = new ArrayList<Profile>();

    List<Profile> rawProfiles = nativeModel.getProfiles();
    List<Profile> expandedProfilesCache = null;

    for (int i = 0; i < rawProfiles.size(); i++) {
      Profile eachRawProfile = rawProfiles.get(i);

      boolean shouldAdd =
          explicitProfiles.contains(eachRawProfile.getId())
              || alwaysOnProfiles.contains(eachRawProfile.getId());

      Activation activation = eachRawProfile.getActivation();
      if (activation != null) {
        if (activation.isActiveByDefault()) {
          activeByDefault.add(eachRawProfile);
        }

        // expand only if necessary
        if (expandedProfilesCache == null)
          expandedProfilesCache = doInterpolate(nativeModel, basedir).getProfiles();
        Profile eachExpandedProfile = expandedProfilesCache.get(i);

        for (ProfileActivator eachActivator : getProfileActivators(basedir)) {
          try {
            if (eachActivator.canDetermineActivation(eachExpandedProfile)
                && eachActivator.isActive(eachExpandedProfile)) {
              shouldAdd = true;
              break;
            }
          } catch (ProfileActivationException e) {
            Maven3ServerGlobals.getLogger().warn(e);
          }
        }
      }

      if (shouldAdd) {
        if (MavenConstants.PROFILE_FROM_POM.equals(eachRawProfile.getSource())) {
          activatedPom.add(eachRawProfile);
        } else {
          activatedExternal.add(eachRawProfile);
        }
      }
    }

    List<Profile> activatedProfiles =
        new ArrayList<Profile>(activatedPom.isEmpty() ? activeByDefault : activatedPom);
    activatedProfiles.addAll(activatedExternal);

    for (Profile each : activatedProfiles) {
      new DefaultProfileInjector().injectProfile(nativeModel, each, null, null);
    }

    return new ProfileApplicationResult(
        MavenModelConverter.convertModel(nativeModel, null), collectProfilesIds(activatedProfiles));
  }
  @Override
  public <T> List<T> getData(String key, Class<T> type, Object... params) {
    List<T> retval = null;

    if ("profileIds".equals(key)) {
      final List<T> profileIds = new ArrayList<T>();

      try {
        final List<Profile> profiles = MavenPlugin.getMaven().getSettings().getProfiles();

        for (final Profile profile : profiles) {
          if (profile.getActivation() != null) {
            if (profile.getActivation().isActiveByDefault()) {
              continue;
            }
          }

          profileIds.add(type.cast(profile.getId()));
        }

        if (params[0] != null && params[0] instanceof File) {
          final File locationDir = (File) params[0];

          File pomFile = new File(locationDir, IMavenConstants.POM_FILE_NAME);

          if (!pomFile.exists() && locationDir.getParentFile().exists()) {
            // try one level up for when user is adding new module
            pomFile = new File(locationDir.getParentFile(), IMavenConstants.POM_FILE_NAME);
          }

          if (pomFile.exists()) {
            final IMaven maven = MavenPlugin.getMaven();

            Model model = maven.readModel(pomFile);

            File parentDir = pomFile.getParentFile();

            while (model != null) {
              for (org.apache.maven.model.Profile p : model.getProfiles()) {
                profileIds.add(type.cast(p.getId()));
              }

              parentDir = parentDir.getParentFile();

              if (parentDir != null && parentDir.exists()) {
                try {
                  model = maven.readModel(new File(parentDir, IMavenConstants.POM_FILE_NAME));
                } catch (Exception e) {
                  model = null;
                }
              }
            }
          }
        }
      } catch (CoreException e) {
        LiferayMavenCore.logError(e);
      }

      retval = profileIds;
    } else if ("liferayVersions".equals(key)) {
      final List<T> possibleVersions = new ArrayList<T>();

      final RepositorySystem system = AetherUtil.newRepositorySystem();

      final RepositorySystemSession session = AetherUtil.newRepositorySystemSession(system);

      final String groupId = params[0].toString();
      final String artifactId = params[1].toString();

      final String coords = groupId + ":" + artifactId + ":[6,)";

      final Artifact artifact = new DefaultArtifact(coords);

      final VersionRangeRequest rangeRequest = new VersionRangeRequest();
      rangeRequest.setArtifact(artifact);
      rangeRequest.addRepository(AetherUtil.newCentralRepository());
      rangeRequest.addRepository(AetherUtil.newLiferayRepository());

      try {
        final VersionRangeResult rangeResult = system.resolveVersionRange(session, rangeRequest);

        final List<Version> versions = rangeResult.getVersions();

        for (Version version : versions) {
          final String val = version.toString();

          if (!"6.2.0".equals(val)) {
            possibleVersions.add(type.cast(val));
          }
        }

        retval = possibleVersions;
      } catch (VersionRangeResolutionException e) {
      }
    } else if ("parentVersion".equals(key)) {
      final List<T> version = new ArrayList<T>();

      final File locationDir = (File) params[0];

      final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME);

      if (parentPom.exists()) {
        try {
          final IMaven maven = MavenPlugin.getMaven();

          final Model model = maven.readModel(parentPom);

          version.add(type.cast(model.getVersion()));

          retval = version;
        } catch (CoreException e) {
          LiferayMavenCore.logError("unable to get parent version", e);
        }
      }
    } else if ("parentGroupId".equals(key)) {
      final List<T> groupId = new ArrayList<T>();

      final File locationDir = (File) params[0];

      final File parentPom = new File(locationDir, IMavenConstants.POM_FILE_NAME);

      if (parentPom.exists()) {
        try {
          final IMaven maven = MavenPlugin.getMaven();

          final Model model = maven.readModel(parentPom);

          groupId.add(type.cast(model.getGroupId()));

          retval = groupId;
        } catch (CoreException e) {
          LiferayMavenCore.logError("unable to get parent groupId", e);
        }
      }
    }

    return retval;
  }
Esempio n. 13
0
  protected void generateAggregatedZip(
      MavenProject rootProject,
      List<MavenProject> reactorProjects,
      Set<MavenProject> pomZipProjects)
      throws IOException, MojoExecutionException {
    File projectBaseDir = rootProject.getBasedir();
    String rootProjectGroupId = rootProject.getGroupId();
    String rootProjectArtifactId = rootProject.getArtifactId();
    String rootProjectVersion = rootProject.getVersion();

    String aggregatedZipFileName =
        "target/" + rootProjectArtifactId + "-" + rootProjectVersion + "-app.zip";
    File projectOutputFile = new File(projectBaseDir, aggregatedZipFileName);
    getLog()
        .info(
            "Generating "
                + projectOutputFile.getAbsolutePath()
                + " from root project "
                + rootProjectArtifactId);
    File projectBuildDir = new File(projectBaseDir, reactorProjectOutputPath);

    if (projectOutputFile.exists()) {
      projectOutputFile.delete();
    }
    createAggregatedZip(
        projectBaseDir,
        projectBuildDir,
        reactorProjectOutputPath,
        projectOutputFile,
        includeReadMe,
        pomZipProjects);
    if (rootProject.getAttachedArtifacts() != null) {
      // need to remove existing as otherwise we get a WARN
      Artifact found = null;
      for (Artifact artifact : rootProject.getAttachedArtifacts()) {
        if (artifactClassifier != null
            && artifact.hasClassifier()
            && artifact.getClassifier().equals(artifactClassifier)) {
          found = artifact;
          break;
        }
      }
      if (found != null) {
        rootProject.getAttachedArtifacts().remove(found);
      }
    }

    getLog()
        .info(
            "Attaching aggregated zip "
                + projectOutputFile
                + " to root project "
                + rootProject.getArtifactId());
    projectHelper.attachArtifact(rootProject, artifactType, artifactClassifier, projectOutputFile);

    // if we are doing an install goal, then also install the aggregated zip manually
    // as maven will install the root project first, and then build the reactor projects, and at
    // this point
    // it does not help to attach artifact to root project, as those artifacts will not be installed
    // so we need to install manually
    List<String> activeProfileIds = new ArrayList<>();
    List<Profile> activeProfiles = rootProject.getActiveProfiles();
    if (activeProfiles != null) {
      for (Profile profile : activeProfiles) {
        String id = profile.getId();
        if (Strings.isNotBlank(id)) {
          activeProfileIds.add(id);
        }
      }
    }
    if (rootProject.hasLifecyclePhase("install")) {
      getLog().info("Installing aggregated zip " + projectOutputFile);
      InvocationRequest request = new DefaultInvocationRequest();
      request.setBaseDirectory(rootProject.getBasedir());
      request.setPomFile(new File("./pom.xml"));
      request.setGoals(Collections.singletonList("install:install-file"));
      request.setRecursive(false);
      request.setInteractive(false);
      request.setProfiles(activeProfileIds);

      Properties props = new Properties();
      props.setProperty("file", aggregatedZipFileName);
      props.setProperty("groupId", rootProjectGroupId);
      props.setProperty("artifactId", rootProjectArtifactId);
      props.setProperty("version", rootProjectVersion);
      props.setProperty("classifier", "app");
      props.setProperty("packaging", "zip");
      props.setProperty("generatePom", "false");
      request.setProperties(props);

      getLog()
          .info(
              "Installing aggregated zip using: mvn install:install-file"
                  + serializeMvnProperties(props));
      Invoker invoker = new DefaultInvoker();
      try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
          throw new IllegalStateException("Error invoking Maven goal install:install-file");
        }
      } catch (MavenInvocationException e) {
        throw new MojoExecutionException("Error invoking Maven goal install:install-file", e);
      }
    }

    if (rootProject.hasLifecyclePhase("deploy")) {

      if (deploymentRepository == null && Strings.isNullOrBlank(altDeploymentRepository)) {
        String msg =
            "Cannot run deploy phase as Maven project has no <distributionManagement> with the maven url to use for deploying the aggregated zip file, neither an altDeploymentRepository property.";
        getLog().warn(msg);
        throw new MojoExecutionException(msg);
      }

      getLog()
          .info(
              "Deploying aggregated zip "
                  + projectOutputFile
                  + " to root project "
                  + rootProject.getArtifactId());
      getLog()
          .info(
              "Using deploy goal: "
                  + deployFileGoal
                  + " with active profiles: "
                  + activeProfileIds);

      InvocationRequest request = new DefaultInvocationRequest();
      request.setBaseDirectory(rootProject.getBasedir());
      request.setPomFile(new File("./pom.xml"));
      request.setGoals(Collections.singletonList(deployFileGoal));
      request.setRecursive(false);
      request.setInteractive(false);
      request.setProfiles(activeProfileIds);
      request.setProperties(getProject().getProperties());

      Properties props = new Properties();
      props.setProperty("file", aggregatedZipFileName);
      props.setProperty("groupId", rootProjectGroupId);
      props.setProperty("artifactId", rootProjectArtifactId);
      props.setProperty("version", rootProjectVersion);
      props.setProperty("classifier", "app");
      props.setProperty("packaging", "zip");
      String deployUrl = null;

      if (!Strings.isNullOrBlank(deployFileUrl)) {
        deployUrl = deployFileUrl;
      } else if (altDeploymentRepository != null && altDeploymentRepository.contains("::")) {
        deployUrl =
            altDeploymentRepository.substring(altDeploymentRepository.lastIndexOf("::") + 2);
      } else {
        deployUrl = deploymentRepository.getUrl();
      }

      props.setProperty("url", deployUrl);
      props.setProperty("repositoryId", deploymentRepository.getId());
      props.setProperty("generatePom", "false");
      request.setProperties(props);

      getLog()
          .info(
              "Deploying aggregated zip using: mvn deploy:deploy-file"
                  + serializeMvnProperties(props));
      Invoker invoker = new DefaultInvoker();
      try {
        InvocationResult result = invoker.execute(request);
        if (result.getExitCode() != 0) {
          throw new IllegalStateException("Error invoking Maven goal deploy:deploy-file");
        }
      } catch (MavenInvocationException e) {
        throw new MojoExecutionException("Error invoking Maven goal deploy:deploy-file", e);
      }
    }
  }