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());
      }
    }
  }
예제 #2
0
 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("------------------------------------------------------------------------");
 }
예제 #3
0
 /**
  * Get Current Connection from <em>ref</em> parameter or create a new one!
  *
  * @return The server connection
  * @throws MalformedURLException
  * @throws IOException
  */
 @SuppressWarnings("null")
 public static MBeanServerConnection accessJMXConnection(
     Project project,
     String url,
     String host,
     String port,
     String username,
     String password,
     String refId)
     throws MalformedURLException, IOException {
   MBeanServerConnection jmxServerConnection = null;
   boolean isRef = project != null && refId != null && refId.length() > 0;
   if (isRef) {
     Object pref = project.getReference(refId);
     try {
       jmxServerConnection = (MBeanServerConnection) pref;
     } catch (ClassCastException cce) {
       project.log("wrong object reference " + refId + " - " + pref.getClass());
       return null;
     }
   }
   if (jmxServerConnection == null) {
     jmxServerConnection = createJMXConnection(url, host, port, username, password);
   }
   if (isRef && jmxServerConnection != null) {
     project.addReference(refId, jmxServerConnection);
   }
   return jmxServerConnection;
 }
 public static synchronized AntRepoSys getInstance(Project project) {
   Object obj = project.getReference(Names.ID);
   if (obj instanceof AntRepoSys) {
     return (AntRepoSys) obj;
   }
   AntRepoSys instance = new AntRepoSys(project);
   project.addReference(Names.ID, instance);
   instance.initDefaults();
   return instance;
 }
예제 #5
0
 /**
  * Creates a processor initialized to be an extension of the base processor.
  *
  * @param baseProcessor base processor
  * @return extending processor
  */
 protected final ProcessorDef createExtendedProcessorDef(final ProcessorDef baseProcessor) {
   Project project = new Project();
   baseProcessor.setProject(project);
   baseProcessor.setId("base");
   project.addReference("base", baseProcessor);
   ProcessorDef extendedLinker = create();
   extendedLinker.setProject(project);
   extendedLinker.setExtends(new Reference("base"));
   return extendedLinker;
 }
예제 #6
0
  /**
   * Parse a source xml input.
   *
   * @param project the current project
   * @param source the xml source
   * @exception BuildException if an error occurs
   */
  public void parse(Project project, Object source) throws BuildException {
    getImportStack().addElement(source);
    AntXMLContext context = null;
    context = (AntXMLContext) project.getReference(REFID_CONTEXT);
    if (context == null) {
      context = new AntXMLContext(project);
      project.addReference(REFID_CONTEXT, context);
      project.addReference(REFID_TARGETS, context.getTargets());
    }
    if (getImportStack().size() > 1) {
      // we are in an imported file.
      context.setIgnoreProjectTag(true);
      Target currentTarget = context.getCurrentTarget();
      Target currentImplicit = context.getImplicitTarget();
      Map<String, Target> currentTargets = context.getCurrentTargets();
      try {
        Target newCurrent = new Target();
        newCurrent.setProject(project);
        newCurrent.setName("");
        context.setCurrentTarget(newCurrent);
        context.setCurrentTargets(new HashMap<String, Target>());
        context.setImplicitTarget(newCurrent);
        parse(project, source, new RootHandler(context, mainHandler));
        newCurrent.execute();
      } finally {
        context.setCurrentTarget(currentTarget);
        context.setImplicitTarget(currentImplicit);
        context.setCurrentTargets(currentTargets);
      }
    } else {
      // top level file
      context.setCurrentTargets(new HashMap<String, Target>());
      parse(project, source, new RootHandler(context, mainHandler));
      // Execute the top-level target
      context.getImplicitTarget().execute();

      // resolve extensionOf attributes
      resolveExtensionOfAttributes(project);
    }
  }
  public void execute() {
    if (applicationDir == null) {
      throw new BuildException("No applicationDir set!");
    }

    // Add the properties from application.conf as ant properties
    for (Map.Entry<String, String> entry : properties().entrySet()) {
      String key = entry.getKey();
      String value = project.replaceProperties(entry.getValue());
      project.setProperty(prefix + key, value);
      project.log("Loaded property '" + prefix + key + "'='" + value + "'", Project.MSG_VERBOSE);
    }

    // Add the module classpath as an ant property
    Path path = new Path(project);
    FilenameSelector endsToJar = new FilenameSelector();
    endsToJar.setName("*.jar");

    for (File module : modules()) {
      File moduleLib = new File(module, "lib");
      if (moduleLib.exists()) {
        FileSet fileSet = new FileSet();
        fileSet.setDir(moduleLib);
        fileSet.addFilename(endsToJar);
        path.addFileset(fileSet);
        project.log("Added fileSet to path: " + fileSet, Project.MSG_VERBOSE);
      } else {
        project.log(
            "Ignoring non existing lib dir: " + moduleLib.getAbsolutePath(), Project.MSG_VERBOSE);
      }
    }
    project.addReference(modulesClasspath, path);
    project.log(
        "Generated classpath '" + modulesClasspath + "':" + project.getReference(modulesClasspath),
        Project.MSG_VERBOSE);
  }
