コード例 #1
0
  private void initDefaults() {
    RemoteRepository repo = new RemoteRepository();
    repo.setProject(project);
    repo.setId("central");
    repo.setUrl("http://repo1.maven.org/maven2/");
    project.addReference(Names.ID_CENTRAL, repo);

    repo = new RemoteRepository();
    repo.setProject(project);
    repo.setRefid(new Reference(project, Names.ID_CENTRAL));
    RemoteRepositories repos = new RemoteRepositories();
    repos.setProject(project);
    repos.addRemoterepo(repo);
    project.addReference(Names.ID_DEFAULT_REPOS, repos);

    // resolve maven.repo.local only once relative to project, as the basedir may change for <ant>
    // tasks
    String localRepoResolved = project.getProperty("maven.repo.local.resolved");
    if (localRepoResolved != null) {
      mavenRepoDirFromProperty = new File(localRepoResolved);
    } else {
      String mavenRepoProperty = project.getProperty("maven.repo.local");
      if (mavenRepoProperty != null) {
        mavenRepoDirFromProperty = project.resolveFile(mavenRepoProperty);
        project.setProperty(
            "maven.repo.local.resolved", mavenRepoDirFromProperty.getAbsolutePath());
      }
    }
  }
 /**
  * Prepares a command line argument object for use with the appclient exec task that uses the
  * default set of arguments: the default location and name for the retreived app client jar file.
  *
  * @param exec the ExecTask with which the command line should be associated
  * @return the argument, associated with the exec task, and set to invoke the gen'd app client
  */
 protected Commandline.Argument prepareRunCommandlineArg(ExecTask exec) {
   Commandline.Argument arg = exec.createArg();
   String archiveDir = project.getProperty("archivedir");
   String testName = project.getProperty("testName");
   arg.setLine("-client " + archiveDir + "/" + testName + "Client.jar");
   return arg;
 }
コード例 #3
0
ファイル: JSystemMojo.java プロジェクト: Top-Q/jsystem
 private void executeSingleScenario(final File scenarioFile, final Project p) {
   getLog()
       .info(
           "Executing scenario "
               + scenarioFile.getName()
               + " with sut "
               + p.getProperty("sutFile"));
   try {
     p.fireBuildStarted();
     p.init();
     ProjectHelper helper = ProjectHelper.getProjectHelper();
     p.addReference("ant.projectHelper", helper);
     helper.parse(p, scenarioFile);
     p.executeTarget(p.getDefaultTarget());
   } catch (Exception e) {
     getLog().error("Failed to execute scenario " + scenarioFile.getName());
     getLog().error(e);
   } finally {
     p.fireBuildFinished(null);
   }
   getLog()
       .info(
           "Execution of scenario "
               + scenarioFile.getName()
               + " with sut "
               + p.getProperty("sutFile")
               + " has ended");
   getLog().info("------------------------------------------------------------------------");
 }
コード例 #4
0
ファイル: JUnitTest.java プロジェクト: saeg/experiments
  public boolean shouldRun(Project p) {
    if (ifProperty != null && p.getProperty(ifProperty) == null) {
      return false;
    } else if (unlessProperty != null && p.getProperty(unlessProperty) != null) {
      return false;
    }

    return true;
  }
コード例 #5
0
 /** Returns true if the define's if and unless conditions (if any) are satisfied. */
 public boolean isActive(org.apache.tools.ant.Project p) {
   if (value == null) {
     return false;
   }
   if (ifCond != null && p.getProperty(ifCond) == null) {
     return false;
   } else if (unlessCond != null && p.getProperty(unlessCond) != null) {
     return false;
   }
   return true;
 }
コード例 #6
0
  /**
   * transformation
   *
   * @throws BuildException exception if something goes wrong with the transformation.
   */
  public void transform() throws BuildException {
    checkOptions();
    Project project = task.getProject();

    TempFile tempFileTask = new TempFile();
    tempFileTask.bindToOwner(task);

    XSLTProcess xsltTask = new XSLTProcess();
    xsltTask.bindToOwner(task);

    xsltTask.setXslResource(getStylesheet());

    // acrobatic cast.
    xsltTask.setIn(((XMLResultAggregator) task).getDestinationFile());
    File outputFile = null;
    if (format.equals(FRAMES)) {
      String tempFileProperty = getClass().getName() + String.valueOf(counter++);
      File tmp =
          FILE_UTILS.resolveFile(project.getBaseDir(), project.getProperty("java.io.tmpdir"));
      tempFileTask.setDestDir(tmp);
      tempFileTask.setProperty(tempFileProperty);
      tempFileTask.execute();
      outputFile = new File(project.getProperty(tempFileProperty));
    } else {
      outputFile = new File(toDir, "junit-noframes.html");
    }
    xsltTask.setOut(outputFile);
    for (Iterator i = params.iterator(); i.hasNext(); ) {
      XSLTProcess.Param param = (XSLTProcess.Param) i.next();
      XSLTProcess.Param newParam = xsltTask.createParam();
      newParam.setProject(task.getProject());
      newParam.setName(param.getName());
      newParam.setExpression(param.getExpression());
    }
    XSLTProcess.Param paramx = xsltTask.createParam();
    paramx.setProject(task.getProject());
    paramx.setName("output.dir");
    paramx.setExpression(toDir.getAbsolutePath());
    final long t0 = System.currentTimeMillis();
    try {
      xsltTask.execute();
    } catch (Exception e) {
      throw new BuildException("Errors while applying transformations: " + e.getMessage(), e);
    }
    final long dt = System.currentTimeMillis() - t0;
    task.log("Transform time: " + dt + "ms");
    if (format.equals(FRAMES)) {
      Delete delete = new Delete();
      delete.bindToOwner(task);
      delete.setFile(outputFile);
      delete.execute();
    }
  }
