コード例 #1
0
  private Dependency toDependency(String id, String version, String type) throws ResolveException {
    Matcher matcher = PARSER_ID.matcher(id);
    if (!matcher.matches()) {
      throw new ResolveException(
          "Bad id " + id + ", expected format is <groupId>:<artifactId>[:<classifier>]");
    }

    Dependency dependency = new Dependency();

    dependency.setGroupId(matcher.group(1));
    dependency.setArtifactId(matcher.group(2));
    if (matcher.group(4) != null) {
      dependency.setClassifier(StringUtils.defaultString(matcher.group(4), ""));
    }

    if (version != null) {
      dependency.setVersion(version);
    }

    if (type != null) {
      dependency.setType(type);
    }

    return dependency;
  }
コード例 #2
0
ファイル: BaseMojoExecutor.java プロジェクト: emenaceb/appjar
 protected Dependency dependency(String groupId, String artifactId, String version) {
   Dependency dependency = new Dependency();
   dependency.setGroupId(groupId);
   dependency.setArtifactId(artifactId);
   dependency.setVersion(version);
   return dependency;
 }
  public Dependency getDependency(ArtifactDependency artifactDependency) {
    Dependency dependency = new Dependency();
    dependency.setGroupId(artifactDependency.getOrg());
    dependency.setArtifactId(artifactDependency.getName());

    final String latestVersion =
        resolverService.getLatestVersion(artifactDependency.getOrg(), artifactDependency.getName());
    if (latestVersion == null) {
      // Case of third party or not tracked;
      dependency.setVersion(artifactDependency.getVersion());
    } else {
      dependency.setVersion(latestVersion);
    }

    dependency.setScope(artifactDependency.getScope());
    List<ArtifactDependencyExclusion> artifactDependencyExclusions =
        artifactDependency.getExclusions();
    List<Exclusion> exclusions = new ArrayList<Exclusion>();
    for (ArtifactDependencyExclusion artifactDependencyExclusion : artifactDependencyExclusions) {
      Exclusion ex = new Exclusion();
      ex.setGroupId(artifactDependencyExclusion.getGroupId());
      ex.setArtifactId(artifactDependencyExclusion.getArtifactId());
      exclusions.add(ex);
    }
    dependency.setExclusions(exclusions);

    return dependency;
  }
コード例 #4
0
 /**
  * Converts an Aether artifact to a Maven model dependency.
  *
  * @param artifact the Aether artifact to be converted
  * @return a Maven dependency with the same coordinates
  */
 private Dependency artifactToDependency(Artifact artifact) {
   final Dependency dependency = new Dependency();
   dependency.setGroupId(artifact.getGroupId());
   dependency.setArtifactId(artifact.getArtifactId());
   dependency.setVersion(artifact.getVersion());
   dependency.setType(artifact.getExtension());
   return dependency;
 }
コード例 #5
0
  protected Dependency createDependency() {
    Dependency d = new Dependency();
    d.setGroupId(dependencyGroupId);
    d.setArtifactId(dependencyArtifactId);
    d.setVersion(dependencyVersion);
    d.setType(dependencyType);
    d.setClassifier(dependencyClassifier);

    return d;
  }
