/**
  * Handle the project tag
  *
  * @param uri The namespace uri.
  * @param name The element tag.
  * @param qname The element qualified name.
  * @param attrs The attributes of the element.
  * @param context The current context.
  * @return The project handler that handles subelements of project
  * @exception SAXParseException if the qualified name is not "project".
  */
 public AntHandler onStartChild(
     String uri, String name, String qname, Attributes attrs, AntXMLContext context)
     throws SAXParseException {
   if (name.equals("project") && (uri.equals("") || uri.equals(ANT_CORE_URI))) {
     return ProjectHelper2.projectHandler;
   }
   if (name.equals(qname)) {
     throw new SAXParseException(
         "Unexpected element \"{" + uri + "}" + name + "\" {" + ANT_CORE_URI + "}" + name,
         context.getLocator());
   }
   throw new SAXParseException(
       "Unexpected element \"" + qname + "\" " + name, context.getLocator());
 }
    /**
     * Handles text within an element. This base implementation just throws an exception, you must
     * override it if you expect content.
     *
     * @param buf A character array of the text within the element. Will not be <code>null</code>.
     * @param start The start element in the array.
     * @param count The number of characters to read from the array.
     * @param context The current context.
     * @exception SAXParseException if this method is not overridden, or in case of error in an
     *     overridden version
     */
    public void characters(char[] buf, int start, int count, AntXMLContext context)
        throws SAXParseException {
      String s = new String(buf, start, count).trim();

      if (s.length() > 0) {
        throw new SAXParseException("Unexpected text \"" + s + "\"", context.getLocator());
      }
    }
    /**
     * Initialisation routine called after handler creation with the element name and attributes.
     * The attributes which this handler can deal with are: <code>"name"</code>, <code>"depends"
     * </code>, <code>"if"</code>, <code>"unless"</code>, <code>"id"</code> and <code>"description"
     * </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>"name"
     *     </code> attribute is missing.
     */
    public void onStartElement(
        String uri, String tag, String qname, Attributes attrs, AntXMLContext context)
        throws SAXParseException {
      String name = null;
      String depends = "";
      String extensionPoint = null;
      OnMissingExtensionPoint extensionPointMissing = null;

      Project project = context.getProject();
      Target target = "target".equals(tag) ? new Target() : new ExtensionPoint();
      target.setProject(project);
      target.setLocation(new Location(context.getLocator()));
      context.addTarget(target);

      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("name")) {
          name = value;
          if ("".equals(name)) {
            throw new BuildException("name attribute must " + "not be empty");
          }
        } else if (key.equals("depends")) {
          depends = value;
        } else if (key.equals("if")) {
          target.setIf(value);
        } else if (key.equals("unless")) {
          target.setUnless(value);
        } else if (key.equals("id")) {
          if (value != null && !value.equals("")) {
            context.getProject().addReference(value, target);
          }
        } else if (key.equals("description")) {
          target.setDescription(value);
        } else if (key.equals("extensionOf")) {
          extensionPoint = value;
        } else if (key.equals("onMissingExtensionPoint")) {
          try {
            extensionPointMissing = OnMissingExtensionPoint.valueOf(value);
          } catch (IllegalArgumentException e) {
            throw new BuildException("Invalid onMissingExtensionPoint " + value);
          }
        } else {
          throw new SAXParseException("Unexpected attribute \"" + key + "\"", context.getLocator());
        }
      }

      if (name == null) {
        throw new SAXParseException(
            "target element appears without a name attribute", context.getLocator());
      }

      String prefix = null;
      boolean isInIncludeMode = context.isIgnoringProjectTag() && isInIncludeMode();
      String sep = getCurrentPrefixSeparator();

      if (isInIncludeMode) {
        prefix = getTargetPrefix(context);
        if (prefix == null) {
          throw new BuildException(
              "can't include build file "
                  + context.getBuildFileURL()
                  + ", no as attribute has been given"
                  + " and the project tag doesn't"
                  + " specify a name attribute");
        }
        name = prefix + sep + name;
      }

      // Check if this target is in the current build file
      if (context.getCurrentTargets().get(name) != null) {
        throw new BuildException("Duplicate target '" + name + "'", target.getLocation());
      }
      Hashtable projectTargets = project.getTargets();
      boolean usedTarget = false;
      // If the name has not already been defined define it
      if (projectTargets.containsKey(name)) {
        project.log(
            "Already defined in main or a previous import, ignore " + name, Project.MSG_VERBOSE);
      } else {
        target.setName(name);
        context.getCurrentTargets().put(name, target);
        project.addOrReplaceTarget(name, target);
        usedTarget = true;
      }

      if (depends.length() > 0) {
        if (!isInIncludeMode) {
          target.setDepends(depends);
        } else {
          for (Iterator iter = Target.parseDepends(depends, name, "depends").iterator();
              iter.hasNext(); ) {
            target.addDependency(prefix + sep + iter.next());
          }
        }
      }
      if (!isInIncludeMode
          && context.isIgnoringProjectTag()
          && (prefix = getTargetPrefix(context)) != null) {
        // In an imported file (and not completely
        // ignoring the project tag or having a preconfigured prefix)
        String newName = prefix + sep + name;
        Target newTarget = usedTarget ? new Target(target) : target;
        newTarget.setName(newName);
        context.getCurrentTargets().put(newName, newTarget);
        project.addOrReplaceTarget(newName, newTarget);
      }
      if (extensionPointMissing != null && extensionPoint == null) {
        throw new BuildException(
            "onMissingExtensionPoint attribute cannot "
                + "be specified unless extensionOf is specified",
            target.getLocation());
      }
      if (extensionPoint != null) {
        ProjectHelper helper =
            (ProjectHelper)
                context.getProject().getReference(ProjectHelper.PROJECTHELPER_REFERENCE);
        for (Iterator iter = Target.parseDepends(extensionPoint, name, "extensionOf").iterator();
            iter.hasNext(); ) {
          String tgName = (String) iter.next();
          if (isInIncludeMode()) {
            tgName = prefix + sep + tgName;
          }
          if (extensionPointMissing == null) {
            extensionPointMissing = OnMissingExtensionPoint.FAIL;
          }
          // defer extensionpoint resolution until the full
          // import stack has been processed
          helper.getExtensionStack().add(new String[] {tgName, name, extensionPointMissing.name()});
        }
      }
    }
    /**
     * 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());
    }
 /**
  * Handles the start of an element. This base implementation just throws an exception - you must
  * override this method if you expect child elements.
  *
  * @param uri The namespace uri for this element.
  * @param tag The name of the element being started. Will not be <code>null</code>.
  * @param qname The qualified name for this element.
  * @param attrs Attributes of the element being started. Will not be <code>null</code>.
  * @param context The current context.
  * @return a handler (in the derived classes)
  * @exception SAXParseException if this method is not overridden, or in case of error in an
  *     overridden version
  */
 public AntHandler onStartChild(
     String uri, String tag, String qname, Attributes attrs, AntXMLContext context)
     throws SAXParseException {
   throw new SAXParseException("Unexpected element \"" + qname + " \"", context.getLocator());
 }
    /**
     * Initialisation routine called after handler creation with the element name and attributes.
     * This configures the element with its attributes and sets it up with its parent container (if
     * any). Nested elements are then added later as the parser encounters them.
     *
     * @param uri The namespace URI for this element.
     * @param tag Name of the element which caused this handler to be created. Must not be <code>
     *     null</code>.
     * @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 in case of error (not thrown in this implementation)
     */
    public void onStartElement(
        String uri, String tag, String qname, Attributes attrs, AntXMLContext context)
        throws SAXParseException {
      RuntimeConfigurable parentWrapper = context.currentWrapper();
      Object parent = null;

      if (parentWrapper != null) {
        parent = parentWrapper.getProxy();
      }

      /* UnknownElement is used for tasks and data types - with
      delayed eval */
      UnknownElement task = new UnknownElement(tag);
      task.setProject(context.getProject());
      task.setNamespace(uri);
      task.setQName(qname);
      task.setTaskType(ProjectHelper.genComponentName(task.getNamespace(), tag));
      task.setTaskName(qname);

      Location location =
          new Location(
              context.getLocator().getSystemId(),
              context.getLocator().getLineNumber(),
              context.getLocator().getColumnNumber());
      task.setLocation(location);
      task.setOwningTarget(context.getCurrentTarget());

      if (parent != null) {
        // Nested element
        ((UnknownElement) parent).addChild(task);
      } else {
        // Task included in a target ( including the default one ).
        context.getCurrentTarget().addTask(task);
      }

      context.configureId(task, attrs);

      // container.addTask(task);
      // This is a nop in UE: task.init();

      RuntimeConfigurable wrapper = new RuntimeConfigurable(task, task.getTaskName());

      for (int i = 0; i < attrs.getLength(); i++) {
        String name = attrs.getLocalName(i);
        String attrUri = attrs.getURI(i);
        if (attrUri != null && !attrUri.equals("") && !attrUri.equals(uri)) {
          name = attrUri + ":" + attrs.getQName(i);
        }
        String value = attrs.getValue(i);
        // PR: Hack for ant-type value
        //  an ant-type is a component name which can
        // be namespaced, need to extract the name
        // and convert from qualified name to uri/name
        if (ANT_TYPE.equals(name)
            || (ANT_CORE_URI.equals(attrUri) && ANT_TYPE.equals(attrs.getLocalName(i)))) {
          name = ANT_TYPE;
          int index = value.indexOf(":");
          if (index >= 0) {
            String prefix = value.substring(0, index);
            String mappedUri = context.getPrefixMapping(prefix);
            if (mappedUri == null) {
              throw new BuildException("Unable to find XML NS prefix \"" + prefix + "\"");
            }
            value = ProjectHelper.genComponentName(mappedUri, value.substring(index + 1));
          }
        }
        wrapper.setAttribute(name, value);
      }
      if (parentWrapper != null) {
        parentWrapper.addChild(wrapper);
      }
      context.pushWrapper(wrapper);
    }