private List<String> alterModel(MavenProject project, String newVersion) {
    Model originalModel = project.getOriginalModel();
    originalModel.setVersion(newVersion);

    List<String> errors = new ArrayList<String>();

    String searchingFrom = project.getArtifactId();
    MavenProject parent = project.getParent();
    if (parent != null && isSnapshot(parent.getVersion())) {
      try {
        ReleasableModule parentBeingReleased =
            reactor.find(parent.getGroupId(), parent.getArtifactId(), parent.getVersion());
        originalModel.getParent().setVersion(parentBeingReleased.getVersionToDependOn());
        log.debug(
            " Parent "
                + parentBeingReleased.getArtifactId()
                + " rewritten to version "
                + parentBeingReleased.getVersionToDependOn());
      } catch (UnresolvedSnapshotDependencyException e) {
        errors.add("The parent of " + searchingFrom + " is " + e.artifactId + " " + e.version);
      }
    }
    for (Dependency dependency : originalModel.getDependencies()) {
      String version = dependency.getVersion();
      if (isSnapshot(version)) {
        try {
          ReleasableModule dependencyBeingReleased =
              reactor.find(dependency.getGroupId(), dependency.getArtifactId(), version);
          dependency.setVersion(dependencyBeingReleased.getVersionToDependOn());
          log.debug(
              " Dependency on "
                  + dependencyBeingReleased.getArtifactId()
                  + " rewritten to version "
                  + dependencyBeingReleased.getVersionToDependOn());
        } catch (UnresolvedSnapshotDependencyException e) {
          errors.add(searchingFrom + " references dependency " + e.artifactId + " " + e.version);
        }
      } else
        log.debug(
            " Dependency on "
                + dependency.getArtifactId()
                + " kept at version "
                + dependency.getVersion());
    }
    for (Plugin plugin : project.getModel().getBuild().getPlugins()) {
      String version = plugin.getVersion();
      if (isSnapshot(version)) {
        if (!isMultiModuleReleasePlugin(plugin)) {
          errors.add(
              searchingFrom + " references plugin " + plugin.getArtifactId() + " " + version);
        }
      }
    }
    return errors;
  }
コード例 #2
0
  public void updatePom() throws Exception {
    File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile();
    MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);

    boolean pluginExists =
        MavenUtils.checkOldPluginEntry(
            mavenProject,
            "org.wso2.maven",
            "wso2-esb-template-plugin",
            MavenConstants.WSO2_ESB_TEMPLATE_VERSION);
    if (pluginExists) {
      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);
    Repository repo = new Repository();
    repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/");
    repo.setId("wso2-nexus");

    RepositoryPolicy releasePolicy = new RepositoryPolicy();
    releasePolicy.setEnabled(true);
    releasePolicy.setUpdatePolicy("daily");
    releasePolicy.setChecksumPolicy("ignore");

    repo.setReleases(releasePolicy);

    if (!mavenProject.getRepositories().contains(repo)) {
      mavenProject.getModel().addRepository(repo);
      mavenProject.getModel().addPluginRepository(repo);
    }

    MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation);
  }
コード例 #3
0
  private AgentProjectInfo processProject(MavenProject project) {
    long startTime = System.currentTimeMillis();

    log.info(WssUtils.logMsg(LOG_COMPONENT, "processing Maven project " + project.getId()));

    AgentProjectInfo projectInfo = new AgentProjectInfo();

    // project token
    if (project.equals(mavenParser.getMavenProject())) {
      projectInfo.setProjectToken(projectToken);
    } else {
      projectInfo.setProjectToken(moduleTokens.get(project.getArtifactId()));
    }

    // project coordinates
    projectInfo.setCoordinates(extractCoordinates(project));

    Parent parent = project.getModel().getParent();
    // parent coordinates
    if (parent != null) {
      projectInfo.setParentCoordinates(extractParentCoordinates(parent));
    }

    // dependencies
    Map<Dependency, Artifact> lut = createLookupTable(project);
    for (Dependency dependency : mavenParser.getDependencies(project)) {
      DependencyInfo dependencyInfo = getDependencyInfo(dependency);

      Artifact artifact = lut.get(dependency);
      if (artifact != null) {
        File artifactFile = artifact.getFile();
        if (artifactFile != null && artifactFile.exists()) {
          try {
            dependencyInfo.setSha1(ChecksumUtils.calculateSHA1(artifactFile));
          } catch (IOException e) {
            log.warn(WssUtils.logMsg(LOG_COMPONENT, ERROR_SHA1 + " for " + artifact.getId()));
          }
        }
      }

      projectInfo.getDependencies().add(dependencyInfo);
    }

    log.info(
        WssUtils.logMsg(
            LOG_COMPONENT,
            "Total Maven project processing time is "
                + (System.currentTimeMillis() - startTime)
                + " [msec]"));

    return projectInfo;
  }
