Exemplo n.º 1
1
  /**
   * Tests all options, checks if their default values are correct.
   *
   * @throws Exception
   */
  public void testDefaultConfig() throws Exception {
    ZipalignMojo mojo = createMojo("zipalign-config-project0");
    final ConfigHandler cfh = new ConfigHandler(mojo);
    cfh.parseConfiguration();

    Boolean skip = Whitebox.getInternalState(mojo, "parsedSkip");
    assertTrue("zipalign 'skip' parameter should be true", skip);

    Boolean verbose = Whitebox.getInternalState(mojo, "parsedVerbose");
    assertFalse("zipalign 'verbose' parameter should be false", verbose);

    MavenProject project = Whitebox.getInternalState(mojo, "project");

    String inputApk = Whitebox.getInternalState(mojo, "parsedInputApk");
    File inputApkFile =
        new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".apk");
    assertEquals(
        "zipalign 'inputApk' parameter should be equal", inputApkFile.getAbsolutePath(), inputApk);

    String outputApk = Whitebox.getInternalState(mojo, "parsedOutputApk");
    File outputApkFile =
        new File(
            project.getBuild().getDirectory(), project.getBuild().getFinalName() + "-aligned.apk");
    assertEquals(
        "zipalign 'outputApk' parameter should be equal",
        outputApkFile.getAbsolutePath(),
        outputApk);
  }
    public Object[] getChildren(Object parentElement) {
      if (parentElement instanceof MavenProject) {
        /*
         * Walk the hierarchy list until we find the parentElement and
         * return the previous element, which is the child.
         */
        MavenProject parent = (MavenProject) parentElement;

        if (getProjectHierarchy().size() == 1) {
          // No parent exists, only one element in the tree
          return new Object[0];
        }

        if (getProjectHierarchy().getFirst().equals(parent)) {
          // We are the final child
          return new Object[0];
        }

        ListIterator<MavenProject> iter = getProjectHierarchy().listIterator();
        while (iter.hasNext()) {
          MavenProject next = iter.next();
          if (next.equals(parent)) {
            iter.previous();
            MavenProject previous = iter.previous();
            return new Object[] {previous};
          }
        }
      }
      return new Object[0];
    }
  private void updateArtifactEntry(final BufferedReader reader, final BufferedWriter writer)
      throws IOException {

    // this line remains the same
    writer.write(project.getArtifactId());
    writer.newLine();
    // next line is version, author (or "deployer"), date & time,
    reader.readLine();
    writer.write(
        project.getVersion()
            + " was last deployed by "
            + System.getProperty("user.name")
            + " at "
            + SimpleDateFormat.getDateTimeInstance().format(now));
    writer.newLine();
    // next line is the quote
    for (String line = reader.readLine();
        null != line && 0 < line.length();
        line = reader.readLine()) {}
    ;
    final String quote = project.getProperties().getProperty("version.quote");
    if (null != quote) {
      writer.write(quote);
      writer.newLine();
      writer.newLine();
    }
  }
  void generatePropertiesFile(@NotNull Properties properties, File base, String propertiesFilename)
      throws IOException {
    FileWriter fileWriter = null;
    File gitPropsFile = new File(base, propertiesFilename);
    try {
      Files.createParentDirs(gitPropsFile);

      fileWriter = new FileWriter(gitPropsFile);
      if ("json".equalsIgnoreCase(format)) {
        log(
            "Writing json file to [",
            gitPropsFile.getAbsolutePath(),
            "] (for module ",
            project.getName() + (++counter),
            ")...");
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(fileWriter, properties);
      } else {
        log(
            "Writing properties file to [",
            gitPropsFile.getAbsolutePath(),
            "] (for module ",
            project.getName() + (++counter),
            ")...");
        properties.store(fileWriter, "Generated by Git-Commit-Id-Plugin");
      }

    } catch (IOException ex) {
      throw new RuntimeException("Cannot create custom git properties file: " + gitPropsFile, ex);
    } finally {
      Closeables.closeQuietly(fileWriter);
    }
  }
  String getBundleClasspath() throws MojoExecutionException {
    StringBuffer sb = new StringBuffer();

    File outputDirectory = new File(project.getBuild().getOutputDirectory());
    if (outputDirectory.exists()) {
      if (classifier != null) {
        for (Iterator i = project.getAttachedArtifacts().iterator(); i.hasNext(); ) {
          Artifact a = (Artifact) i.next();
          if (classifier.equals(a.getClassifier())) {
            sb.append(jars + "/" + a.getFile().getName());
          }
        }
      } else if (projectJar != null) {
        sb.append(jars + "/" + projectJar);
      }
    }

    if (bundleClasspath != null) {
      for (int i = 0; i < bundleClasspath.length; i++) {
        if (sb.length() > 0) sb.append(',');
        sb.append(bundleClasspath[i]);
      }
    }
    for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
      Artifact a = (Artifact) i.next();
      if (sb.length() > 0) sb.append(',');
      sb.append(jars + "/" + a.getFile().getName());
    }
    return sb.toString();
  }
 /** Walk project references recursively, adding thrift files to the provided list. */
 List<File> getRecursiveThriftFiles(MavenProject project, String outputDirectory, List<File> files)
     throws IOException {
   HashFunction hashFun = Hashing.md5();
   if (dependencyIncludes.contains(project.getArtifactId())) {
     File dir = new File(new File(project.getFile().getParent(), "target"), outputDirectory);
     if (dir.exists()) {
       URI baseDir = getFileURI(dir);
       for (File f : findThriftFilesInDirectory(dir)) {
         URI fileURI = getFileURI(f);
         String relPath = baseDir.relativize(fileURI).getPath();
         File destFolder = getResourcesOutputDirectory();
         destFolder.mkdirs();
         File destFile = new File(destFolder, relPath);
         if (!destFile.exists()
             || (destFile.isFile()
                 && !Files.hash(f, hashFun).equals(Files.hash(destFile, hashFun)))) {
           getLog()
               .info(
                   format("copying %s to %s", f.getCanonicalPath(), destFile.getCanonicalPath()));
           copyFile(f, destFile);
         }
         files.add(destFile);
       }
     }
   }
   Map<String, MavenProject> refs = project.getProjectReferences();
   for (String name : refs.keySet()) {
     getRecursiveThriftFiles(refs.get(name), outputDirectory, files);
   }
   return files;
 }
 @SuppressWarnings("unchecked")
 private void prepareArtifacts() {
   try {
     // TODO: do only if artifacts are not resolved
     Set<Artifact> artifacts = new LinkedHashSet<Artifact>();
     Map<String, Artifact> managedVersions = createManagedVersionMap();
     List<ResolutionListener> listeners = new ArrayList<ResolutionListener>();
     ArtifactResolutionResult resolveResult =
         artifactCollector.collect(
             getAllArtifacts(),
             project.getArtifact(),
             managedVersions,
             session.getLocalRepository(),
             project.getRemoteArtifactRepositories(),
             artifactMetadataSource,
             null,
             listeners);
     for (ResolutionNode node : (Set<ResolutionNode>) resolveResult.getArtifactResolutionNodes()) {
       if (!isReactorProject(node.getArtifact())) {
         artifactResolver.resolve(
             node.getArtifact(), node.getRemoteRepositories(), session.getLocalRepository());
         artifacts.add(node.getArtifact());
       } else {
         addProjectReferenceArtifact(node.getArtifact());
       }
     }
     this.artifacts = artifacts;
   } catch (Exception e) {
     getLog().debug("[WarSync] " + e.getMessage(), e);
     getLog().error("[WarSync] " + e.getMessage());
   }
 }
 @SuppressWarnings("unchecked")
 @Before
 public void setup() throws ClassNotFoundException, DependencyResolutionRequiredException {
   MockitoAnnotations.initMocks(this);
   when(project.getCompileClasspathElements()).thenReturn(Arrays.asList("foo", "bar"));
   when(project.getName()).thenReturn(PROJECT_NAME);
 }
  public boolean select(Viewer viewer, Object parentElement, Object element) {
    if (element instanceof IFolder) {
      IFolder folder = (IFolder) element;
      IProject project = folder.getProject();
      try {
        if (project.hasNature(IMavenConstants.NATURE_ID)) {
          IMavenProjectRegistry projectManager = MavenPlugin.getMavenProjectRegistry();

          IMavenProjectFacade projectFacade = projectManager.create(project, null);
          if (projectFacade != null) {
            // XXX implement corner cases
            // modules have ".." in the path
            // modules have more then one segment in the path
            // modules not imported in workspace
            MavenProject mavenProject = projectFacade.getMavenProject(null);
            IPath folderPath = folder.getFullPath();

            // workspace-relative path sans project name
            String folderName = folderPath.removeFirstSegments(1).toPortableString();

            if (mavenProject.getModules().contains(folderName)) {
              return false;
            }
          }
        }
      } catch (CoreException ex) {
        log.error(ex.getMessage(), ex);
      }
    }
    return true;
  }
  public TargetPlatform computeTargetPlatform(
      MavenSession session, MavenProject project, List<ReactorProject> reactorProjects) {
    TargetPlatformConfiguration configuration =
        TychoProjectUtils.getTargetPlatformConfiguration(project);

    ExecutionEnvironment ee =
        projectTypes.get(project.getPackaging()).getExecutionEnvironment(project);

    TargetPlatformBuilder tpBuilder =
        resolverFactory.createTargetPlatformBuilder( //
            ee != null ? ee.getProfileName() : null, configuration.isDisableP2Mirrors());
    tpBuilder.setProjectLocation(project.getBasedir());

    addReactorProjectsToTargetPlatform(reactorProjects, tpBuilder);

    if (TargetPlatformConfiguration.POM_DEPENDENCIES_CONSIDER.equals(
        configuration.getPomDependencies())) {
      addPomDependenciesToTargetPlatform(project, tpBuilder, reactorProjects, session);
    }

    for (ArtifactRepository repository : project.getRemoteArtifactRepositories()) {
      addEntireP2RepositoryToTargetPlatform(repository, tpBuilder, session);
    }

    if (configuration.getTarget() != null) {
      addTargetFileContentToTargetPlatform(configuration, tpBuilder, session);
    }

    tpBuilder.addFilters(configuration.getFilters());

    return tpBuilder.buildTargetPlatform();
  }
  /** {@inheritDoc} */
  @Override
  protected void doConfigure(
      final MavenProject mavenProject,
      IProject project,
      ProjectConfigurationRequest request,
      final IProgressMonitor monitor)
      throws CoreException {

    if (configureNature(project, mavenProject, GAE_NATURE_ID, false, monitor)) {

      // Remove DN support if we use GAE
      if (mavenProject.getPlugin("org.datanucleus:maven-datanucleus-plugin") != null) {
        for (ProjectBuilderDefinition builderDefinition :
            ProjectBuilderDefinitionFactory.getProjectBuilderDefinitions()) {
          if (DN_BUILDER_ID.equals(builderDefinition.getId())) {
            builderDefinition.setEnabled(false, project);
            break;
          }
        }
      }
    } else {
      // Make sure that we add DN support if DN is being used in the pom.xml
      if (mavenProject.getPlugin("org.datanucleus:maven-datanucleus-plugin") != null) {
        for (ProjectBuilderDefinition builderDefinition :
            ProjectBuilderDefinitionFactory.getProjectBuilderDefinitions()) {
          if (DN_BUILDER_ID.equals(builderDefinition.getId())) {
            SpringCorePreferences.getProjectPreferences(project)
                .putBoolean(SpringCore.PROJECT_PROPERTY_ID, true);
            builderDefinition.setEnabled(true, project);
            break;
          }
        }
      }
    }
  }
  @Override
  public void execute() throws MojoExecutionException, MojoFailureException {

    FileOutputStream fos = null;
    try {
      if (!project.getPackaging().equalsIgnoreCase("pom")) {

        String status = project.getProperties().getProperty("deegree.module.status");
        if (status == null) {
          status = "unknown";
        }

        File f = new File("/tmp/" + status + ".txt");
        fos = new FileOutputStream(f, true);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));

        writer.print("||");
        writer.print(project.getArtifactId());
        writer.print("||");
        writer.print(project.getDescription());
        writer.print("||");
        writer.print("\n");
        writer.close();
      }
    } catch (FileNotFoundException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
      throw new MojoExecutionException(e.getMessage(), e);
    } finally {
      IOUtils.closeQuietly(fos);
    }
  }
  protected void setUp() throws Exception {
    // prepare plexus environment
    super.setUp();

    ajcMojo.project = project;
    String temp = new File(".").getAbsolutePath();
    basedir = temp.substring(0, temp.length() - 2) + "/src/test/projects/" + getProjectName() + "/";
    project.getBuild().setDirectory(basedir + "/target");
    project.getBuild().setOutputDirectory(basedir + "/target/classes");
    project.getBuild().setTestOutputDirectory(basedir + "/target/test-classes");
    project.getBuild().setSourceDirectory(basedir + "/src/main/java");
    project.getBuild().setTestSourceDirectory(basedir + "/src/test/java");
    project.addCompileSourceRoot(project.getBuild().getSourceDirectory());
    project.addTestCompileSourceRoot(project.getBuild().getTestSourceDirectory());
    ajcMojo.basedir = new File(basedir);

    setVariableValueToObject(
        ajcMojo, "outputDirectory", new File(project.getBuild().getOutputDirectory()));

    ArtifactHandler artifactHandler = new MockArtifactHandler();
    Artifact artifact = new MockArtifact("dill", "dall");
    artifact.setArtifactHandler(artifactHandler);
    project.setArtifact(artifact);
    project.setDependencyArtifacts(Collections.EMPTY_SET);
  }