예제 #8
0
  /** Runs the given targets for the test project specified */
  public Map run(
      File buildFile, List targets, Properties projectProperties, Properties pluginState) {
    Project project = new Project();
    project.setCoreLoader(getClass().getClassLoader());
    antListener = new AntRunner.AntListener();

    project.addBuildListener(
        createLogger(projectProperties.getProperty("quokka.debugger.logLevel")));
    project.addBuildListener(antListener);

    //        project.setInputHandler(new DefaultInputHandler());
    project.setInputHandler(
        new InputHandler() {
          public void handleInput(InputRequest request) throws BuildException {
            System.out.println(request.getPrompt());

            try {
              String line = new BufferedReader(new InputStreamReader(System.in)).readLine();
              request.setInput(line);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        });
    project.setKeepGoingMode(false);

    //        PrintStream err = System.err;
    //        PrintStream out = System.out;
    //        InputStream in = System.in;
    project.setDefaultInputStream(System.in);

    //        System.setIn(new DemuxInputStream(project));
    //        System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
    //        System.setErr(new PrintStream(new DemuxOutputStream(project, true)));
    for (Iterator i = projectProperties.entrySet().iterator(); i.hasNext(); ) {
      Map.Entry entry = (Map.Entry) i.next();
      project.setUserProperty((String) entry.getKey(), (String) entry.getValue());
    }

    Exception exception = null;

    try {
      project.fireBuildStarted();

      project.init();
      project.setUserProperty("ant.version", "1.7.0");
      project.setUserProperty("ant.file", buildFile.getAbsolutePath());

      // Remove hard dependency on core.main to allow integration tests to be
      // done within the core.main package. This is ok as AntRunner is loaded via the integration
      // test class loader.
      org.apache.tools.ant.ProjectHelper helper =
          (org.apache.tools.ant.ProjectHelper)
              getClass()
                  .getClassLoader()
                  .loadClass("ws.quokka.core.main.ant.ProjectHelper")
                  .newInstance();
      project.addReference("ant.projectHelper", helper);
      helper.parse(project, buildFile);

      // Add any plugin state
      PluginState state = (PluginState) project.getReference("quokka.pluginState");

      for (Iterator i = pluginState.entrySet().iterator(); i.hasNext(); ) {
        Map.Entry entry = (Map.Entry) i.next();
        state.put((String) entry.getKey(), entry.getValue());
      }

      Vector targetsVector = new Vector();
      targetsVector.addAll(targets);

      // make sure that we have a target to execute
      if (targets.size() == 0) {
        if (project.getDefaultTarget() != null) {
          targetsVector.add(project.getDefaultTarget());
        }
      }

      project.executeTargets(targetsVector);

      Map results = antListener.toMap();
      results.put("antProperties", new HashMap(project.getProperties()));

      return results;
    } catch (Exception e) {
      exception = e;

      if (e instanceof RuntimeException) {
        throw (RuntimeException) e;
      } else {
        throw new BuildException(e);
      }
    } finally {
      //            System.setOut(out);
      //            System.setErr(err);
      //            System.setIn(in);
      project.fireBuildFinished(exception);
    }
  }
    /**
     * 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());
    }
  /**
   * Parse a source xml input.
   *
   * @param project the current project
   * @param source the xml source
   * @exception BuildException if an error occurs
   */
  public void parse(Project project, Object source) throws BuildException {
    getImportStack().addElement(source);
    AntXMLContext context = null;
    context = (AntXMLContext) project.getReference(REFID_CONTEXT);
    if (context == null) {
      context = new AntXMLContext(project);
      project.addReference(REFID_CONTEXT, context);
      project.addReference(REFID_TARGETS, context.getTargets());
    }
    if (getImportStack().size() > 1) {
      // we are in an imported file.
      context.setIgnoreProjectTag(true);
      Target currentTarget = context.getCurrentTarget();
      Target currentImplicit = context.getImplicitTarget();
      Map currentTargets = context.getCurrentTargets();
      try {
        Target newCurrent = new Target();
        newCurrent.setProject(project);
        newCurrent.setName("");
        context.setCurrentTarget(newCurrent);
        context.setCurrentTargets(new HashMap());
        context.setImplicitTarget(newCurrent);
        parse(project, source, new RootHandler(context, mainHandler));
        newCurrent.execute();
      } finally {
        context.setCurrentTarget(currentTarget);
        context.setImplicitTarget(currentImplicit);
        context.setCurrentTargets(currentTargets);
      }
    } else {
      // top level file
      context.setCurrentTargets(new HashMap());
      parse(project, source, new RootHandler(context, mainHandler));
      // Execute the top-level target
      context.getImplicitTarget().execute();

      // resolve extensionOf attributes
      for (Iterator i = getExtensionStack().iterator(); i.hasNext(); ) {
        String[] extensionInfo = (String[]) i.next();
        String tgName = extensionInfo[0];
        String name = extensionInfo[1];
        OnMissingExtensionPoint missingBehaviour =
            OnMissingExtensionPoint.valueOf(extensionInfo[2]);
        Hashtable projectTargets = project.getTargets();
        if (!projectTargets.containsKey(tgName)) {
          String message =
              "can't add target "
                  + name
                  + " to extension-point "
                  + tgName
                  + " because the extension-point is unknown.";
          if (missingBehaviour == OnMissingExtensionPoint.FAIL) {
            throw new BuildException(message);
          } else if (missingBehaviour == OnMissingExtensionPoint.WARN) {
            Target target = (Target) projectTargets.get(name);
            context.getProject().log(target, "Warning: " + message, Project.MSG_WARN);
          }
        } else {
          Target t = (Target) projectTargets.get(tgName);
          if (!(t instanceof ExtensionPoint)) {
            throw new BuildException("referenced target " + tgName + " is not an extension-point");
          }
          t.addDependency(name);
        }
      }
    }
  }
예제 #11
0
 /* (non-Javadoc)
  * @see org.apache.tools.ant.Executor#executeTargets(org.apache.tools.ant.Project, java.lang.String[])
  */
 public void executeTargets(Project project, String[] targetNames) throws BuildException {
   Vector v = new Vector();
   v.addAll(Arrays.asList(targetNames));
   project.addReference("eclipse.ant.targetVector", v); // $NON-NLS-1$
   super.executeTargets(project, targetNames);
 }
  @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();
  }