コード例 #4
0
  /**
   * Creates a request for the specified plugin prefix and build session. The provided build session
   * will be used to configure repository settings. If the session has a current project, its plugin
   * repositories and model will be used as well.
   *
   * @param prefix The plugin prefix to resolve, must not be {@code null}.
   * @param session The build session from which to derive further settings, must not be {@code
   *     null}.
   */
  public DefaultPluginPrefixRequest(String prefix, MavenSession session) {
    setPrefix(prefix);

    setRepositorySession(session.getRepositorySession());

    MavenProject project = session.getCurrentProject();
    if (project != null) {
      setRepositories(project.getRemotePluginRepositories());
      setPom(project.getModel());
    }

    setPluginGroups(session.getPluginGroups());
  }
コード例 #5
0
  @NotNull
  private MavenServerExecutionResult createExecutionResult(
      File file, MavenExecutionResult result, DependencyNode rootNode) throws RemoteException {
    Collection<MavenProjectProblem> problems = MavenProjectProblem.createProblemsList();
    THashSet<MavenId> unresolvedArtifacts = new THashSet<MavenId>();

    validate(file, result.getExceptions(), problems, unresolvedArtifacts);

    MavenProject mavenProject = result.getMavenProject();
    if (mavenProject == null)
      return new MavenServerExecutionResult(null, problems, unresolvedArtifacts);

    MavenModel model =
        MavenModelConverter.convertModel(
            mavenProject.getModel(),
            mavenProject.getCompileSourceRoots(),
            mavenProject.getTestCompileSourceRoots(),
            mavenProject.getArtifacts(),
            (rootNode == null ? Collections.emptyList() : rootNode.getChildren()),
            mavenProject.getExtensionArtifacts(),
            getLocalRepositoryFile());

    RemoteNativeMavenProjectHolder holder = new RemoteNativeMavenProjectHolder(mavenProject);
    try {
      UnicastRemoteObject.exportObject(holder, 0);
    } catch (RemoteException e) {
      throw new RuntimeException(e);
    }

    Collection<String> activatedProfiles = collectActivatedProfiles(mavenProject);

    MavenServerExecutionResult.ProjectData data =
        new MavenServerExecutionResult.ProjectData(
            model,
            MavenModelConverter.convertToMap(mavenProject.getModel()),
            holder,
            activatedProfiles);
    return new MavenServerExecutionResult(data, problems, unresolvedArtifacts);
  }
コード例 #6
0
  private boolean loadParentHierarchy(IMavenProjectFacade facade, IProgressMonitor monitor)
      throws CoreException {
    boolean loadedParent = false;
    MavenProject mavenProject = facade.getMavenProject();

    try {
      if (mavenProject.getModel().getParent() == null || mavenProject.getParent() != null) {
        // If the getParent() method is called without error,
        // we can assume the project has been fully loaded, no need to continue.
        return false;
      }
    } catch (IllegalStateException e) {
      // The parent can not be loaded properly
    }

    MavenExecutionRequest request = null;

    while (mavenProject != null && mavenProject.getModel().getParent() != null) {
      if (monitor.isCanceled()) {
        break;
      }

      if (request == null) {
        request = projectManager.createExecutionRequest(facade, monitor);
      }

      MavenProject parentProject = maven.resolveParentProject(request, mavenProject, monitor);

      if (parentProject != null) {
        mavenProject.setParent(parentProject);
        loadedParent = true;
      }

      mavenProject = parentProject;
    }

    return loadedParent;
  }