コード例 #7
0
  /**
   * Loads the bundle archives built from this project.
   *
   * <p>The jar files to analyze is determined from:
   *
   * <ul>
   *   <li>The project property named <code>jarfile</code>. This is used to create a file set with
   *       dir set to the directory part of the property value that selects the file named by the
   *       file name part of the property value.
   *   <li>The project properties <code>jars.dir</code> and <code>jardir.name</code> (set by all
   *       projects based on <code>bundlebuild.xml</code>. The file set derived from these
   *       properties will have its dir-property set to the value <code>jars.dir</code> and an
   *       includes pattern of the form <code>${jardir.name}/&ast;&ast;/&ast;.jar</code>.
   *   <li>The file set with id <code>docbuild.jarfiles</code>.
   * </ul>
   *
   * @return bundle archives object holding the bundle archives selected by the file sets described
   *     above or null if no file set was defined.
   */
  private BundleArchives getBundleArchives() {
    final List<ResourceCollection> fileSets = new ArrayList<ResourceCollection>();
    final Project proj = getProject();

    // File set for bundlebuild.xml properties
    final String jarsDir = proj.getProperty("jars.dir");
    if (null != jarsDir && 0 < jarsDir.length()) {
      final File file = new File(jarsDir);
      if (file.exists()) {
        final FileSet fileSet = new FileSet();
        fileSet.setProject(proj);
        fileSet.setDir(file);
        final FilenameSelector fns = new FilenameSelector();
        fns.setName(proj.getProperty("jardir.name") + "/**/*.jar");
        fileSet.add(fns);
        fileSet.setExcludes("**/*-source.jar,**/*-javadoc.jar");
        fileSets.add(fileSet);
        log("Found build results (bundlebuild): " + fileSet, Project.MSG_DEBUG);
      }
    }

    // File set for jarfile-property (e.g., framework.jar)
    final String jarfile = proj.getProperty("jarfile");
    if (null != jarfile && 0 < jarfile.length()) {
      final File file = new File(jarfile);
      if (file.exists()) {
        final FileSet fileSet = new FileSet();
        fileSet.setProject(proj);
        fileSet.setDir(file.getParentFile());
        final FilenameSelector fns = new FilenameSelector();
        fns.setName(file.getName());
        fileSet.add(fns);
        fileSets.add(fileSet);
        log("Found build results (jarfile): " + fileSet, Project.MSG_DEBUG);
      }
    }

    // FileSet defined with id (for bundle overview documentation).
    final FileSet docbuildeFileSet = (FileSet) proj.getReference("docbuild.jarfiles");
    if (null != docbuildeFileSet) {
      fileSets.add(docbuildeFileSet);
      log("Found build results (docbuild.jarfiles): " + docbuildeFileSet, Project.MSG_DEBUG);
    }

    if (0 < fileSets.size()) {
      final BundleArchives bas = new BundleArchives(this, fileSets, true);
      bas.doProviders();
      return bas;
    }
    return null;
  }
コード例 #8
0
 private boolean isOffline() {
   String prop = project.getProperty(Names.PROPERTY_OFFLINE);
   if (prop != null) {
     return Boolean.parseBoolean(prop);
   }
   return getSettings().isOffline();
 }
コード例 #9
0
ファイル: SshCommand.java プロジェクト: epsilon/aws-tasks
 public boolean isIfFulfilled(Project project) {
   String property = project.getProperty(_if);
   if (_if == null || _if.isEmpty()) {
     return true;
   }
   return property != null && "true".equals(property.trim());
 }
コード例 #10
0
 /**
  * Get Property
  *
  * @param property name
  * @return The property value
  */
 public String getProperty(String property) {
   Project currentProject = getProject();
   if (currentProject != null) {
     return currentProject.getProperty(property);
   } else {
     return properties.getProperty(property);
   }
 }
コード例 #11
0
  @Override
  protected String getMessage(String urlString) throws Exception {
    Project project = getProject(urlString, urlString.substring("file:".length()));

    GitHubJobMessageUtil.getFailedJobMessage(project);

    return project.getProperty("report.html.content");
  }