コード例 #6
0
  @Test
  public void testJacocoCommands() throws Exception {

    Project project = initializeJavaProject();
    Dependency junitDep = new Dependency();
    junitDep.setArtifactId("junit");
    junitDep.setGroupId("junit");
    junitDep.setVersion("4.10");
    junitDep.setScope("test");
    MavenCoreFacet facet = project.getFacet(MavenCoreFacet.class);
    Model pom = facet.getPOM();
    pom.addDependency(junitDep);
    facet.setPOM(pom);

    queueInputLines("");
    // create some simple classes
    getShell().execute("java new-class --package com.test \"public class A {}\"");
    getShell().execute("java new-field \"private int numberA=1;\"");
    getShell().execute("java new-method  \"public int getNumberA(){return numberA;}\"");

    getShell().execute("java new-class --package com.test \"public class B {}\"");
    getShell().execute("java new-field \"private int numberB=2;\"");
    getShell().execute("java new-method  \"public int getNumberB(){return numberB;}\"");

    // create and copy test class
    getShell()
        .execute(
            "java new-class --package com.test \"package com.test; import org.junit.Test;import static org.junit.Assert.*; public class ABTest {}\"");
    getShell()
        .execute(
            "java new-method  \"@Test public void testClasses(){A a = new A();B b = new B();assertEquals(3,a.getNumberA()+b.getNumberB());}\"");
    getShell().execute("cd " + project.getProjectRoot().getFullyQualifiedName());
    getShell().execute("cp src/main/java/com/test/ABTest.java src/test/java/");
    getShell().execute("rm -rf src/main/java/com/test/ABTest.java");

    // run jacoco plugin commands
    getShell().execute("jacoco setup");
    getShell().execute("jacoco run-tests --package com.test");
    queueInputLines("N");
    getShell().execute("jacoco create-report");

    assertTrue(
        "Missing jacoco.exec file!",
        project.getProjectRoot().getChildDirectory("target").getChild("jacoco.exec").exists());
    assertTrue(
        "Missing index.html report file!",
        project
            .getProjectRoot()
            .getChildDirectory("target")
            .getChildDirectory("site")
            .getChildDirectory("jacoco")
            .getChild("index.html")
            .exists());
  }
コード例 #7
0
  public List<Dependency> getDependencyMgtList(ArtifactItem item) {
    Dependency dep = new Dependency();
    dep.setArtifactId(item.getArtifactId());
    dep.setClassifier(item.getClassifier());
    dep.setGroupId(item.getGroupId());
    dep.setType(item.getType());
    dep.setVersion("3.0-SNAPSHOT");

    Dependency dep2 = new Dependency();
    dep2.setArtifactId(item.getArtifactId());
    dep2.setClassifier("classifier");
    dep2.setGroupId(item.getGroupId());
    dep2.setType(item.getType());
    dep2.setVersion("3.1");

    List<Dependency> list = new ArrayList<Dependency>(2);
    list.add(dep2);
    list.add(dep);

    return list;
  }
コード例 #8
0
 @Override
 protected boolean doModify(Model model, Dependency dependency) {
   String depArtifId = dependency.getArtifactId();
   if (R_MAP.containsKey(depArtifId)) {
     String[] replacement = R_MAP.get(depArtifId);
     dependency.setArtifactId(replacement[0]);
     if (replacement.length > 1) dependency.setGroupId(replacement[1]);
     if (replacement.length > 2) dependency.setVersion(replacement[2]);
     return true;
   }
   return false;
 }
 private Dependency createSystemScopeDependency(Artifact artifact, File location, String suffix) {
   String artifactId = artifact.getArtifactId();
   if (suffix != null) {
     artifactId = "_" + suffix;
   }
   final Dependency dependency = new Dependency();
   dependency.setGroupId(artifact.getGroupId());
   dependency.setArtifactId(artifactId);
   dependency.setVersion(artifact.getVersion());
   dependency.setScope(Artifact.SCOPE_SYSTEM);
   dependency.setSystemPath(location.getAbsolutePath());
   return dependency;
 }
コード例 #10
0
  /*
   * (non-Javadoc)
   *
   * @see junit.framework.TestCase#setUp()
   */
  @Override
  protected void setUp() throws Exception {
    tempModel =
        (IDOMModel)
            StructuredModelManager.getModelManager()
                .createUnManagedStructuredModelFor("org.eclipse.m2e.core.pomFile");
    document = tempModel.getStructuredDocument();

    d = new Dependency();
    d.setArtifactId("BBBB");
    d.setGroupId("AAA");
    d.setVersion("1.0");

    e = new ArtifactKey("g", "a", "1.0", null);
  }