コード例 #7
0
ファイル: MavenFacetImpl.java プロジェクト: higoramp/core
 private String createDefaultPOM() {
   MavenXpp3Writer writer = new MavenXpp3Writer();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   org.apache.maven.project.MavenProject mavenProject =
       new org.apache.maven.project.MavenProject();
   mavenProject.setModelVersion("4.0.0");
   try {
     writer.write(baos, mavenProject.getModel());
     return baos.toString();
   } catch (IOException e) {
     // Should not happen
     throw new RuntimeException("Failed to create default pom.xml", e);
   }
 }
コード例 #8
0
ファイル: XmlUtils.java プロジェクト: nickboldt/m2e-core
 /**
  * converts an InputLocation to a file path on the local disk, null if not available. still the
  * input source's model value can be used further..
  *
  * @param location
  * @return
  */
 public static File fileForInputLocation(InputLocation location, MavenProject origin) {
   InputSource source = location.getSource();
   if (source != null) {
     // MNGECLIPSE-2539 apparently if maven can't resolve the model from local storage,
     // the location will be empty. not only applicable to local repo models but
     // apparently also to models in workspace not reachable by relativePath
     String loc = source.getLocation();
     File file = null;
     if (loc != null) {
       file = new File(loc);
     } else {
       // try to find pom by coordinates..
       String modelId = source.getModelId();
       if (origin.getModel().getId().equals(modelId) && origin.getFile() != null) {
         return origin.getFile();
       }
       String[] splitStrings = modelId.split(":");
       assert splitStrings.length == 3;
       IMavenProjectFacade facade =
           MavenPlugin.getMavenProjectRegistry()
               .getMavenProject(splitStrings[0], splitStrings[1], splitStrings[2]);
       if (facade != null) {
         file = facade.getPomFile();
       } else {
         // if not in the workspace, try looking into the local repository.
         IMaven maven = MavenPlugin.getMaven();
         try {
           String path =
               maven.getArtifactPath(
                   maven.getLocalRepository(),
                   splitStrings[0],
                   splitStrings[1],
                   splitStrings[2],
                   "pom",
                   null);
           if (path != null) {
             file = new File(maven.getLocalRepositoryPath(), path);
           }
         } catch (CoreException e) {
           log.error("Failed to calculate local repository path of artifact", e);
         }
       }
     }
     return file;
   }
   return null;
 }
コード例 #9
0
 static InputLocation findLocationForManagedArtifact(
     final ManagedArtifactRegion region, MavenProject mavprj) {
   Model mdl = mavprj.getModel();
   InputLocation openLocation = null;
   if (region.isDependency) {
     DependencyManagement dm = mdl.getDependencyManagement();
     if (dm != null) {
       List<Dependency> list = dm.getDependencies();
       String id = region.groupId + ":" + region.artifactId + ":"; // $NON-NLS-1$ //$NON-NLS-2$
       if (list != null) {
         for (Dependency dep : list) {
           if (dep.getManagementKey().startsWith(id)) {
             InputLocation location = dep.getLocation(ARTIFACT_ID); // $NON-NLS-1$
             // when would this be null?
             if (location != null) {
               openLocation = location;
               break;
             }
           }
         }
       }
     }
   }
   if (region.isPlugin) {
     Build build = mdl.getBuild();
     if (build != null) {
       PluginManagement pm = build.getPluginManagement();
       if (pm != null) {
         List<Plugin> list = pm.getPlugins();
         String id = Plugin.constructKey(region.groupId, region.artifactId);
         if (list != null) {
           for (Plugin plg : list) {
             if (id.equals(plg.getKey())) {
               InputLocation location = plg.getLocation(ARTIFACT_ID); // $NON-NLS-1$
               // when would this be null?
               if (location != null) {
                 openLocation = location;
                 break;
               }
             }
           }
         }
       }
     }
   }
   return openLocation;
 }
  /** Add jar files in libs into the project classpath. */
  private void addLibsJarsToClassPath(
      UnpackedLibHelper helper, MavenProject project, Artifact artifact)
      throws MavenExecutionException {
    try {
      final File unpackLibFolder = helper.getUnpackedLibFolder(artifact);
      final File artifactFile = helper.getArtifactToFile(artifact);
      ZipFile zipFile = new ZipFile(artifactFile);
      Enumeration enumeration = zipFile.entries();
      while (enumeration.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) enumeration.nextElement();
        String entryName = entry.getName();

        // Only jar files under 'libs' directory to be processed.
        if (Pattern.matches("^libs/.+\\.jar$", entryName)) {
          final File libsJarFile = new File(unpackLibFolder, entryName);
          log.warn("Adding jar from libs folder to classpath: " + libsJarFile);

          // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
          // has a Mojo requiring dependency resolution I need to create a dummy classesJar here.
          if (!libsJarFile.getParentFile().exists()) {
            libsJarFile.getParentFile().mkdirs();
          }
          libsJarFile.createNewFile();

          // Add the jar to the classpath.
          final Dependency dependency =
              createSystemScopeDependency(artifact, libsJarFile, libsJarFile.getName());

          project.getModel().addDependency(dependency);
          addedJarFromLibs = true;
        }
      }
    } catch (MojoExecutionException e) {
      log.debug("Error extract jars");
    } catch (ZipException e) {
      log.debug("Error");
    } catch (IOException e) {
      log.debug("Error");
    }
  }