コード例 #12
0
 /** Returns true if the define's if and unless conditions (if any) are satisfied. */
 public boolean isActive(final org.apache.tools.ant.Project p) {
   if (p == null) {
     throw new NullPointerException("p");
   }
   if (this.ifCond != null) {
     final String ifValue = p.getProperty(this.ifCond);
     if (ifValue != null) {
       if (ifValue.equals("no") || ifValue.equals("false")) {
         throw new BuildException(
             "property "
                 + this.ifCond
                 + " used as if condition has value "
                 + ifValue
                 + " which suggests a misunderstanding of if attributes");
       }
     } else {
       return false;
     }
   }
   if (this.unlessCond != null) {
     final String unlessValue = p.getProperty(this.unlessCond);
     if (unlessValue != null) {
       if (unlessValue.equals("no") || unlessValue.equals("false")) {
         throw new BuildException(
             "property "
                 + this.unlessCond
                 + " used as unless condition has value "
                 + unlessValue
                 + " which suggests a misunderstanding of unless attributes");
       }
       return false;
     }
   }
   if (isReference()) {
     final LibrarySet master = (LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet");
     return master.isActive(this.project);
   }
   if (this.libnames.length == 0) {
     p.log("libnames not specified or empty.", Project.MSG_WARN);
     return false;
   }
   return true;
 }
コード例 #13
0
  private String links() {
    final Project proj = getProject();
    final StringBuffer buf = new StringBuffer();

    for (int i = 0; ; i++) {
      final String id = proj.getProperty(LINK_ID + i);

      if (id == null) {
        break;
      }

      final String type = proj.getProperty(LINK_TYPE + i);
      if (type == null) {
        throw new BuildException("must set htdocs.link.type." + i);
      }

      if (type.equals("separator")) {
        buf.append("<p></p>");

      } else if (type.equals("link")) {

        final String name = proj.getProperty(LINK_NAME + i);
        final String url = proj.getProperty(LINK_URL + i);
        if (name == null) {
          throw new BuildException("Name not set for htdocs.link.url." + i);
        }

        String cssClass = null;

        if (disable != null && disable.equals(id)) {
          cssClass = getProject().getProperty(CSS_CLASS_DISABLED);
        } else {
          cssClass = getProject().getProperty(CSS_CLASS_ENABLED);
        }

        buf.append("<a class=\"" + cssClass + "\" href=\"" + url + "\">" + name + "</a><br/>\n");
      } else {
        throw new BuildException("Do not recognize type " + type);
      }
    }

    return buf.toString();
  }
コード例 #14
0
  private File getDefaultLocalRepoDir() {
    if (mavenRepoDirFromProperty != null) {
      return mavenRepoDirFromProperty;
    }

    Settings settings = getSettings();
    if (settings.getLocalRepository() != null) {
      return new File(settings.getLocalRepository());
    }

    return new File(new File(project.getProperty("user.home"), ".m2"), "repository");
  }
コード例 #15
0
ファイル: GitHubUtil.java プロジェクト: hawky-4s-/github-ant
  public static Credentials getCredentials(Project project) {
    String user = null;
    String password = null;
    String oauth = null;

    Credentials credentials;

    // check userhome/.github
    Properties properties = GitHubUtil.getProperties(null);

    // check dir specified by property 'github.ant.filepath'
    if (properties == null && project != null) {
      // check dir/.github
      try {
        String filePath = project.getUserProperty("github.ant.filepath");
        properties = GitHubUtil.getProperties(filePath);
      } catch (NullPointerException e) {
        // ignore: userproperty does not exist.
      }
    }

    if (properties != null) {
      user = properties.getProperty("github.ant.user");
      password = properties.getProperty("github.ant.password");
      oauth = properties.getProperty("github.ant.oauth");
    } else {
      // try to resolve properties from commandline
      try {
        user = project.getProperty("github.ant.user");
        password = project.getProperty("github.ant.password");
        oauth = project.getProperty("github.ant.oauth");
      } catch (NullPointerException e) {

      }
    }

    return Credentials.createNewCredentials(user, password, oauth);
  }
コード例 #16
0
  private String getUserAgent() {
    StringBuilder buffer = new StringBuilder(128);

    buffer.append("Apache-Ant/").append(project.getProperty("ant.version"));
    buffer.append(" (");
    buffer.append("Java ").append(System.getProperty("java.version"));
    buffer.append("; ");
    buffer
        .append(System.getProperty("os.name"))
        .append(" ")
        .append(System.getProperty("os.version"));
    buffer.append(")");
    buffer.append(" Aether");

    return buffer.toString();
  }
  /**
   * Constructs an ExecTask instance, linked to the current project, for running the client. This
   * implementation prepares the exec task so it will run the appclient script.
   *
   * @return ExecTask initialized for running the appclient script to execute the generated and
   *     retrieved app client
   */
  protected ExecTask prepareRunExecTask() {
    /*
     This is the ant excerpt imitated by the exec task built by this method:

     <exec executable="${APPCLIENT}" resultproperty="result" failonerror="false" output="${build}/${log.id}.output.log">
                <arg line="-client ${archivedir}/${testName}Client.jar"/>
            </exec>
    */
    ExecTask exec = new ExecTask();
    exec.setProject(project);
    String appclientValue = project.getProperty("APPCLIENT");
    exec.setExecutable(appclientValue);
    exec.setFailonerror(false);
    exec.setTaskName("runclient");
    return exec;
  }
コード例 #18
0
ファイル: Database.java プロジェクト: fedor4ever/linux_build
  /**
   * Get the list of all Ant files we want to process. These can be project and antlib files.
   *
   * @return antFiles a list of ant files to be processed
   */
  public ArrayList getAntFiles(Project project, boolean homeOnly) {
    ArrayList antFiles = new ArrayList();

    Map targets = project.getTargets();
    Iterator targetsIter = targets.values().iterator();

    String projectHome = null;
    try {
      projectHome = new File(project.getProperty("helium.dir")).getCanonicalPath();

      while (targetsIter.hasNext()) {
        Target target = (Target) targetsIter.next();
        String projectPath = new File(target.getLocation().getFileName()).getCanonicalPath();

        if (!antFiles.contains(projectPath)) {
          if (homeOnly) {
            if (!projectPath.contains(projectHome)) {
              antFiles.add(projectPath);
            }
          } else antFiles.add(projectPath);
        }
      }

      if (rc != null) {
        Iterator extraFilesIter = rc.iterator();
        while (extraFilesIter.hasNext()) {
          FileResource f = (FileResource) extraFilesIter.next();
          String extrafile = f.getFile().getCanonicalPath();

          if (!antFiles.contains(f.toString()) && !f.getFile().getName().startsWith("test_")) {
            if (homeOnly) {
              if (!extrafile.contains(projectHome)) {
                antFiles.add(extrafile);
              }
            } else antFiles.add(extrafile);
          }
        }
      }

    } catch (Exception e) {
      log(e.getMessage(), Project.MSG_ERR);
      e.printStackTrace();
    }
    return antFiles;
  }
コード例 #19
0
  public static String resolveExecutableAbsolutePath(
      Project project, String executableName, String propertyName) {
    if (executableName == null) executableName = executableName();

    // If qmakebinary is already absolute use it "/somedir/bin/qmake"
    if (executableName != null) {
      File file = new File(executableName);
      if (file.isAbsolute()) return file.getAbsolutePath();

      if (propertyName != null) {
        // try in ${qtjambi.qt.bindir} if it is configured (caller supplies
        // propertyName=Constants.BINDIR)
        // try in ${tools.qt.bindir} if it is configured (caller supplies
        // propertyName=Constants.TOOLS_BINDIR)
        String binDir = project.getProperty(propertyName);
        if (binDir != null) {
          File exeFile = new File(binDir, executableName);
          if (exeFile.isFile()) {
            // FIXME: Prepend 'binDir' to $PATH (so qmake can find moc)
            return exeFile.getAbsolutePath();
          }
        }
      }

      // try in $QTDIR/bin if it is configured
      try {
        String qtDir = System.getenv("QTDIR");
        if (qtDir != null) {
          File exeFile = new File(qtDir, "bin" + File.separator + executableName);
          if (exeFile.isFile()) {
            // FIXME: Prepend '$QTDIR/bin' to $PATH (so qmake can find moc)
            return exeFile.getAbsolutePath();
          }
        }
      } catch (SecurityException eat) {
      }
    }

    // otherwise search $PATH
    return Util.LOCATE_EXEC(executableName, (String) null, null).getAbsolutePath();
  }
コード例 #20
0
  @Override
  public void execute() throws BuildException {
    Project antProject = getProject();

    // get the SDK location
    String sdkLocation = antProject.getProperty(ProjectProperties.PROPERTY_SDK);

    // check if it's valid and exists
    if (sdkLocation == null || sdkLocation.length() == 0) {
      throw new BuildException("SDK Location is not set.");
    }

    File sdk = new File(sdkLocation);
    if (sdk.isDirectory() == false) {
      throw new BuildException(String.format("SDK Location '%s' is not valid.", sdkLocation));
    }

    // get the target property value
    String targetHashString = antProject.getProperty(ProjectProperties.PROPERTY_TARGET);
    if (targetHashString == null) {
      throw new BuildException("Android Target is not set.");
    }

    // load up the sdk targets.
    final ArrayList<String> messages = new ArrayList<String>();
    SdkManager manager =
        SdkManager.createManager(
            sdkLocation,
            new ISdkLog() {
              public void error(Throwable t, String errorFormat, Object... args) {
                if (errorFormat != null) {
                  messages.add(String.format("Error: " + errorFormat, args));
                }
                if (t != null) {
                  messages.add("Error: " + t.getMessage());
                }
              }

              public void printf(String msgFormat, Object... args) {
                messages.add(String.format(msgFormat, args));
              }

              public void warning(String warningFormat, Object... args) {
                messages.add(String.format("Warning: " + warningFormat, args));
              }
            });

    if (manager == null) {
      // since we failed to parse the SDK, lets display the parsing output.
      for (String msg : messages) {
        System.out.println(msg);
      }
      throw new BuildException("Failed to parse SDK content.");
    }

    // resolve it
    IAndroidTarget androidTarget = manager.getTargetFromHashString(targetHashString);

    if (androidTarget == null) {
      throw new BuildException(String.format("Unable to resolve target '%s'", targetHashString));
    }

    // display it
    System.out.println("Project Target: " + androidTarget.getName());
    if (androidTarget.isPlatform() == false) {
      System.out.println("Vendor: " + androidTarget.getVendor());
    }
    System.out.println("Platform Version: " + androidTarget.getApiVersionName());
    System.out.println("API level: " + androidTarget.getApiVersionNumber());

    // sets up the properties to find android.jar/framework.aidl
    String androidJar = androidTarget.getPath(IAndroidTarget.ANDROID_JAR);
    String androidAidl = androidTarget.getPath(IAndroidTarget.ANDROID_AIDL);
    antProject.setProperty(PROPERTY_ANDROID_JAR, androidJar);
    antProject.setProperty(PROPERTY_ANDROID_AIDL, androidAidl);

    // sets up the boot classpath

    // create the Path object
    Path bootclasspath = new Path(antProject);

    // create a PathElement for the framework jar
    PathElement element = bootclasspath.createPathElement();
    element.setPath(androidJar);

    // create PathElement for each optional library.
    IOptionalLibrary[] libraries = androidTarget.getOptionalLibraries();
    if (libraries != null) {
      HashSet<String> visitedJars = new HashSet<String>();
      for (IOptionalLibrary library : libraries) {
        String jarPath = library.getJarPath();
        if (visitedJars.contains(jarPath) == false) {
          visitedJars.add(jarPath);

          element = bootclasspath.createPathElement();
          element.setPath(library.getJarPath());
        }
      }
    }

    // finally sets the path in the project with a reference
    antProject.addReference(REF_CLASSPATH, bootclasspath);

    // find the file to import, and import it.
    String templateFolder = androidTarget.getPath(IAndroidTarget.TEMPLATES);

    // make sure the file exists.
    File templates = new File(templateFolder);
    if (templates.isDirectory() == false) {
      throw new BuildException(
          String.format("Template directory '%s' is missing.", templateFolder));
    }

    // now check the rules file exists.
    File rules = new File(templateFolder, ANDROID_RULES);
    if (rules.isFile() == false) {
      throw new BuildException(String.format("Build rules file '%s' is missing.", templateFolder));
    }

    // set the file location to import
    setFile(rules.getAbsolutePath());

    // and import it
    super.execute();
  }
コード例 #21
0
ファイル: SDK.java プロジェクト: petrep/liferay-ide
  public Map<String, Object> getBuildProperties(final boolean reload) throws CoreException {
    final Project project = new Project();

    Map<String, Object> sdkProperties = buildPropertiesCache.get(getLocation().toPortableString());

    try {
      if (sdkProperties == null || reload == true) {
        project.setBaseDir(new File(getLocation().toPortableString()));
        project.setSystemProperties();

        final Property envTask = new Property();
        envTask.setProject(project);
        envTask.setEnvironment("env");
        envTask.execute();

        loadPropertiesFile(project, "build." + project.getProperty("user.name") + ".properties");
        loadPropertiesFile(
            project, "build." + project.getProperty("env.COMPUTERNAME") + ".properties");
        loadPropertiesFile(project, "build." + project.getProperty("env.HOST") + ".properties");
        loadPropertiesFile(project, "build." + project.getProperty("env.HOSTNAME") + ".properties");
        loadPropertiesFile(project, "build.properties");

        if (project.getProperty("app.server.type") == null) {
          throw new CoreException(
              SDKCorePlugin.createErrorStatus(
                  "Missing ${app.server.type} setting in build.properties file."));
        }

        final Map<String, String> propertyCopyList = new HashMap<String, String>();
        propertyCopyList.put(
            "app.server." + project.getProperty("app.server.type") + ".dir", "app.server.dir");
        propertyCopyList.put(
            "app.server." + project.getProperty("app.server.type") + ".deploy.dir",
            "app.server.deploy.dir");
        propertyCopyList.put(
            "app.server." + project.getProperty("app.server.type") + ".lib.global.dir",
            "app.server.lib.global.dir");
        propertyCopyList.put(
            "app.server." + project.getProperty("app.server.type") + ".portal.dir",
            "app.server.portal.dir");

        for (String key : propertyCopyList.keySet()) {
          AntPropertyCopy propertyCopyTask = new AntPropertyCopy();
          propertyCopyTask.setOverride(true);
          propertyCopyTask.setProject(project);
          String from = key;
          String to = propertyCopyList.get(from);
          propertyCopyTask.setFrom(from);
          propertyCopyTask.setName(to);
          propertyCopyTask.execute();
        }

        sdkProperties = project.getProperties();

        for (String propertyKey : APP_SERVER_PROPERTIES_KEYS) {
          if (!sdkProperties.keySet().contains(propertyKey)) {
            throw new CoreException(
                SDKCorePlugin.createErrorStatus(
                    "Missing ${" + propertyKey + "} setting in build.properties file."));
          }
        }

        buildPropertiesCache.put(getLocation().toPortableString(), sdkProperties);
      }
    } catch (Exception e) {
      throw new CoreException(SDKCorePlugin.createErrorStatus(e.getMessage()));
    }

    return sdkProperties;
  }
コード例 #22
0
  public Runnable createTargetInstance(Target target, Properties localProperties, Logger logger) {
    //        System.out.println("DefaultProjectModel.createTargetInstance");
    AntClassLoader loader = null;
    DefaultResources resources;

    try {
      org.apache.tools.ant.types.Path classPath = toAntPath(resolvePathGroup(target, "classpath"));

      // Allow additional classes to added to the plugin classpath. This is primarily designed to
      // allow the additional of instrumented testing classes and libraries for code coverage of
      // integration
      // tests with Cobertura
      String key = "quokka.classpath." + target.getPlugin().getArtifact().getId().getGroup();

      if (log.isDebugEnabled()) {
        log.debug("Searching for additional classpath with key: " + key);
      }

      String additionalPath = System.getProperty(key);

      if ((additionalPath != null) && !additionalPath.trim().equals("")) {
        org.apache.tools.ant.types.Path existing = classPath;
        classPath = new org.apache.tools.ant.types.Path(antProject, additionalPath);
        log.verbose("Prefixing classpath with: " + classPath);
        classPath.append(existing); // Make sure additions override existing
      }

      if ("true".equals(antProject.getProperty("quokka.project.debugclassloaders"))) {
        loader =
            new QuokkaLoader(target, antProject.getClass().getClassLoader(), antProject, classPath);
      } else {
        loader = antProject.createClassLoader(classPath);
      }

      loader.setParent(antProject.getCoreLoader());
      loader.setParentFirst(true);
      loader.setIsolated(false);
      loader.setThreadContextLoader();

      // Initialise this plugin
      Plugin plugin = target.getPlugin();
      loader.forceLoadClass(plugin.getClassName());

      Class pluginClass = Class.forName(plugin.getClassName(), true, loader);
      ws.quokka.core.plugin_spi.Plugin actualPlugin =
          (ws.quokka.core.plugin_spi.Plugin) pluginClass.newInstance();

      if (actualPlugin instanceof MetadataAware) {
        ((MetadataAware) actualPlugin).setMetadata(getMetadata());
      }

      if (actualPlugin instanceof ResourcesAware) {
        resources = new DefaultResources(this, target, antProject, logger);
        ((ResourcesAware) actualPlugin).setResources(resources);
      }

      if (actualPlugin instanceof RepositoryAware) {
        ((RepositoryAware) actualPlugin).setRepository(getRepository());
      }

      if (actualPlugin instanceof RepositoryFactoryAware) {
        ((RepositoryFactoryAware) actualPlugin)
            .setRepositoryFactory(
                (RepositoryFactory) antProject.getReference(ProjectHelper.REPOSITORY_FACTORY));
      }

      if (actualPlugin instanceof ResolverAware) {
        ((ResolverAware) actualPlugin).setResolver(pathResolver);
      }

      if (actualPlugin instanceof ModelFactoryAware) {
        ((ModelFactoryAware) actualPlugin).setModelFactory(getModelFactory());
      }

      actualPlugin.initialise();

      return actualPlugin.getTarget(
          (target.getTemplateName() != null) ? target.getTemplateName() : target.getName());
    } catch (Exception e) {
      throw new BuildException(e);
    } finally {
      if (loader != null) {
        loader.resetThreadContextLoader();
        loader.cleanup();
      }
    }
  }
コード例 #23
0
  public void initialise() {
    pathResolver = new Resolver(repository, log);

    // Add ant-types path
    project
        .getDependencySet()
        .addPath(
            new Path(
                "ant-types",
                "Dependencies added to this path are available to ant optional tasks."));

    // Get dependency sets, applying profiles and overrides
    List sets = depthFirst(project.getDependencySet());

    // O pass: aggregate overrides
    for (Iterator i = sets.iterator(); i.hasNext(); ) {
      DependencySet set = (DependencySet) i.next();
      overrides.addAll(set.getOverrides());
    }

    // 1st pass: Define targets, paths, imported URLs
    Map targets = new HashMap();

    for (Iterator i = sets.iterator(); i.hasNext(); ) {
      DependencySet set = (DependencySet) i.next();

      // Get targets
      for (Iterator j = set.getDependencies().iterator(); j.hasNext(); ) {
        Dependency dependency = (Dependency) j.next();

        if (dependency instanceof PluginDependency) {
          resolveTargets(targets, (PluginDependency) dependency);
        }
      }

      // Get paths
      for (Iterator j = set.getPaths().values().iterator(); j.hasNext(); ) {
        addPath((Path) j.next());
      }

      if (set.getImportURL() != null) {
        resolvedImports.add(set.getImportURL());
      }

      // Find the unique names for all declared artifacts
      Set uniqueNames = new HashSet();

      for (Iterator j = project.getArtifacts().iterator(); j.hasNext(); ) {
        Artifact artifact = (Artifact) j.next();
        uniqueNames.add(artifact.getId().getName());
      }

      // Create artifacts for any licenses referenced by files
      for (Iterator j = set.getLicenses().iterator(); j.hasNext(); ) {
        License license = (License) j.next();

        if (license.getFile() != null) {
          Assert.isTrue(
              project.getArtifacts().size() != 0,
              license.getLocator(),
              "There are no artifacts defined for a license to be applied to.");

          Artifact artifact = (Artifact) project.getArtifacts().iterator().next();
          RepoArtifactId id = artifact.getId();

          // If no name is specified, default it to name of the artifact if it is unique,
          // otherwise use the default from the group
          String name = license.getId().getName();
          String defaultName = RepoArtifactId.defaultName(id.getGroup());

          if (name == null) {
            if (uniqueNames.size() == 1) {
              name = (String) uniqueNames.iterator().next();
            } else {
              name = defaultName;
            }
          }

          Artifact licenseArtifact = new Artifact(id.getGroup(), name, "license", id.getVersion());
          licenseArtifact.setDescription(
              "License for " + id.getGroup() + (name.equals(defaultName) ? "" : (":" + name)));
          project.addArtifact(licenseArtifact);
          license.setId(licenseArtifact.getId());
        }
      }
    }

    // 2nd pass: Define default paths specs, add imported targets
    for (Iterator i = sets.iterator(); i.hasNext(); ) {
      DependencySet set = (DependencySet) i.next();

      // Fill in path spec defaults now that the project paths have been defined
      addPathSpecDefaults(set);
    }

    // 3rd pass: Reverse order for build resources
    List reverse = new ArrayList(sets);
    Collections.reverse(reverse);

    for (Iterator i = reverse.iterator(); i.hasNext(); ) {
      DependencySet set = (DependencySet) i.next();
      buildResources.putAll(set.getBuildResources()); // Parent overrides children
    }

    resolvedTargets = targets;
    corePath = resolveCorePath();

    if ("true".equals(antProject.getProperty("quokka.project.overrideCore"))) {
      coreOverrides = getCoreOverrides();
    }
  }
コード例 #24
0
  private void transform(String fromFile, String toFile) {
    if (fromFile == null) {
      throw new BuildException("fromfile must be set");
    }
    if (toFile == null) {
      throw new BuildException("tofile must be set");
    }

    try {
      final Project proj = getProject();
      File tmp = new File(outdir, toFile).getParentFile();

      if (!tmp.exists()) {
        if (tmp.exists() || !tmp.mkdirs()) {
          throw new IOException("Could not create " + tmp);
        }
      }

      tmp = new File(toFile);
      String pathToRoot = ".";

      while ((tmp = tmp.getParentFile()) != null) {
        pathToRoot = pathToRoot + "/..";
      }

      // Compute the relative path from directory holding the toFile
      // to the javadoc direcotry.
      String pathToOutDir = "";
      tmp = new File(outdir, toFile).getParentFile();
      while ((tmp = tmp.getParentFile()) != null && tmp.equals(outdir)) {
        pathToOutDir = pathToOutDir + "../";
      }
      final String pathToJavadocDir = pathToOutDir + javadocRelPath;

      String content = FileUtil.loadFile(template.toString());
      content = Util.replace(content, "$(LINKS)", links());
      content = Util.replace(content, "$(MAIN)", FileUtil.loadFile(fromFile));
      for (final Object element : fragments.keySet()) {
        final String key = (String) element;
        final HtmlFragment frag = fragments.get(key);
        final String linkText = frag.getLinkText();
        if (null != linkText && 0 < linkText.length()) {
          final String fragLink = "<a href=\"#" + key + "\">" + linkText + "</a>";
          content = Util.replace(content, "$(" + key + "_LINK)", fragLink);
        }
        String fragCont = FileUtil.loadFile(frag.getFromFile().getPath());
        if (null != fragCont && 0 < fragCont.length()) {
          fragCont = "<a name=\"" + key + "\"></a>\n" + fragCont;
        }
        content = Util.replace(content, "$(" + key + ")", fragCont);
      }
      content = Util.replace(content, "$(TITLE)", title);
      content = Util.replace(content, "$(DESC)", description);
      content = Util.replace(content, "$(TSTAMP)", TIMESTAMP);
      content = Util.replace(content, "$(YEAR)", YEAR);
      content = Util.replace(content, "$(USER)", System.getProperty("user.name"));
      content = Util.replace(content, "$(VERSION)", proj.getProperty("version"));
      content = Util.replace(content, "$(VERSION_PREV)", proj.getProperty("version.previous"));
      content = Util.replace(content, "$(KF_VERSION)", proj.getProperty("kf_version"));
      content = Util.replace(content, "$(BASE_VERSION)", proj.getProperty("base_version"));
      content = Util.replace(content, "$(BASE_URL)", proj.getProperty("base.url"));
      content = Util.replace(content, "$(DISTNAME)", proj.getProperty("distname"));
      content = Util.replace(content, "$(DISTRIB_NAME)", proj.getProperty("distrib.name"));
      content = Util.replace(content, "$(RELEASE_NAME)", proj.getProperty("release.name"));
      content = Util.replace(content, "$(RELEASE_DATE)", proj.getProperty("release.date"));
      content = Util.replace(content, "$(MESSAGE)", proj.getProperty("release"));
      content = Util.replace(content, "$(BUNDLE_LIST)", bundleList);
      content = Util.replace(content, "$(ROOT)", pathToRoot);
      content = Util.replace(content, "$(JAVADOC)", proj.getProperty("JAVADOC"));
      content =
          Util.replace(content, "$(CLASS_NAVIGATION)", proj.getProperty("css_navigation_enabled"));
      content = Util.replace(content, "$(SVN_REPO_URL)", proj.getProperty("svn.repo.url"));
      content = Util.replace(content, "$(SVN_TAG)", proj.getProperty("svn.tag"));
      content = Util.replace(content, "$(JAVADOCPATH)", pathToJavadocDir);
      content = Util.replace(content, "$(JAVADOCLINK)", pathToJavadocDir + "/index.html?");

      // Used for bundle_doc generation
      if (do_manpage) {
        content = Util.replace(content, "$(BUNDLE_NAME)", this.projectName);
        content =
            Util.replace(content, "$(BUNDLE_VERSION)", proj.getProperty("bmfa.Bundle-Version"));

        final BundleArchives bas = getBundleArchives();

        // Create links to jardoc for bundles built from this project
        content = Util.replace(content, "$(BUNDLE_JARDOCS)", basToString(bas));

        content =
            Util.replace(content, "$(BUNDLE_EXPORT_PACKAGE)", getExportPkgs(bas, pathToJavadocDir));

        // Replce H1-H3 headers to man page style, if manpage style
        content = Util.replace(content, "<h1", "<h1 class=\"man\"");
        content = Util.replace(content, "<H1", "<h1 class=\"man\"");
        content = Util.replace(content, "<h2", "<h2 class=\"man\"");
        content = Util.replace(content, "<H2", "<h2 class=\"man\"");
        content = Util.replace(content, "<h3", "<h3 class=\"man\"");
        content = Util.replace(content, "<H3", "<h3 class=\"man\"");
      }

      final String s = proj.getProperty("navigation_pages");
      final String navEnabled = proj.getProperty("css_navigation_enabled");
      final String navDisabled = proj.getProperty("css_navigation_disabled");
      // System.out.println("Navigation pages: " + s);
      if (s != null) {
        final String[] navPages = Util.splitwords(s);
        for (final String navPage : navPages) {
          // System.out.println("Checking: " + navPages[i]);
          if (disable != null && disable.equals(navPage)) {
            content = Util.replace(content, "$(CLASS_NAVIGATION_" + navPage + ")", navDisabled);
          } else {
            content = Util.replace(content, "$(CLASS_NAVIGATION_" + navPage + ")", navEnabled);
          }
        }
      }

      FileUtil.writeStringToFile(new File(outdir, toFile), content);
      log("Created: " + new File(outdir, toFile));
    } catch (final IOException e) {
      e.printStackTrace();
      throw new BuildException(e);
    } catch (final Exception e) {
      e.printStackTrace();
      throw new BuildException(e);
    }
  }
コード例 #25
0
    /**
     * Initialisation routine called after handler creation with the element name and attributes.
     * The attributes which this handler can deal with are: <code>"default"</code>, <code>"name"
     * </code>, <code>"id"</code> and <code>"basedir"</code>.
     *
     * @param uri The namespace URI for this element.
     * @param tag Name of the element which caused this handler to be created. Should not be <code>
     *     null</code>. Ignored in this implementation.
     * @param qname The qualified name for this element.
     * @param attrs Attributes of the element which caused this handler to be created. Must not be
     *     <code>null</code>.
     * @param context The current context.
     * @exception SAXParseException if an unexpected attribute is encountered or if the <code>
     *     "default"</code> attribute is missing.
     */
    public void onStartElement(
        String uri, String tag, String qname, Attributes attrs, AntXMLContext context)
        throws SAXParseException {
      String baseDir = null;
      boolean nameAttributeSet = false;

      Project project = context.getProject();
      // Set the location of the implicit target associated with the project tag
      context.getImplicitTarget().setLocation(new Location(context.getLocator()));

      /**
       * XXX I really don't like this - the XML processor is still too 'involved' in the processing.
       * A better solution (IMO) would be to create UE for Project and Target too, and then process
       * the tree and have Project/Target deal with its attributes ( similar with Description ).
       *
       * <p>If we eventually switch to ( or add support for ) DOM, things will work smoothly - UE
       * can be avoided almost completely ( it could still be created on demand, for backward
       * compatibility )
       */
      for (int i = 0; i < attrs.getLength(); i++) {
        String attrUri = attrs.getURI(i);
        if (attrUri != null && !attrUri.equals("") && !attrUri.equals(uri)) {
          continue; // Ignore attributes from unknown uris
        }
        String key = attrs.getLocalName(i);
        String value = attrs.getValue(i);

        if (key.equals("default")) {
          if (value != null && !value.equals("")) {
            if (!context.isIgnoringProjectTag()) {
              project.setDefault(value);
            }
          }
        } else if (key.equals("name")) {
          if (value != null) {
            context.setCurrentProjectName(value);
            nameAttributeSet = true;
            if (!context.isIgnoringProjectTag()) {
              project.setName(value);
              project.addReference(value, project);
            } else if (isInIncludeMode()) {
              if (!"".equals(value)
                  && (getCurrentTargetPrefix() == null || getCurrentTargetPrefix().length() == 0)) {
                // help nested include tasks
                setCurrentTargetPrefix(value);
              }
            }
          }
        } else if (key.equals("id")) {
          if (value != null) {
            // What's the difference between id and name ?
            if (!context.isIgnoringProjectTag()) {
              project.addReference(value, project);
            }
          }
        } else if (key.equals("basedir")) {
          if (!context.isIgnoringProjectTag()) {
            baseDir = value;
          }
        } else {
          // XXX ignore attributes in a different NS ( maybe store them ? )
          throw new SAXParseException(
              "Unexpected attribute \"" + attrs.getQName(i) + "\"", context.getLocator());
        }
      }

      // XXX Move to Project ( so it is shared by all helpers )
      String antFileProp = MagicNames.ANT_FILE + "." + context.getCurrentProjectName();
      String dup = project.getProperty(antFileProp);
      String typeProp = MagicNames.ANT_FILE_TYPE + "." + context.getCurrentProjectName();
      String dupType = project.getProperty(typeProp);
      if (dup != null && nameAttributeSet) {
        Object dupFile = null;
        Object contextFile = null;
        if (MagicNames.ANT_FILE_TYPE_URL.equals(dupType)) {
          try {
            dupFile = new URL(dup);
          } catch (java.net.MalformedURLException mue) {
            throw new BuildException(
                "failed to parse "
                    + dup
                    + " as URL while looking"
                    + " at a duplicate project"
                    + " name.",
                mue);
          }
          contextFile = context.getBuildFileURL();
        } else {
          dupFile = new File(dup);
          contextFile = context.getBuildFile();
        }

        if (context.isIgnoringProjectTag() && !dupFile.equals(contextFile)) {
          project.log(
              "Duplicated project name in import. Project "
                  + context.getCurrentProjectName()
                  + " defined first in "
                  + dup
                  + " and again in "
                  + contextFile,
              Project.MSG_WARN);
        }
      }
      if (nameAttributeSet) {
        if (context.getBuildFile() != null) {
          project.setUserProperty(antFileProp, context.getBuildFile().toString());
          project.setUserProperty(typeProp, MagicNames.ANT_FILE_TYPE_FILE);
        } else if (context.getBuildFileURL() != null) {
          project.setUserProperty(antFileProp, context.getBuildFileURL().toString());
          project.setUserProperty(typeProp, MagicNames.ANT_FILE_TYPE_URL);
        }
      }
      if (context.isIgnoringProjectTag()) {
        // no further processing
        return;
      }
      // set explicitly before starting ?
      if (project.getProperty("basedir") != null) {
        project.setBasedir(project.getProperty("basedir"));
      } else {
        // Default for baseDir is the location of the build file.
        if (baseDir == null) {
          project.setBasedir(context.getBuildFileParent().getAbsolutePath());
        } else {
          // check whether the user has specified an absolute path
          if ((new File(baseDir)).isAbsolute()) {
            project.setBasedir(baseDir);
          } else {
            project.setBaseDir(FILE_UTILS.resolveFile(context.getBuildFileParent(), baseDir));
          }
        }
      }
      project.addTarget("", context.getImplicitTarget());
      context.setCurrentTarget(context.getImplicitTarget());
    }