Exemplo n.º 14
0
  /**
   * DOCUMENT ME!
   *
   * @throws MojoExecutionException DOCUMENT ME!
   */
  public void execute() throws MojoExecutionException {
    MavenLogWrapper.setLog(getLog());

    LogFactory.getFactory()
        .setAttribute(
            "org.apache.commons.logging.Log", "net.sourceforge.floggy.maven.MavenLogWrapper");

    Weaver weaver = new Weaver();

    try {
      List list = project.getCompileClasspathElements();
      File temp =
          new File(project.getBuild().getDirectory(), String.valueOf(System.currentTimeMillis()));
      FileUtils.forceMkdir(temp);
      weaver.setOutputFile(temp);
      weaver.setInputFile(input);
      weaver.setClasspath((String[]) list.toArray(new String[list.size()]));

      if (configurationFile == null) {
        Configuration configuration = new Configuration();
        configuration.setAddDefaultConstructor(addDefaultConstructor);
        configuration.setGenerateSource(generateSource);
        weaver.setConfiguration(configuration);
      } else {
        weaver.setConfigurationFile(configurationFile);
      }

      weaver.execute();
      FileUtils.copyDirectory(temp, output);
      FileUtils.forceDelete(temp);
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
Exemplo n.º 15
0
  public void testAccessRulesClasspath() throws Exception {
    File basedir = getBasedir("projects/accessrules");
    List<MavenProject> projects = getSortedProjects(basedir, null);

    getMojo(projects, projects.get(1)).execute();
    getMojo(projects, projects.get(2)).execute();
    getMojo(projects, projects.get(3)).execute();

    MavenProject project = projects.get(4);
    AbstractOsgiCompilerMojo mojo = getMojo(projects, project);
    List<String> cp = mojo.getClasspathElements();
    assertEquals(4, cp.size());
    assertEquals(getClasspathElement(project.getBasedir(), "target/classes", ""), cp.get(0));
    assertEquals(
        getClasspathElement(
            new File(getBasedir()),
            "target/projects/accessrules/p001/target/classes",
            "[+p001/*:?**/*]"),
        cp.get(1));
    // note that PDE sorts dependencies coming via imported-package by symbolicName_version
    assertEquals(
        getClasspathElement(
            new File(getBasedir()),
            "target/projects/accessrules/p003/target/classes",
            "[+p003/*:?**/*]"),
        cp.get(2));
    assertEquals(
        getClasspathElement(
            new File(getBasedir()),
            "target/projects/accessrules/p004/target/classes",
            "[+p004/*:?**/*]"),
        cp.get(3));
  }
Exemplo n.º 16
0
  public void execute() throws MojoExecutionException {
    MavenProject project = getProject();

    if (!supportedProjectTypes.contains(project.getPackaging())) {
      getLog().info("Ignoring packaging type " + project.getPackaging());
      return;
    } else if ("NONE".equalsIgnoreCase(obrRepository)) {
      getLog().info("OBR update disabled (enable with -DobrRepository)");
      return;
    }

    Log log = getLog();
    ObrUpdate update;

    String mavenRepository = localRepository.getBasedir();

    URI repositoryXml = ObrUtils.findRepositoryXml(mavenRepository, obrRepository);
    URI obrXmlFile = ObrUtils.toFileURI(obrXml);
    URI bundleJar;

    if (null == file) {
      bundleJar = ObrUtils.findBundleJar(localRepository, project.getArtifact());
    } else {
      bundleJar = file.toURI();
    }

    Config userConfig = new Config();

    update =
        new ObrUpdate(
            repositoryXml, obrXmlFile, project, bundleJar, mavenRepository, userConfig, log);

    update.updateRepository();
  }
Exemplo n.º 17
0
  /**
   * Merge WsdlOptions that point to the same file by adding the extraargs to the first option and
   * deleting the second from the options list
   *
   * @param options
   */
  @SuppressWarnings("unchecked")
  private Artifact resolveRemoteWsdlArtifact(List<?> remoteRepos, Artifact artifact)
      throws MojoExecutionException {

    /**
     * First try to find the artifact in the reactor projects of the maven session. So an artifact
     * that is not yet built can be resolved
     */
    List<MavenProject> rProjects = mavenSession.getSortedProjects();
    for (MavenProject rProject : rProjects) {
      if (artifact.getGroupId().equals(rProject.getGroupId())
          && artifact.getArtifactId().equals(rProject.getArtifactId())
          && artifact.getVersion().equals(rProject.getVersion())) {
        Set<Artifact> artifacts = rProject.getArtifacts();
        for (Artifact pArtifact : artifacts) {
          if ("wadl".equals(pArtifact.getType())) {
            return pArtifact;
          }
        }
      }
    }

    /** If this did not work resolve the artifact using the artifactResolver */
    try {
      artifactResolver.resolve(artifact, remoteRepos, localRepository);
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException("Error downloading wsdl artifact.", e);
    } catch (ArtifactNotFoundException e) {
      throw new MojoExecutionException("Resource can not be found.", e);
    }

    return artifact;
  }
Exemplo n.º 18
0
  protected String getGrailsPluginFileName() {
    String artifactId = project.getArtifactId();

    String pluginName =
        GrailsNameUtils.getNameFromScript(project.getArtifactId()) + "GrailsPlugin.groovy";

    String name = this.getBasedir() + File.separator + pluginName;

    if (new File(name).exists()) {
      return pluginName;
    }

    if (artifactId.startsWith("grails-")) {
      artifactId = artifactId.substring("grails-".length());

      pluginName = GrailsNameUtils.getNameFromScript(artifactId) + "GrailsPlugin.groovy";

      name = this.getBasedir() + File.separator + pluginName;

      if (new File(name).exists()) {
        return pluginName;
      }
    }

    return null;
  }
Exemplo n.º 19
0
 private Map<String, Artifact> createManagedVersionMap() throws MojoExecutionException {
   Map<String, Artifact> map = new HashMap<String, Artifact>();
   DependencyManagement dependencyManagement = project.getDependencyManagement();
   if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
     for (Dependency d : dependencyManagement.getDependencies()) {
       try {
         VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
         Artifact artifact =
             artifactFactory.createDependencyArtifact(
                 d.getGroupId(),
                 d.getArtifactId(),
                 versionRange,
                 d.getType(),
                 d.getClassifier(),
                 d.getScope(),
                 d.isOptional());
         handleExclusions(artifact, d);
         map.put(d.getManagementKey(), artifact);
       } catch (InvalidVersionSpecificationException e) {
         throw new MojoExecutionException(
             String.format(
                 "%1s: unable to parse version '%2s' for dependency '%3s': %4s",
                 project.getId(), d.getVersion(), d.getManagementKey(), e.getMessage()),
             e);
       }
     }
   }
   return map;
 }
Exemplo n.º 20
0
  /**
   * Get the set of artifacts that are provided by Synapse at runtime.
   *
   * @return
   * @throws MojoExecutionException
   */
  private Set<Artifact> getSynapseRuntimeArtifacts() throws MojoExecutionException {
    Log log = getLog();
    log.debug("Looking for synapse-core artifact in XAR project dependencies ...");
    Artifact synapseCore = null;
    for (Iterator<?> it = project.getDependencyArtifacts().iterator(); it.hasNext(); ) {
      Artifact artifact = (Artifact) it.next();
      if (artifact.getGroupId().equals("org.apache.synapse")
          && artifact.getArtifactId().equals("synapse-core")) {
        synapseCore = artifact;
        break;
      }
    }
    if (synapseCore == null) {
      throw new MojoExecutionException("Could not locate dependency on synapse-core");
    }

    log.debug("Loading project data for " + synapseCore + " ...");
    MavenProject synapseCoreProject;
    try {
      synapseCoreProject =
          projectBuilder.buildFromRepository(
              synapseCore, remoteArtifactRepositories, localRepository);
    } catch (ProjectBuildingException e) {
      throw new MojoExecutionException(
          "Unable to retrieve project information for " + synapseCore, e);
    }
    Set<Artifact> synapseRuntimeDeps;
    try {
      synapseRuntimeDeps =
          synapseCoreProject.createArtifacts(
              artifactFactory, Artifact.SCOPE_RUNTIME, new TypeArtifactFilter("jar"));
    } catch (InvalidDependencyVersionException e) {
      throw new MojoExecutionException("Unable to get project dependencies for " + synapseCore, e);
    }
    log.debug("Direct runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    log.debug("Resolving transitive dependencies for " + synapseCore + " ...");
    try {
      synapseRuntimeDeps =
          artifactCollector
              .collect(
                  synapseRuntimeDeps,
                  synapseCoreProject.getArtifact(),
                  synapseCoreProject.getManagedVersionMap(),
                  localRepository,
                  remoteArtifactRepositories,
                  artifactMetadataSource,
                  null,
                  Collections.singletonList(new DebugResolutionListener(logger)))
              .getArtifacts();
    } catch (ArtifactResolutionException e) {
      throw new MojoExecutionException(
          "Unable to resolve transitive dependencies for " + synapseCore);
    }
    log.debug("All runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    return synapseRuntimeDeps;
  }
  public void testMissingVersionFromDependencyMgtWithClassifier() throws Exception {
    ArtifactItem item = new ArtifactItem();

    item.setArtifactId("artifactId");
    item.setClassifier("classifier");
    item.setGroupId("groupId");
    item.setType("jar");

    MavenProject project = mojo.getProject();
    project.setDependencies(getDependencyList(item));

    item = new ArtifactItem();

    item.setArtifactId("artifactId-2");
    item.setClassifier("classifier");
    item.setGroupId("groupId");
    item.setType("jar");

    List<ArtifactItem> list = new ArrayList<ArtifactItem>();
    list.add(item);

    mojo.setArtifactItems(list);

    project.getDependencyManagement().setDependencies(getDependencyMgtList(item));

    mojo.execute();

    assertMarkerFile(true, item);
    assertEquals("3.1", item.getVersion());
  }
Exemplo n.º 22
0
 private void checkOnNoDependencieVersionsFrom3rdParty(MavenProject project)
     throws EnforcerRuleException {
   Model originalModel = project.getOriginalModel();
   StringBuilder dependenciesWithVersionDeclaration = new StringBuilder();
   if (project.getGroupId().equals(ignoreMasterProjectGroupId)
       || originalModel.getDependencyManagement() == null
       || originalModel.getDependencyManagement().getDependencies() == null) {
     return;
   }
   boolean fail = false;
   for (Dependency d : originalModel.getDependencyManagement().getDependencies()) {
     if (!d.getGroupId().startsWith(allowedGroupPrefix)) {
       dependenciesWithVersionDeclaration.append(" - " + d.toString() + "\n");
       fail = true;
     }
   }
   if (fail) {
     throw new EnforcerRuleException(
         "This Project contains Dependency-Versions from 3rd party libs (not "
             + allowedGroupPrefix
             + ").\n"
             + "Please declare for maintainance reasons 3rd pary versions in "
             + ignoreMasterProjectGroupId
             + ".\n"
             + "This dependencies sould be corrected:\n"
             + dependenciesWithVersionDeclaration);
   }
 }
Exemplo n.º 23
0
  public void execute() throws MojoExecutionException {
    try {
      File out = new File(project.getBasedir(), jars);
      for (Iterator i = getIncludedArtifacts().iterator(); i.hasNext(); ) {
        Artifact a = (Artifact) i.next();
        FileUtils.copyFileToDirectory(a.getFile(), out);
      }

      if (packageSources) {
        packageSources(getIncludedArtifacts());
      }

      Manifest manifest = getManifest();
      File metaInf = new File(project.getBasedir(), "META-INF");
      metaInf.mkdirs();
      BufferedOutputStream os =
          new BufferedOutputStream(new FileOutputStream(new File(metaInf, "MANIFEST.MF")));
      manifest.write(os);
      os.close();

      //			packageBundle();
    } catch (Exception e) {
      throw new MojoExecutionException(e.getMessage(), e);
    }
  }
  public void updatePom() throws IOException, XmlPullParserException {
    File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile();
    MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);
    version = mavenProject.getVersion();

    // Skip changing the pom file if group ID and artifact ID are matched
    if (MavenUtils.checkOldPluginEntry(
        mavenProject, "org.wso2.maven", "wso2-esb-template-plugin")) {
      return;
    }

    Plugin plugin =
        MavenUtils.createPluginEntry(
            mavenProject,
            "org.wso2.maven",
            "wso2-esb-template-plugin",
            MavenConstants.WSO2_ESB_TEMPLATE_VERSION,
            true);
    PluginExecution pluginExecution = new PluginExecution();
    pluginExecution.addGoal("pom-gen");
    pluginExecution.setPhase("process-resources");
    pluginExecution.setId("template");

    Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode();
    Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation");
    artifactLocationNode.setValue(".");
    Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList");
    typeListNode.setValue("${artifact.types}");
    pluginExecution.setConfiguration(configurationNode);
    plugin.addExecution(pluginExecution);
    MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation);
  }
Exemplo n.º 25
0
  /**
   * Copies all found resource files, including test resources to the <code>targetFolder</code>.
   *
   * <p>Resource files to be copied are filtered or included according to the configurations inside
   * <code>project</code>'s pom.xml file.
   *
   * @param project project whose resource files to be copied
   * @param targetFolder matching resource files are stored in this directory
   */
  public static void copyResourcesTo(MavenProject project, String targetFolder) {
    File targetFolderFile = new File(targetFolder);
    String includes;
    String excludes;
    List allResources = project.getResources();
    allResources.addAll(project.getTestResources());
    LOG.info("Copying resource files to runner.jar");

    for (Object res : allResources) {
      if (!(res instanceof Resource)) {
        continue;
      }
      try {
        Resource resource = (Resource) res;
        File baseDir = new File(resource.getDirectory());
        includes =
            resource.getIncludes().toString().replace("[", "").replace("]", "").replace(" ", "");
        excludes =
            resource.getExcludes().toString().replace("[", "").replace("]", "").replace(" ", "");
        List<String> resFiles = FileUtils.getFileNames(baseDir, includes, excludes, true, true);
        for (String resFile : resFiles) {
          File resourceFile = new File(resFile);
          LOG.info("Copying {} to {}", resourceFile.getName(), targetFolder);
          FileUtils.copyFileToDirectory(resourceFile, targetFolderFile);
        }
      } catch (IOException e) {
        LOG.warn("Error while trying to copy resource files", e);
      }
    }
  }
  public UpdateResult updateVersion() {
    List<File> changedPoms = new ArrayList<File>();
    List<String> errors = new ArrayList<String>();
    for (ReleasableModule module : reactor.getModulesInBuildOrder()) {
      try {
        MavenProject project = module.getProject();
        if (module.willBeReleased()) {
          log.info("Going to release " + module.getArtifactId() + " " + module.getNewVersion());
        }

        List<String> errorsForCurrentPom = alterModel(project, module.getNewVersion());
        errors.addAll(errorsForCurrentPom);

        File pom = project.getFile().getCanonicalFile();
        changedPoms.add(pom);
        Writer fileWriter = new FileWriter(pom);

        Model originalModel = project.getOriginalModel();
        try {
          MavenXpp3Writer pomWriter = new MavenXpp3Writer();
          pomWriter.write(fileWriter, originalModel);
        } finally {
          fileWriter.close();
        }
      } catch (Exception e) {
        return new UpdateResult(changedPoms, errors, e);
      }
    }
    return new UpdateResult(changedPoms, errors, null);
  }
Exemplo n.º 27
0
  private boolean ensureNoLocalModifications()
      throws ComponentLookupException, ScmException, MojoExecutionException {

    if (!Boolean.getBoolean("sesat.mojo.localModifications.ignore")) {

      final ScmManager scmManager = (ScmManager) container.lookup(ScmManager.ROLE);

      loadPomProject();

      final StatusScmResult result =
          scmManager.status(
              scmManager.makeScmRepository(project.getScm().getDeveloperConnection()),
              new ScmFileSet(pomProject.getBasedir()));

      if (!result.isSuccess()) {

        getLog().error(result.getCommandOutput());
        throw new MojoExecutionException("Failed to ensure checkout has no modifications");
      }

      if (0 < result.getChangedFiles().size()) {

        throw new MojoExecutionException(
            "Your checkout has local modifications. "
                + "Server deploy can *only* be done with a clean workbench.");
      }

      return result.isSuccess() && 0 == result.getChangedFiles().size();
    }
    return true; // sesat.mojo.localModifications.ignore
  }
Exemplo n.º 28
0
  public void testExecutionEnvironment() throws Exception {
    File basedir = getBasedir("projects/executionEnvironment");
    List<MavenProject> projects = getSortedProjects(basedir, null);
    MavenProject project;
    // project with neither POM nor MANIFEST configuration => must fallback to
    // source/target level == 1.5
    project = projects.get(1);
    getMojo(projects, project).execute();
    assertBytecodeMajorLevel(
        TARGET_1_5, new File(project.getBasedir(), "target/classes/Generic.class"));

    // project with multiple execution envs.
    // Minimum source and target level must be taken
    project = projects.get(2);
    try {
      getMojo(projects, project).execute();
      fail("compilation failure due to assert keyword expected");
    } catch (CompilationFailureException e) {
      // expected
    }
    // project with both explicit compiler configuration in pom.xml and
    // Bundle-RequiredExecutionEnvironment.
    // explicit compiler configuration in the pom should win. see
    // https://issues.sonatype.org/browse/TYCHO-476
    project = projects.get(3);
    AbstractOsgiCompilerMojo mojo = getMojo(projects, project);
    assertEquals("jsr14", mojo.getTargetLevel());
    assertEquals("1.5", mojo.getSourceLevel());
    assertEquals("J2SE-1.5", mojo.getExecutionEnvironment());
    mojo.execute();
    assertBytecodeMajorLevel(
        TARGET_1_4, new File(project.getBasedir(), "target/classes/Generic.class"));
  }
Exemplo n.º 29
0
  private List<Dependency> addWebDependencies(
      String appfuseVersion, List<Dependency> newDependencies, String webFramework) {
    // Add dependencies from appfuse-common-web
    newDependencies = addModuleDependencies(newDependencies, "web", "web");

    Double appfuseVersionAsDouble =
        new Double(appfuseVersion.substring(0, appfuseVersion.lastIndexOf(".")));

    getLog().debug("Detected AppFuse version: " + appfuseVersionAsDouble);

    if (isAppFuse() && appfuseVersionAsDouble < 2.1) {

      // Add dependencies from appfuse-common-web
      newDependencies = addModuleDependencies(newDependencies, "web-common", "web/common");

      // newDependencies = addModuleDependencies(newDependencies, webFramework, "web/" +
      // webFramework);
    }

    // modular archetypes still seem to need these - todo: figure out why
    if (isAppFuse() && project.getPackaging().equals("war") && project.hasParent()) {
      newDependencies = addModuleDependencies(newDependencies, "web-common", "web/common");

      newDependencies = addModuleDependencies(newDependencies, webFramework, "web/" + webFramework);
    }
    return newDependencies;
  }
 public Object getParent(Object element) {
   if (element instanceof MavenProject) {
     MavenProject project = (MavenProject) element;
     return project.getParent();
   }
   return null;
 }