コード例 #11
0
 private boolean pomUsesSwitchYardBOM() {
   final MavenProject project = _switchYardProject.getMavenProject();
   DependencyManagement depMgmt = null;
   if (project != null && project.getOriginalModel() != null) {
     final Model originalModel = project.getOriginalModel();
     depMgmt = originalModel.getDependencyManagement();
   } else if (project != null && project.getModel() != null) {
     final Model originalModel = project.getOriginalModel();
     depMgmt = originalModel.getDependencyManagement();
   }
   if (depMgmt != null && !depMgmt.getDependencies().isEmpty()) {
     Iterator<Dependency> depIter = depMgmt.getDependencies().iterator();
     while (depIter.hasNext()) {
       Dependency tempDep = depIter.next();
       if (tempDep.getArtifactId().equals(M2EUtils.SWITCHYARD_BOM_ARTIFACT_ID)) {
         return true;
         //                } else if (tempDep.getArtifactId().equals("fuse-integration-bom")) {
         //                    return true;
       }
     }
   }
   return false;
 }
  /** Add the dependent library classes to the project classpath. */
  private void addClassesToClasspath(
      UnpackedLibHelper helper, MavenProject project, Artifact artifact)
      throws MavenExecutionException {
    // Work out where the dep will be extracted and calculate the file path to the classes jar.
    // This is location where the GenerateSourcesMojo will extract the classes.
    final File classesJar = helper.getUnpackedClassesJar(artifact);
    log.debug("Adding to classpath : " + classesJar);

    // In order to satisfy the LifecycleDependencyResolver on execution up to a phase that
    // has a Mojo requiring dependency resolution I need to create a dummy classesJar here.
    classesJar.getParentFile().mkdirs();
    try {
      classesJar.createNewFile();
      log.debug("Created dummy " + classesJar.getName() + " exist=" + classesJar.exists());
    } catch (IOException e) {
      throw new MavenExecutionException(
          "Could not add " + classesJar.getName() + " as dependency", e);
    }

    // Add the classes to the classpath
    final Dependency dependency = createSystemScopeDependency(artifact, classesJar, null);
    project.getModel().addDependency(dependency);
  }