コード例 #11
0
  public static Dependency getDependencyForTheProject(IFile file) {
    IProject project = file.getProject();
    MavenProject mavenProject = getMavenProject(project);

    String groupId = mavenProject.getGroupId();
    String artifactId = mavenProject.getArtifactId();
    String version = mavenProject.getVersion();

    String filePath = file.getLocation().toOSString();
    int startIndex =
        (project.getLocation().toOSString()
                + File.separator
                + "src"
                + File.separator
                + "main"
                + File.separator
                + "synapse-config"
                + File.separator)
            .length();
    int endIndex = filePath.lastIndexOf(File.separator);

    String typeString;
    if (startIndex < endIndex) {
      String typeStringFromPath = filePath.substring(startIndex, endIndex);
      if (typeStringFromPath.equalsIgnoreCase("sequences")) {
        typeString = "sequence";
      } else if (typeStringFromPath.equalsIgnoreCase("endpoints")) {
        typeString = "endpoint";
      } else if (typeStringFromPath.equalsIgnoreCase("proxy-services")) {
        typeString = "proxy-service";
      } else {
        typeString = "local-entry";
      }

    } else {
      typeString = "synapse";
    }

    Dependency dependency = new Dependency();
    dependency.setGroupId(groupId + "." + typeString);
    dependency.setArtifactId(artifactId);
    dependency.setVersion(version);

    return dependency;
  }