コード例 #13
0
  /**
   * @param expression the user expression asked.
   * @throws MojoExecutionException if any
   * @throws MojoFailureException if any reflection exceptions occur or missing components.
   */
  private void handleResponse(String expression)
      throws MojoExecutionException, MojoFailureException {
    StringBuilder response = new StringBuilder();

    Object obj;
    try {
      obj = getEvaluator().evaluate(expression);
    } catch (ExpressionEvaluationException e) {
      throw new MojoExecutionException("Error when evaluating the Maven expression", e);
    }

    if (obj != null && expression.equals(obj.toString())) {
      getLog().warn("The Maven expression was invalid. Please use a valid expression.");
      return;
    }

    // handle null
    if (obj == null) {
      response.append("null object or invalid expression");
    }
    // handle primitives objects
    else if (obj instanceof String) {
      response.append(obj.toString());
    } else if (obj instanceof Boolean) {
      response.append(obj.toString());
    } else if (obj instanceof Byte) {
      response.append(obj.toString());
    } else if (obj instanceof Character) {
      response.append(obj.toString());
    } else if (obj instanceof Double) {
      response.append(obj.toString());
    } else if (obj instanceof Float) {
      response.append(obj.toString());
    } else if (obj instanceof Integer) {
      response.append(obj.toString());
    } else if (obj instanceof Long) {
      response.append(obj.toString());
    } else if (obj instanceof Short) {
      response.append(obj.toString());
    }
    // handle specific objects
    else if (obj instanceof File) {
      File f = (File) obj;
      response.append(f.getAbsolutePath());
    }
    // handle Maven pom object
    else if (obj instanceof MavenProject) {
      MavenProject projectAsked = (MavenProject) obj;
      StringWriter sWriter = new StringWriter();
      MavenXpp3Writer pomWriter = new MavenXpp3Writer();
      try {
        pomWriter.write(sWriter, projectAsked.getModel());
      } catch (IOException e) {
        throw new MojoExecutionException("Error when writing pom", e);
      }

      response.append(sWriter.toString());
    }
    // handle Maven Settings object
    else if (obj instanceof Settings) {
      Settings settingsAsked = (Settings) obj;
      StringWriter sWriter = new StringWriter();
      SettingsXpp3Writer settingsWriter = new SettingsXpp3Writer();
      try {
        settingsWriter.write(sWriter, settingsAsked);
      } catch (IOException e) {
        throw new MojoExecutionException("Error when writing settings", e);
      }

      response.append(sWriter.toString());
    } else {
      // others Maven objects
      response.append(toXML(expression, obj));
    }

    getLog().info("\n" + response.toString());
  }
コード例 #14
0
 private void loadMavenSettings(MavenProject pom) {
   addConfiguration(new MapConfiguration(pom.getModel().getProperties()));
 }
コード例 #15
0
  public List<Artifact> resolvePom(File pomFile) {
    if (pomFile == null) {
      throw new RuntimeException("pomFile is null");
    }

    MavenProject pom;
    try {
      PlexusContainer container = container();
      org.apache.maven.repository.RepositorySystem lrs =
          container.lookup(org.apache.maven.repository.RepositorySystem.class);
      ProjectBuilder projectBuilder = container.lookup(ProjectBuilder.class);
      ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
      request.setRepositorySession(repositorySystemSession);
      request.setProcessPlugins(false);
      request.setLocalRepository(lrs.createDefaultLocalRepository());
      request.setRemoteRepositories(
          Arrays.asList(new ArtifactRepository[] {lrs.createDefaultRemoteRepository()}.clone()));
      ProjectBuildingResult result = projectBuilder.build(pomFile, request);
      pom = result.getProject();
    } catch (Exception e) {
      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      }
      throw new RuntimeException("Error loading pom: " + pomFile.getAbsolutePath(), e);
    }

    Artifact rootArtifact =
        new DefaultArtifact(
            pom.getArtifact().getGroupId(),
            pom.getArtifact().getArtifactId(),
            pom.getArtifact().getClassifier(),
            pom.getArtifact().getType(),
            pom.getArtifact().getVersion(),
            null,
            new File(pom.getModel().getBuild().getOutputDirectory()));

    CollectRequest collectRequest = new CollectRequest();
    for (org.apache.maven.model.Dependency dependency : pom.getDependencies()) {
      collectRequest.addDependency(toAetherDependency(dependency));
    }
    for (RemoteRepository repository : pom.getRemoteProjectRepositories()) {
      collectRequest.addRepository(repository);
    }
    for (RemoteRepository repository : repositories) {
      collectRequest.addRepository(repository);
    }

    // Make sure we account for managed dependencies
    if (pom.getDependencyManagement() != null) {
      for (org.apache.maven.model.Dependency managedDependency :
          pom.getDependencyManagement().getDependencies()) {
        collectRequest.addManagedDependency(toAetherDependency(managedDependency));
      }
    }

    DependencyRequest dependencyRequest =
        new DependencyRequest(
            collectRequest, DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME));
    List<Artifact> artifacts = resolveArtifacts(dependencyRequest);
    return ImmutableList.<Artifact>builder().add(rootArtifact).addAll(artifacts).build();
  }
コード例 #16
0
  public boolean performFinish() {
    try {
      project = createNewProject();
      sourceFolder = ProjectUtils.getWorkspaceFolder(project, "src", "main", "java");
      javaProject = JavaCore.create(project);
      root = javaProject.getPackageFragmentRoot(sourceFolder);
      JavaUtils.addJavaSupportAndSourceFolder(project, sourceFolder);
      addDependancies(project);

      String className = filterModel.getFilterClass();
      String packageName = filterModel.getFilterClassPackage();

      IPackageFragment sourcePackage = root.createPackageFragment(packageName, false, null);

      ICompilationUnit cu =
          sourcePackage.createCompilationUnit(
              className + ".java", getFilterClassSource(packageName, className), false, null);
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      File pomfile = project.getFile("pom.xml").getLocation().toFile();
      getModel().getMavenInfo().setPackageName("bundle");
      if (!pomfile.exists()) {
        createPOM(pomfile);
      }

      MavenProject mavenProject = MavenUtils.getMavenProject(pomfile);

      mavenProject.getModel().getProperties().put("CApp.type", "lib/registry/filter");

      Plugin plugin =
          MavenUtils.createPluginEntry(
              mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4", true);

      Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode(plugin);
      Xpp3Dom instructionNode = MavenUtils.createXpp3Node(configurationNode, "instructions");
      Xpp3Dom symbolicNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-SymbolicName");
      symbolicNameNode.setValue(mavenProject.getArtifactId());
      Xpp3Dom bundleNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Name");
      bundleNameNode.setValue(mavenProject.getArtifactId());
      Xpp3Dom exportPackageNode = MavenUtils.createXpp3Node(instructionNode, "Export-Package");
      exportPackageNode.setValue(packageName);
      Xpp3Dom dynamicImportNode =
          MavenUtils.createXpp3Node(instructionNode, "DynamicImport-Package");
      dynamicImportNode.setValue("*");

      Repository repo = new Repository();
      repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/");
      repo.setId("wso2-maven2-repository-1");

      mavenProject.getModel().addRepository(repo);
      mavenProject.getModel().addPluginRepository(repo);

      List<Dependency> dependencyList = new ArrayList<Dependency>();

      Map<String, JavaLibraryBean> dependencyInfoMap =
          JavaLibraryUtil.getDependencyInfoMap(project);
      Map<String, String> map = ProjectDependencyConstants.DEPENDENCY_MAP;
      for (JavaLibraryBean bean : dependencyInfoMap.values()) {
        if (bean.getVersion().contains("${")) {
          for (String path : map.keySet()) {
            bean.setVersion(bean.getVersion().replace(path, map.get(path)));
          }
        }
        Dependency dependency = new Dependency();
        dependency.setArtifactId(bean.getArtifactId());
        dependency.setGroupId(bean.getGroupId());
        dependency.setVersion(bean.getVersion());
        dependencyList.add(dependency);
      }
      MavenUtils.addMavenDependency(mavenProject, dependencyList);
      MavenUtils.saveMavenProject(mavenProject, pomfile);
      ProjectUtils.addNatureToProject(project, false, Constants.REGISTRY_FILTER_PROJECT_NATURE);
      MavenUtils.updateWithMavenEclipsePlugin(
          pomfile,
          new String[] {JDT_BUILD_COMMAND},
          new String[] {Constants.REGISTRY_FILTER_PROJECT_NATURE, JDT_PROJECT_NATURE});
      project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());

      try {
        refreshDistProjects();
        IEditorPart javaEditor = JavaUI.openInEditor(cu);
        JavaUI.revealInEditor(javaEditor, (IJavaElement) cu);
      } catch (Exception e) {
        /* ignore */
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return true;
  }
コード例 #17
0
  public List<IResource> exportArtifact(IProject project) throws Exception {
    List<IResource> exportResources = new ArrayList<IResource>();
    List<String> exportedPackageList = new ArrayList<String>();
    List<String> importededPackageList = new ArrayList<String>();

    ArchiveManipulator archiveManipulator = new ArchiveManipulator();
    NullProgressMonitor nullProgressMonitor = new NullProgressMonitor();
    BundlesDataInfo bundleData = new BundlesDataInfo();
    IFile bundleDataFile = project.getFile("bundles-data.xml");
    File tempProject = createTempProject();
    File libResources = createTempDir(tempProject, "lib_resources");
    MavenProject mavenProject =
        MavenUtils.getMavenProject(project.getFile("pom.xml").getLocation().toFile());

    if (bundleDataFile.exists()) {
      bundleData.deserialize(bundleDataFile);

      for (String lib : bundleData.getExportedPackageListsFromJar().keySet()) {
        IFile JarFile = project.getFile(lib);
        if (JarFile.exists()) {
          archiveManipulator.extract(JarFile.getLocation().toFile(), libResources);
          exportedPackageList.addAll(bundleData.getExportedPackageListsFromJar().get(lib));
        }
      }
      for (IProject lib : bundleData.getExportedPackageListsFromProject().keySet()) {
        if (lib.isOpen()) {
          lib.build(IncrementalProjectBuilder.FULL_BUILD, nullProgressMonitor);
          IJavaProject javaLibProject = JavaCore.create(lib);
          for (IPackageFragment pkg : javaLibProject.getPackageFragments()) {
            if (pkg.getKind() == IPackageFragmentRoot.K_SOURCE) {
              if (pkg.hasChildren()) {
                exportedPackageList.add(pkg.getElementName());
              }
            }
          }

          IPath outPutPath = getOutputPath(javaLibProject);
          // get resource location
          IPath resources = getResourcePath(lib);

          FileUtils.copyDirectoryContents(outPutPath.toFile(), libResources);
          if (resources.toFile().exists()) {
            FileUtils.copyDirectoryContents(resources.toFile(), libResources);
          }
        }
      }
      getPackages(exportedPackageList, mavenProject, "Export-Package");
      getPackages(importededPackageList, mavenProject, "Import-Package");
      BundleManifest manifest = new BundleManifest();
      manifest.setBundleName(project.getName());
      manifest.setBundleSymbolicName(project.getName());
      if (null != mavenProject.getModel().getDescription()
          && !"".equals(mavenProject.getModel().getDescription())) {
        manifest.setBundleDescription(mavenProject.getModel().getDescription());
      } else {
        manifest.setBundleDescription(project.getName());
      }
      if (null != mavenProject.getModel().getVersion()
          && !"".equals(mavenProject.getDescription())) {
        manifest.setBundleVersion(mavenProject.getModel().getVersion());
      } else {
        manifest.setBundleVersion("1.0.0");
      }
      if (null != bundleData.getFragmentHost() && !"".equals(bundleData.getFragmentHost())) {
        manifest.setFragmentHost(bundleData.getFragmentHost());
      }
      manifest.setExportPackagesList(exportedPackageList);
      if (importededPackageList.size() > 0) {
        manifest.setImportPackagesList(importededPackageList);
        manifest.setDynamicImports(false);
      }
      File metaInfDir = new File(libResources, "META-INF");
      if (!metaInfDir.exists()) metaInfDir.mkdir();
      File manifestFile = new File(metaInfDir, "MANIFEST.MF");
      FileUtils.createFile(manifestFile, manifest.toString());

      File tmpArchive = new File(tempProject, project.getName().concat(".jar"));
      archiveManipulator.archiveDir(tmpArchive.toString(), libResources.toString());

      IFile libArchive = getTargetArchive(project, "jar");
      FileUtils.copy(tmpArchive, libArchive.getLocation().toFile());
      exportResources.add((IResource) libArchive);

      // cleaning temp project
      // if(!org.apache.commons.io.FileUtils.deleteQuietly(tempProject.getLocation().toFile())){
      // tempProject.delete(true, getProgressMonitor());
    }

    TempFileUtils.cleanUp();
    return exportResources;
  }