コード例 #12
0
ファイル: Util.java プロジェクト: dargoner/fuseide
  public static void updateMavenDependencies(
      final List<Dependency> dependencies, final IProject project) throws CoreException {
    final IFile pomIFile = project.getProject().getFile("pom.xml");
    final File pomFile = new File(pomIFile.getLocationURI());
    final org.apache.maven.model.Model pom = MavenPlugin.getMaven().readModel(pomFile);

    // Check if dependency already in the pom
    final List<Dependency> missingDependencies = new ArrayList<>();
    for (final Dependency dependency : dependencies) {
      boolean found = false;
      for (final org.apache.maven.model.Dependency pomDependency : pom.getDependencies()) {
        if (pomDependency.getGroupId().equalsIgnoreCase(dependency.getGroupId())
            && pomDependency.getArtifactId().equalsIgnoreCase(dependency.getArtifactId())) {
          // check for correct version
          if (!pomDependency.getVersion().equalsIgnoreCase(dependency.getVersion())) {
            pomDependency.setVersion(dependency.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDependencies.add(dependency);
      }
    }

    for (final Dependency dependency : missingDependencies) {
      final org.apache.maven.model.Dependency pomDependency =
          new org.apache.maven.model.Dependency();
      pomDependency.setGroupId(dependency.getGroupId());
      pomDependency.setArtifactId(dependency.getArtifactId());
      pomDependency.setVersion(dependency.getVersion());
      pom.addDependency(pomDependency);
    }

    if (!missingDependencies.isEmpty()) {
      try (final OutputStream stream = new BufferedOutputStream(new FileOutputStream(pomFile))) {
        MavenPlugin.getMaven().writeModel(pom, stream);
        pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
      } catch (final Exception e) {
        Activator.error(e);
      }
    }
  }
コード例 #13
0
ファイル: InstallSourceMojo.java プロジェクト: szpak/appfuse
  private void createFullSourcePom(List<Dependency> newDependencies) throws MojoFailureException {
    // Change spring-test and jmock dependencies to use <optional>true</option> instead of
    // <scope>test</scope>.
    // This is necessary because Base*TestCase classes are in src/main/java. If we move these
    // classes to their
    // own test module, this will no longer be necessary. For the first version of this mojo, it
    // seems easier
    // to follow the convention used in AppFuse rather than creating a test module and changing all
    // modules to
    // depend on it.

    // create properties based on dependencies while we're at it
    Set<String> projectProperties = new TreeSet<String>();

    for (Dependency dep : newDependencies) {
      if (dep.getArtifactId().equals("spring-test")
          || dep.getArtifactId().contains("jmock")
          || dep.getArtifactId().equals("junit")
          || dep.getArtifactId().equals("shale-test")) {
        dep.setOptional(true);
        dep.setScope(null);
      }
      String version = dep.getVersion();
      // trim off ${}
      if (version.startsWith("${")) {
        version = version.substring(2);
      }

      if (version.endsWith("}")) {
        version = version.substring(0, version.length() - 1);
      }
      projectProperties.add(version);
    }

    // add core as a dependency for modular wars
    if (project.getPackaging().equals("war") && project.hasParent()) {
      Dependency core = new Dependency();
      core.setGroupId("${project.parent.groupId}");
      core.setArtifactId("core");
      core.setVersion("${project.parent.version}");
      newDependencies.add(core);

      // workaround for JSF requiring JSP 2.1 - this is a true hack
      if (project.getProperties().getProperty("web.framework").equals("jsf")) {
        Dependency jsp21 = new Dependency();
        jsp21.setGroupId("javax.servlet.jsp");
        jsp21.setArtifactId("jsp-api");
        jsp21.setVersion("${jsp.version}");
        jsp21.setScope("provided");
        newDependencies.add(jsp21);

        // replace jsp.version property as well
        project.getOriginalModel().getProperties().setProperty("jsp.version", "2.1");
      }
    }

    Collections.sort(newDependencies, new BeanComparator("groupId"));

    project.getOriginalModel().setDependencies(newDependencies);

    Properties currentProperties = project.getOriginalModel().getProperties();

    Set<String> currentKeys = new LinkedHashSet<String>();
    for (Object key : currentProperties.keySet()) {
      currentKeys.add((String) key);
    }

    StringBuffer sortedProperties = new StringBuffer();

    Properties appfuseProperties = getAppFuseProperties();

    // holder for properties - stored in ThreadLocale
    Map<String, String> propertiesForPom = new LinkedHashMap<String, String>();

    for (String key : projectProperties) {
      // don't add property if it already exists in project
      if (!currentKeys.contains(key)) {
        String value = appfuseProperties.getProperty(key);

        // this happens when the version number is hard-coded
        if (value == null) {
          continue;
        }

        // hack for Tapestry depending on commons-pool (a.k.a. commons-dbcp 1.2.2)
        if ("tapestry".equals(project.getProperties().getProperty("web.framework"))
            && key.equals("commons.dbcp.version")) {
          value = "1.2.2";
        }

        if (value.contains("&amp;")) {
          value = "<![CDATA[" + value + "]]>";
        }

        sortedProperties
            .append("        <")
            .append(key)
            .append(">")
            .append(value)
            .append("</")
            .append(key)
            .append(">" + "\n");
        propertiesForPom.put(key, value);
      }
    }

    if (project.getPackaging().equals("pom") || project.hasParent()) {
      // store sorted properties in a thread local for later retrieval
      Map<String, String> properties = new LinkedHashMap<String, String>();
      if (propertiesContextHolder.get() != null) {
        properties = (LinkedHashMap) propertiesContextHolder.get();
      }

      for (String key : propertiesForPom.keySet()) {
        if (!properties.containsKey(key)) {
          properties.put(key, propertiesForPom.get(key));
        }
      }

      propertiesContextHolder.set(properties);
    }

    StringWriter writer = new StringWriter();

    try {
      project.writeOriginalModel(writer);

      File pom = new File("pom-fullsource.xml");

      if (pom.exists()) {
        pom.delete();
      }

      FileWriter fw = new FileWriter(pom);
      fw.write(writer.toString());
      fw.flush();
      fw.close();
    } catch (IOException ex) {
      getLog().error("Unable to create pom-fullsource.xml: " + ex.getMessage(), ex);
      throw new MojoFailureException(ex.getMessage());
    }

    log("Updated dependencies in pom.xml...");

    // I tried to use regex here, but couldn't get it to work - going with the old fashioned way
    // instead
    String pomXml = writer.toString();
    int startTag = pomXml.indexOf("\n  <dependencies>");

    String dependencyXml = pomXml.substring(startTag, pomXml.indexOf("</dependencies>", startTag));
    // change 2 spaces to 4
    dependencyXml = dependencyXml.replaceAll("  ", "    ");
    dependencyXml =
        "\n    <!-- Dependencies calculated by AppFuse when running full-source plugin -->"
            + dependencyXml;

    try {
      String packaging = project.getPackaging();
      String pathToPom = "pom.xml";
      if (project.hasParent()) {
        if (packaging.equals("jar")) {
          pathToPom = "core/" + pathToPom;
        } else if (packaging.equals("war")) {
          pathToPom = "web/" + pathToPom;
        }
      }

      String originalPom = FileUtils.readFileToString(new File(pathToPom), "UTF-8");
      // replace tabs with spaces (in case user has changed their pom.xml
      originalPom = originalPom.replace("\t", "    ");
      startTag = originalPom.indexOf("\n    <dependencies>");

      StringBuffer sb = new StringBuffer();
      sb.append(originalPom.substring(0, startTag));
      sb.append(dependencyXml);
      sb.append(originalPom.substring(originalPom.indexOf("</dependencies>", startTag)));

      String adjustedPom = sb.toString();

      // Calculate properties and add them to pom if not a modular project - otherwise properties
      // are added
      // near the end of this method from a threadlocal
      if (!project.getPackaging().equals("pom") && !project.hasParent()) {
        adjustedPom = addPropertiesToPom(adjustedPom, sortedProperties);
      }

      adjustedPom = adjustLineEndingsForOS(adjustedPom);

      FileUtils.writeStringToFile(
          new File(pathToPom), adjustedPom, "UTF-8"); // was pomWithProperties
    } catch (IOException ex) {
      getLog().error("Unable to write to pom.xml: " + ex.getMessage(), ex);
      throw new MojoFailureException(ex.getMessage());
    }

    boolean renamePackages = true;
    if (System.getProperty("renamePackages") != null) {
      renamePackages = Boolean.valueOf(System.getProperty("renamePackages"));
    }

    if (renamePackages && !project.getPackaging().equals("pom")) {
      log("Renaming packages to '" + project.getGroupId() + "'...");
      RenamePackages renamePackagesTool = new RenamePackages(project.getGroupId());
      if (project.hasParent()) {
        if (project.getPackaging().equals("jar")) {
          renamePackagesTool.setBaseDir("core/src");
        } else {
          renamePackagesTool.setBaseDir("web/src");
        }
      }

      renamePackagesTool.execute();
    }

    // when performing full-source on a modular project, add the properties to the root pom.xml at
    // the end
    if (project.getPackaging().equals("war") && project.hasParent()) {
      // store sorted properties in a thread local for later retrieval
      Map properties = propertiesContextHolder.get();
      // alphabetize the properties by key
      Set<String> propertiesToAdd = new TreeSet<String>(properties.keySet());

      StringBuffer calculatedProperties = new StringBuffer();

      for (String key : propertiesToAdd) {
        // don't add property if it already exists in project
        Set<Object> keysInProject = project.getParent().getOriginalModel().getProperties().keySet();
        if (!keysInProject.contains(key)) {
          String value = getAppFuseProperties().getProperty(key);

          if (value.contains("&amp;")) {
            value = "<![CDATA[" + value + "]]>";
          }

          calculatedProperties.append("        <");
          calculatedProperties.append(key);
          calculatedProperties.append(">");
          calculatedProperties.append(value);
          calculatedProperties.append("</");
          calculatedProperties.append(key);
          calculatedProperties.append(">");
          calculatedProperties.append("\n");
        }
      }

      try {
        String originalPom = FileUtils.readFileToString(new File("pom.xml"), "UTF-8");

        // Move modules to build section.
        originalPom = originalPom.replaceAll("  <modules>", "");
        // Because I hate f*****g regex.
        originalPom = originalPom.replaceAll("    <module>.*?</module>", "");
        originalPom = originalPom.replaceAll("  </modules>", "");

        originalPom =
            originalPom.replace(
                "<repositories>",
                "<modules>\n"
                    + "        <module>core</module>\n"
                    + "        <module>web</module>\n"
                    + "    </modules>\n\n    <repositories>");

        String pomWithProperties = addPropertiesToPom(originalPom, calculatedProperties);

        FileUtils.writeStringToFile(new File("pom.xml"), pomWithProperties, "UTF-8");
      } catch (IOException ex) {
        getLog().error("Unable to read root pom.xml: " + ex.getMessage(), ex);
        throw new MojoFailureException(ex.getMessage());
      }
    }

    // cleanup so user isn't aware that files were created
    File pom = new File("pom-fullsource.xml");

    if (pom.exists()) {
      pom.delete();
    }
  }
コード例 #14
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;
  }
コード例 #15
0
ファイル: YangProjectWizard.java プロジェクト: cyqw/yang-ide
  public void updateModel(
      Model model, String yangVersion, List<CodeGeneratorConfig> generators, String yangRoot) {
    // Model model = super.getModel();
    model.setBuild(new Build());
    Plugin plugin = new Plugin();
    plugin.setGroupId("org.opendaylight.yangtools");
    plugin.setArtifactId("yang-maven-plugin");
    plugin.setVersion(yangVersion);

    for (CodeGeneratorConfig genConf : generators) {
      Dependency dependency = new Dependency();
      dependency.setGroupId(genConf.getGroupId());
      dependency.setArtifactId(genConf.getArtifactId());
      dependency.setVersion(genConf.getVersion());
      dependency.setType("jar");
      plugin.addDependency(dependency);
    }

    PluginExecution pluginExecution = new PluginExecution();
    pluginExecution.setId("generate-sources");
    pluginExecution.addGoal("generate-sources");
    Xpp3Dom config = new Xpp3Dom("configuration");

    Xpp3Dom codeGenerators = new Xpp3Dom("codeGenerators");
    for (CodeGeneratorConfig genConf : generators) {
      Xpp3Dom generator = new Xpp3Dom("generator");
      generator.addChild(createSingleParameter("codeGeneratorClass", genConf.getGenClassName()));
      generator.addChild(createSingleParameter("outputBaseDir", genConf.getGenOutputDirectory()));
      codeGenerators.addChild(generator);
    }
    config.addChild(createSingleParameter("yangFilesRootDir", yangRoot));
    config.addChild(codeGenerators);
    config.addChild(createSingleParameter("inspectDependencies", "false"));
    pluginExecution.setConfiguration(config);

    plugin.addExecution(pluginExecution);
    model.getBuild().addPlugin(plugin);
    model.addPluginRepository(
        createRepoParameter(
            "opendaylight-release",
            "http://nexus.opendaylight.org/content/repositories/opendaylight.release/"));
    model.addPluginRepository(
        createRepoParameter(
            "opendaylight-snapshot",
            "http://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/"));
    model.addRepository(
        createRepoParameter(
            "opendaylight-release",
            "http://nexus.opendaylight.org/content/repositories/opendaylight.release/"));
    model.addRepository(
        createRepoParameter(
            "opendaylight-snapshot",
            "http://nexus.opendaylight.org/content/repositories/opendaylight.snapshot/"));

    model.getProperties().put("maven.compiler.source", "1.7");
    model.getProperties().put("maven.compiler.target", "1.7");

    Dependency dependency2 = new Dependency();
    dependency2.setGroupId("org.opendaylight.yangtools");
    dependency2.setArtifactId("yang-binding");
    dependency2.setVersion(yangVersion);
    dependency2.setType("jar");
    model.addDependency(dependency2);
  }
コード例 #16
0
ファイル: Project.java プロジェクト: sveryovka/polyglot-maven
  public Model toMavenModel() {
    Model model = new Model();
    model.setBuild(new Build());
    model.setDescription(description);
    model.setUrl(url);
    model.setName(projectId.getArtifact());
    model.setGroupId(projectId.getGroup());
    model.setVersion(projectId.getVersion());
    model.setArtifactId(projectId.getArtifact());
    model.setModelVersion("4.0.0");

    // parent
    if (parent != null) {
      model.setParent(parent);
    }

    model.setPackaging(packaging);

    if (properties != null) {
      Properties modelProperties = new Properties();
      for (Property p : properties) {
        modelProperties.setProperty(p.getKey(), p.getValue());
      }
      model.setProperties(modelProperties);
    }

    // Add jar repository urls.
    if (null != repositories) {
      for (String repoUrl : repositories.getRepositories()) {
        Repository repository = new Repository();
        repository.setId(Integer.toString(repoUrl.hashCode()));
        repository.setUrl(repoUrl);
        model.addRepository(repository);
      }
    }

    // Add dependency management
    if (overrides != null) {
      DependencyManagement depMan = new DependencyManagement();
      for (Id dep : overrides) {
        Dependency dependency = new Dependency();
        dependency.setGroupId(dep.getGroup());
        dependency.setArtifactId(dep.getArtifact());
        dependency.setVersion(dep.getVersion());
        // JVZ: We need to parse these
        dependency.setType("jar");

        if (null != dep.getClassifier()) {
          dependency.setClassifier(dep.getClassifier());
        }
        depMan.addDependency(dependency);
      }
      model.setDependencyManagement(depMan);
    }

    // Add project dependencies.
    if (deps != null) {
      for (Id dep : deps) {
        Dependency dependency = new Dependency();
        dependency.setGroupId(dep.getGroup());
        dependency.setArtifactId(dep.getArtifact());
        dependency.setVersion(dep.getVersion());
        // JVZ: We need to parse these
        dependency.setType("jar");

        if (null != dep.getClassifier()) {
          dependency.setClassifier(dep.getClassifier());
        }
        model.addDependency(dependency);
      }
    }

    if (modules != null) {
      model.setModules(modules);
    }

    if (pluginOverrides != null) {
      PluginManagement management = new PluginManagement();
      management.setPlugins(pluginOverrides);
      model.getBuild().setPluginManagement(management);
    }

    if (plugins != null) {
      model.getBuild().setPlugins(plugins);
    }

    // Optional source dirs customization.
    if (dirs != null) {
      Build build = new Build();
      String srcDir = dirs.get("src");
      String testDir = dirs.get("test");

      if (null != srcDir) build.setSourceDirectory(srcDir);

      if (null != testDir) build.setTestSourceDirectory(testDir);

      model.setBuild(build);
    }

    if (null != scm) {
      Scm scm = new Scm();
      scm.setConnection(this.scm.getConnection());
      scm.setDeveloperConnection(this.scm.getDeveloperConnection());
      scm.setUrl(this.scm.getUrl());

      model.setScm(scm);
    }

    return model;
  }
コード例 #17
0
ファイル: MavenUtils.java プロジェクト: prabalrakshit/fuseide
  /**
   * checks if we need to add a maven dependency for the chosen component and inserts it into the
   * pom.xml if needed
   */
  public static void updateMavenDependencies(
      List<org.fusesource.ide.camel.model.catalog.Dependency> compDeps) throws CoreException {
    RiderDesignEditor editor = Activator.getDiagramEditor();
    if (editor == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because Editor instance can't be determined.");
      return;
    }

    IProject project = editor.getCamelContextFile().getProject();
    if (project == null) {
      Activator.getLogger()
          .error(
              "Unable to add component dependencies because selected project can't be determined.");
      return;
    }

    IPath pomPathValue =
        project.getProject().getRawLocation() != null
            ? project.getProject().getRawLocation().append("pom.xml")
            : ResourcesPlugin.getWorkspace()
                .getRoot()
                .getLocation()
                .append(project.getFullPath().append("pom.xml"));
    String pomPath = pomPathValue.toOSString();
    final File pomFile = new File(pomPath);
    final Model model = MavenPlugin.getMaven().readModel(pomFile);

    // then check if component dependency is already a dep
    ArrayList<org.fusesource.ide.camel.model.catalog.Dependency> missingDeps =
        new ArrayList<org.fusesource.ide.camel.model.catalog.Dependency>();
    List<Dependency> deps = model.getDependencies();
    for (org.fusesource.ide.camel.model.catalog.Dependency conDep : compDeps) {
      boolean found = false;
      for (Dependency pomDep : deps) {
        if (pomDep.getGroupId().equalsIgnoreCase(conDep.getGroupId())
            && pomDep.getArtifactId().equalsIgnoreCase(conDep.getArtifactId())) {
          // check for correct version
          if (pomDep.getVersion().equalsIgnoreCase(conDep.getVersion()) == false) {
            // not the correct version - change it to fit
            pomDep.setVersion(conDep.getVersion());
          }
          found = true;
          break;
        }
      }
      if (!found) {
        missingDeps.add(conDep);
      }
    }

    for (org.fusesource.ide.camel.model.catalog.Dependency missDep : missingDeps) {
      Dependency dep = new Dependency();
      dep.setGroupId(missDep.getGroupId());
      dep.setArtifactId(missDep.getArtifactId());
      dep.setVersion(missDep.getVersion());
      model.addDependency(dep);
    }

    if (missingDeps.size() > 0) {
      OutputStream os = null;
      try {
        os = new BufferedOutputStream(new FileOutputStream(pomFile));
        MavenPlugin.getMaven().writeModel(model, os);
        IFile pomIFile = project.getProject().getFile("pom.xml");
        if (pomIFile != null) {
          pomIFile.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        }
      } catch (Exception ex) {
        Activator.getLogger().error(ex);
      } finally {
        try {
          if (os != null) {
            os.close();
          }
        } catch (IOException e) {
          Activator.getLogger().error(e);
        }
      }
    }
  }
コード例 #18
0
    /**
     * Build FO documents from DocBook XML sources, including fonts.
     *
     * @param baseConfiguration Common configuration for all executions
     * @param format Specific output format (pdf, rtf)
     * @throws MojoExecutionException Failed to build the output.
     */
    void buildFO(final ArrayList<MojoExecutor.Element> baseConfiguration, final String format)
        throws MojoExecutionException {
      if (!(format.equalsIgnoreCase("pdf") || format.equalsIgnoreCase("rtf"))) {
        throw new MojoExecutionException(
            "Output format " + format + " is not supported." + " Use either pdf or rtf.");
      }

      ArrayList<MojoExecutor.Element> cfg = new ArrayList<MojoExecutor.Element>();
      cfg.addAll(baseConfiguration);
      cfg.add(
          element(
              name("foCustomization"), FilenameUtils.separatorsToUnix(foCustomization.getPath())));

      // If you update this list, also see copyFonts().
      String fontDir = FilenameUtils.separatorsToUnix(fontsDirectory.getPath());
      cfg.add(
          element(
              name("fonts"),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSans.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSans-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansCondensed-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansCondensed-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSans-Oblique.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSans-Oblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSans"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansCondensed-BoldOblique.ttf"),
                  element(
                      name("metricsFile"),
                      fontDir + "/DejaVuSansCondensed-BoldOblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-Oblique.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSansMono-Oblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSansMono"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSansMono-BoldOblique.ttf"),
                  element(
                      name("metricsFile"), fontDir + "/DejaVuSansMono-BoldOblique-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "normal"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSerif.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerif-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "normal"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSerifCondensed-Bold.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerifCondensed-Bold-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "italic"),
                  element(name("weight"), "normal"),
                  element(name("embedFile"), fontDir + "/DejaVuSerif-Italic.ttf"),
                  element(name("metricsFile"), fontDir + "/DejaVuSerif-Italic-metrics.xml")),
              element(
                  name("font"),
                  element(name("name"), "DejaVuSerif"),
                  element(name("style"), "italic"),
                  element(name("weight"), "bold"),
                  element(name("embedFile"), fontDir + "/DejaVuSerifCondensed-BoldItalic.ttf"),
                  element(
                      name("metricsFile"),
                      fontDir + "/DejaVuSerifCondensed-BoldItalic-metrics.xml"))));

      Set<String> docNames = DocUtils.getDocumentNames(xmlSourceDirectory, getDocumentSrcName());
      if (docNames.isEmpty()) {
        throw new MojoExecutionException("No document names found.");
      }

      // When using generated sources, copy the images manually.
      if (xmlSourceDirectory != getDocbkxSourceDirectory()) {
        for (String docName : docNames) {
          File srcDir = new File(imageSourceDirectory, docName + File.separator + "images");
          File destDir = new File(xmlSourceDirectory, docName + File.separator + "images");
          try {
            if (srcDir.exists()) {
              FileUtils.copyDirectory(srcDir, destDir);
            }
          } catch (IOException e) {
            throw new MojoExecutionException(
                "Failed to copy images from " + srcDir + " to " + destDir);
          }
        }
      }

      for (String docName : docNames) {
        cfg.add(element(name("includes"), docName + "/" + getDocumentSrcName()));

        // Permit hyphenation.
        Dependency offo = new Dependency();
        offo.setGroupId("net.sf.offo");
        offo.setArtifactId("fop-hyph");
        offo.setVersion("1.2");
        offo.setScope("runtime");
        Plugin plugin =
            plugin(
                groupId("com.agilejava.docbkx"),
                artifactId("docbkx-maven-plugin"),
                version(getDocbkxVersion()));
        plugin.addDependency(offo);

        executeMojo(
            plugin,
            goal("generate-" + format),
            configuration(cfg.toArray(new Element[0])),
            executionEnvironment(getProject(), getSession(), getPluginManager()));

        // Avoid each new document overwriting the last.
        File file =
            new File(
                getDocbkxOutputDirectory(),
                format
                    + File.separator
                    + FilenameUtils.getBaseName(getDocumentSrcName())
                    + "."
                    + format);
        renameDocument(file, docName);
      }
    }