/**
  * Signals that a build has started. This event is fired before any targets have started.
  *
  * @param event An event with any relevant extra information. Must not be <code>null</code>.
  */
 public void buildStarted(BuildEvent event) {
   Resource resource = m_context.getResource();
   String path = resource.getResourcePath();
   String version = resource.getVersion();
   Project project = m_context.getProject();
   project.log("\n-------------------------------------------------------------------------");
   project.log(path + "#" + version);
   project.log("-------------------------------------------------------------------------");
 }
Esempio n. 2
0
 private void printHeader(int amount) {
   String binaryBinaries = amount > 1 ? "Binaries" : "Binary";
   project.log(" ");
   project.log(" ");
   project.log("======================================================");
   project.log("              Testing " + amount + " " + binaryBinaries);
   project.log("======================================================");
   project.log(" ");
   project.log(" ");
 }
Esempio n. 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;
 }
Esempio n. 4
0
 public void log(String msg, int level) {
   if (task != null) {
     task.log(msg, level);
   } else if (debug) {
     project.log(msg, level);
   }
 }
 /** @since Compress Antlib 1.1 */
 protected final void log(String msg) {
   if (project != null) {
     project.log(msg);
   } else {
     // rely on Ant's output redirection
     System.out.println(msg);
   }
 }
Esempio n. 6
0
  /**
   * Open an ssh seession.
   *
   * @return the opened session
   * @throws JSchException on error
   */
  protected Session openSession() throws JSchException {
    JSch jsch = new JSch();
    if (null != userInfo.getKeyfile()) {
      jsch.addIdentity(userInfo.getKeyfile());
    }

    if (!userInfo.getTrust() && knownHosts != null) {
      project.log("Using known hosts: " + knownHosts, Project.MSG_DEBUG);
      jsch.setKnownHosts(knownHosts);
    }

    Session session = jsch.getSession(userInfo.getName(), host, port);
    session.setUserInfo(userInfo);
    project.log("Connecting to " + host + ":" + port, Project.MSG_VERBOSE);
    session.connect();
    return session;
  }
  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);
  }
Esempio n. 8
0
  private void printFooter() {
    project.log(" ");
    project.log(" ");
    project.log("======================================================");
    if (totalNumberOfFailures > 0) {
      project.log("              " + totalNumberOfFailures + " test(s) failed");

    } else if (totalNumberOfTests > 0) {
      project.log("              OK - All tests green");
    } else {
      project.log("              OK - No tests in subdirectories");
    }
    project.log("======================================================");
    project.log(" ");
    project.log(" ");
  }
Esempio n. 9
0
 /**
  * FIXME Comment this
  *
  * @param session
  * @param cmd
  * @return return code of the process.
  * @throws JSchException if there's an underlying problem exposed in SSH
  * @throws IOException if there's a problem attaching streams.
  * @throws TimeoutException if we exceeded our timeout
  */
 private int executeCommand(Session session, String cmd)
     throws JSchException, IOException, TimeoutException {
   final ChannelExec channel;
   session.setTimeout((int) maxwait);
   /* execute the command */
   channel = (ChannelExec) session.openChannel("exec");
   channel.setCommand(cmd);
   attachStreams(channel);
   project.log("executing command: " + cmd, Project.MSG_VERBOSE);
   channel.connect();
   try {
     waitFor(channel);
   } finally {
     streamHandler.stop();
     closeStreams(channel);
   }
   return channel.getExitStatus();
 }
Esempio n. 10
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;
 }
  private synchronized Settings getSettings() {
    if (settings == null) {
      DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
      request.setUserSettingsFile(getUserSettings());
      request.setGlobalSettingsFile(getGlobalSettings());
      request.setSystemProperties(getSystemProperties());
      request.setUserProperties(getUserProperties());

      try {
        settings = settingsBuilder.build(request).getEffectiveSettings();
      } catch (SettingsBuildingException e) {
        project.log("Could not process settings.xml: " + e.getMessage(), e, Project.MSG_WARN);
      }

      SettingsDecryptionResult result =
          settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(settings));
      settings.setServers(result.getServers());
      settings.setProxies(result.getProxies());
    }
    return settings;
  }
  /*
   * Get the set of modules for the current project. This include old-style (using application.conf)
   * and new style, with dependencies starting at 1.2 (load everything from the modules/ dir)
   */
  private Set<File> modules() {
    Set<File> modules = new HashSet<File>();

    // Old-skool
    for (Map.Entry<String, String> entry : properties().entrySet()) {
      if (!entry.getKey().startsWith("module.")) {
        continue;
      }
      String s = project.replaceProperties(entry.getValue());
      File moduleDir;
      if (!FileUtils.isAbsolutePath(s)) {
        moduleDir = new File(new File(applicationDir, "conf"), s);
      } else {
        moduleDir = new File(s);
      }
      if (!moduleDir.exists()) {
        project.log(
            "Failed add non existing module to classpath! " + moduleDir.getAbsolutePath(),
            Project.MSG_WARN);
        continue;
      }
      modules.add(moduleDir);
    }

    // 1.2+ fashion
    File modulesDir = new File(applicationDir, "modules");
    if (modulesDir.exists()) {
      for (File child : modulesDir.listFiles()) {
        if (child == null) {
          // No-op
        } else if (child.isDirectory()) {
          modules.add(child);
        } else {
          modules.add(new File(IO.readContentAsString(child)));
        }
      }
    }
    return modules;
  }
  private IStatus executeOperation(final Project antProject, final IProgressMonitor monitor) {
    try {
      final Map<String, Object> properties = new HashMap<String, Object>();
      if (antProject != null) {
        final Hashtable<String, Object> antProperties = antProject.getProperties();
        properties.putAll(antProperties);
      }
      final IStringResolver variables = new PropertiesStringResolver(properties, "${", "}");

      updateRcmGml(variables);

      final IRainfallModelProvider provider = new UrlRainfallModellProvider(m_rcmUrl);
      final RainfallGenerationOperation operation =
          new RainfallGenerationOperation(provider, variables);
      return operation.execute(monitor);
    } catch (final CoreException ce) {
      final IStatus status = ce.getStatus();
      antProject.log(this, status.getMessage(), status.getException(), Project.MSG_ERR);
      return Status.OK_STATUS;
    } catch (final InvocationTargetException e) {
      e.printStackTrace();
      throw new BuildException(e.getTargetException());
    }
  }
Esempio n. 14
0
 /**
  * Splits a PATH (with : or ; as separators) into its parts.
  *
  * @param project the project to use
  * @param source a <code>String</code> value
  * @return an array of strings, one for each path element
  */
 public static String[] translatePath(Project project, String source) {
   final Vector<String> result = new Vector<String>();
   if (source == null) {
     return new String[0];
   }
   PathTokenizer tok = new PathTokenizer(source);
   StringBuffer element = new StringBuffer();
   while (tok.hasMoreTokens()) {
     String pathElement = tok.nextToken();
     try {
       element.append(resolveFile(project, pathElement).getPath());
     } catch (BuildException e) {
       project.log(
           "Dropping path element " + pathElement + " as it is not valid relative to the project",
           Project.MSG_VERBOSE);
     }
     for (int i = 0; i < element.length(); i++) {
       translateFileSep(element, i);
     }
     result.addElement(element.toString());
     element = new StringBuffer();
   }
   return result.toArray(new String[result.size()]);
 }
 public void info(String message) {
   myProject.log(message, Project.MSG_INFO);
 }
 public void warning(String message) {
   myProject.log(message, Project.MSG_WARN);
 }
Esempio n. 17
0
  @Override
  public List<Artifact> getArtifactList(Project project, File spreadsheet) throws IOException {
    xlsFile = spreadsheet;

    BufferedInputStream bis = null;
    HSSFWorkbook workBook = null;
    List<Artifact> artifacts = new ArrayList<Artifact>();

    try {
      bis = new BufferedInputStream(new FileInputStream(xlsFile));
      workBook = new HSSFWorkbook(bis);

      HSSFSheet sheet = workBook.getSheetAt(0);

      Map<ColumnType, Integer> columnHeaders = getColumnInfo(sheet);
      Integer typeColumn = columnHeaders.get(ColumnType.TYPE_COLUMN);
      Integer classifierColumn = columnHeaders.get(ColumnType.CLASSIFIER_COLUMN);
      Integer digestColumn = columnHeaders.get(ColumnType.DIGEST_COLUMN);
      String groupId = "";
      String artifactId = "";
      String type = JAR;
      String version = "";
      String classifier = "";
      String digest = "";

      for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); ++i) {
        HSSFRow row = sheet.getRow(i);
        if (row != null) {
          HSSFCell cell = row.getCell(columnHeaders.get(ColumnType.GROUP_COLUMN).intValue());
          if (cell != null) {
            String gId = cell.getStringCellValue().trim();
            if (!gId.isEmpty()) {
              groupId = gId;
            }
          }

          cell = row.getCell(columnHeaders.get(ColumnType.ARTIFACT_COLUMN).intValue());
          if (cell != null) {
            String aId = cell.getStringCellValue().trim();
            if (!aId.isEmpty()) {
              artifactId = aId;
            }
          }

          cell = row.getCell(columnHeaders.get(ColumnType.VERSION_COLUMN).intValue());
          if (cell != null) {
            String v;
            if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
              v = String.valueOf(cell.getNumericCellValue());
            } else {
              v = cell.getStringCellValue().trim();
            }
            if (!v.isEmpty()) {
              version = v;
            }
          }

          cell = (typeColumn != null) ? row.getCell(typeColumn.intValue()) : null;
          if (cell != null) {
            type = cell.getStringCellValue().trim();
          }

          cell = (classifierColumn != null) ? row.getCell(classifierColumn.intValue()) : null;
          if (cell != null) {
            classifier = cell.getStringCellValue().trim();
          }

          cell = (digestColumn != null) ? row.getCell(digestColumn.intValue()) : null;
          if (cell != null) {
            digest = cell.getStringCellValue().trim();
          }

          if (groupId.isEmpty() || artifactId.isEmpty() || version.isEmpty()) {
            if (groupId.isEmpty() || version.isEmpty()) {
              project.log(
                  "Row "
                      + row.getRowNum()
                      + ": Invalid artifact specified: [groupId: "
                      + groupId
                      + ", artifactId: "
                      + artifactId
                      + ", classifier: "
                      + classifier
                      + ", version: "
                      + version
                      + ", digest: "
                      + digest
                      + "]");
            }
          } else {
            artifacts.add(new Artifact(groupId, artifactId, type, classifier, version, digest));
          }
        }

        artifactId = "";
        classifier = "";
        digest = "";
        type = JAR;
      }

      project.log(sheet.getLastRowNum() + " rows read from " + xlsFile, Project.MSG_VERBOSE);
    } finally {
      if (workBook != null) {
        workBook.close();
      }
      Closer.close(bis);
    }

    return artifacts;
  }
Esempio n. 18
0
 public void error(String message, Exception e) {
   Project antProject = AntLogCreator.INSTANCE.getAntProject();
   Task task = antProject.getThreadTask(Thread.currentThread());
   antProject.log(task, message, e, Project.MSG_ERR);
 }
Esempio n. 19
0
 public void warn(String message) {
   Project antProject = AntLogCreator.INSTANCE.getAntProject();
   Task task = antProject.getThreadTask(Thread.currentThread());
   antProject.log(task, message, Project.MSG_WARN);
 }
Esempio n. 20
0
 public void visitLibraries(
     final Project project, final Linker linker, final File[] libpath, final FileVisitor visitor)
     throws BuildException {
   if (isReference()) {
     final LibrarySet master = (LibrarySet) getCheckedRef(LibrarySet.class, "LibrarySet");
     master.visitLibraries(project, linker, libpath, visitor);
   }
   //
   // if there was a libs attribute then
   // add the corresponding patterns to the FileSet
   //
   if (this.libnames != null) {
     for (final String libname : this.libnames) {
       final String[] patterns =
           linker.getLibraryPatterns(new String[] {libname}, this.libraryType);
       if (patterns.length > 0) {
         final FileSet localSet = (FileSet) this.set.clone();
         //
         // unless explicitly set
         // will default to the linker case sensitivity
         //
         if (!this.explicitCaseSensitive) {
           final boolean linkerCaseSensitive = linker.isCaseSensitive();
           localSet.setCaseSensitive(linkerCaseSensitive);
         }
         //
         // add all the patterns for this libname
         //
         for (final String pattern : patterns) {
           final PatternSet.NameEntry entry = localSet.createInclude();
           entry.setName(pattern);
         }
         int matches = 0;
         //
         // if there was no specified directory then
         // run through the libpath backwards
         //
         if (localSet.getDir(project) == null) {
           //
           // scan libpath in reverse order
           // to give earlier entries priority
           //
           for (int j = libpath.length - 1; j >= 0; j--) {
             final FileSet clone = (FileSet) localSet.clone();
             clone.setDir(libpath[j]);
             final DirectoryScanner scanner = clone.getDirectoryScanner(project);
             final File basedir = scanner.getBasedir();
             final String[] files = scanner.getIncludedFiles();
             matches += files.length;
             for (final String file : files) {
               visitor.visit(basedir, file);
             }
           }
         } else {
           final DirectoryScanner scanner = localSet.getDirectoryScanner(project);
           final File basedir = scanner.getBasedir();
           final String[] files = scanner.getIncludedFiles();
           matches += files.length;
           for (final String file : files) {
             visitor.visit(basedir, file);
           }
         }
         //
         // TODO: following section works well for Windows
         // style linkers but unnecessary fails
         // Unix style linkers. Will need to revisit.
         //
         if (matches == 0) {
           final StringBuffer msg = new StringBuffer("No file matching ");
           if (patterns.length == 1) {
             msg.append("pattern (");
             msg.append(patterns[0]);
             msg.append(")");
           } else {
             msg.append("patterns (\"");
             msg.append(patterns[0]);
             for (int k = 1; k < patterns.length; k++) {
               msg.append(", ");
               msg.append(patterns[k]);
             }
             msg.append(")");
           }
           msg.append(" for library name \"");
           msg.append(libname);
           msg.append("\" was found.");
           // TODO: raising the message in the log rather
           // throw new BuildException(msg.toString());
           project.log(msg.toString(), Project.MSG_WARN);
         }
       }
     }
   }
 }
Esempio n. 21
0
 public static void emitDebugLog(Project project, String[] sA) {
   if (sA == null) return;
   for (String s : sA) {
     project.log(s, Project.MSG_DEBUG);
   }
 }
  /**
   * Parses the project file, configuring the project as it goes.
   *
   * @param project the current project
   * @param source the xml source
   * @param handler the root handler to use (contains the current context)
   * @exception BuildException if the configuration is invalid or cannot be read
   */
  public void parse(Project project, Object source, RootHandler handler) throws BuildException {

    AntXMLContext context = handler.context;

    File buildFile = null;
    URL url = null;
    String buildFileName = null;

    if (source instanceof File) {
      buildFile = (File) source;
    } else if (source instanceof URL) {
      url = (URL) source;
    } else if (source instanceof Resource) {
      FileProvider fp = (FileProvider) ((Resource) source).as(FileProvider.class);
      if (fp != null) {
        buildFile = fp.getFile();
      } else {
        URLProvider up = (URLProvider) ((Resource) source).as(URLProvider.class);
        if (up != null) {
          url = up.getURL();
        }
      }
    }
    if (buildFile != null) {
      buildFile = FILE_UTILS.normalize(buildFile.getAbsolutePath());
      context.setBuildFile(buildFile);
      buildFileName = buildFile.toString();
    } else if (url != null) {
      try {
        context.setBuildFile((File) null);
        context.setBuildFile(url);
      } catch (java.net.MalformedURLException ex) {
        throw new BuildException(ex);
      }
      buildFileName = url.toString();
    } else {
      throw new BuildException(
          "Source " + source.getClass().getName() + " not supported by this plugin");
    }
    InputStream inputStream = null;
    InputSource inputSource = null;
    ZipFile zf = null;

    try {
      /** SAX 2 style parser used to parse the given file. */
      XMLReader parser = JAXPUtils.getNamespaceXMLReader();

      String uri = null;
      if (buildFile != null) {
        uri = FILE_UTILS.toURI(buildFile.getAbsolutePath());
        inputStream = new FileInputStream(buildFile);
      } else {
        uri = url.toString();
        int pling = -1;
        if (uri.startsWith("jar:file") && (pling = uri.indexOf("!/")) > -1) {
          zf = new ZipFile(org.apache.tools.ant.launch.Locator.fromJarURI(uri), "UTF-8");
          inputStream = zf.getInputStream(zf.getEntry(uri.substring(pling + 1)));
        } else {
          inputStream = url.openStream();
        }
      }

      inputSource = new InputSource(inputStream);
      if (uri != null) {
        inputSource.setSystemId(uri);
      }
      project.log(
          "parsing buildfile "
              + buildFileName
              + " with URI = "
              + uri
              + (zf != null ? " from a zip file" : ""),
          Project.MSG_VERBOSE);

      DefaultHandler hb = handler;

      parser.setContentHandler(hb);
      parser.setEntityResolver(hb);
      parser.setErrorHandler(hb);
      parser.setDTDHandler(hb);
      parser.parse(inputSource);
    } catch (SAXParseException exc) {
      Location location =
          new Location(exc.getSystemId(), exc.getLineNumber(), exc.getColumnNumber());

      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        BuildException be = (BuildException) t;
        if (be.getLocation() == Location.UNKNOWN_LOCATION) {
          be.setLocation(location);
        }
        throw be;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t, location);
    } catch (SAXException exc) {
      Throwable t = exc.getException();
      if (t instanceof BuildException) {
        throw (BuildException) t;
      }
      throw new BuildException(exc.getMessage(), t == null ? exc : t);
    } catch (FileNotFoundException exc) {
      throw new BuildException(exc);
    } catch (UnsupportedEncodingException exc) {
      throw new BuildException("Encoding of project file " + buildFileName + " is invalid.", exc);
    } catch (IOException exc) {
      throw new BuildException(
          "Error reading project file " + buildFileName + ": " + exc.getMessage(), exc);
    } finally {
      FileUtils.close(inputStream);
      ZipFile.closeQuietly(zf);
    }
  }
Esempio n. 23
0
 public void logFooter(int failures) {
   project.log(" ");
   project.log("FAILURES: " + failures);
   project.log("--------------------------------------------------------------------------");
 }
    /**
     * 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());
    }
    /**
     * 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()});
        }
      }
    }
Esempio n. 26
0
  @Override
  public void run() {
    File destinationFile =
        new File(
            destination,
            artifact.getArtifactId()
                + ((options.isStripVersions()) ? "" : "-" + artifact.getVersion())
                + (artifact.getClassifier().isEmpty() ? "" : ("-" + artifact.getClassifier()))
                + ".jar");
    for (String server : options.getServers()) {
      URL u = artifact.toURL(server);
      HttpURLConnection con = null;
      BufferedInputStream bis = null;
      BufferedOutputStream bos = null;

      try {
        if (!isUpToDate(u, destinationFile)) {
          con = URLSupport.openURL(u, options.getProxyServer());
          con.setConnectTimeout(CONNECTION_TIMEOUT);
          con.connect();

          bis = new BufferedInputStream(con.getInputStream());
          bos = new BufferedOutputStream(new FileOutputStream(destinationFile));
          Deque<TransferBuffer> dq = new ArrayDeque<TransferBuffer>();

          ArtifactReader r =
              new ArtifactReader(
                  project,
                  bis,
                  dq,
                  BUFFER_SIZE,
                  options.isCheckSHADigests() && !artifact.getDigest().isEmpty());
          Thread rt = new Thread(r);
          rt.start();

          ArtifactWriter w = new ArtifactWriter(project, bos, dq);
          Thread wt = new Thread(w);
          wt.start();

          rt.join();
          wt.join();

          if (r.wasSuccessful() && w.wasSuccessful()) {
            if (options.isCheckSHADigests() && !artifact.getDigest().isEmpty()) {
              if (!digestEquals(artifact, r.getDigest())) {
                artifact.setStatus(Artifact.Status.DIGEST_MISMATCH);
                destinationFile.deleteOnExit();
                project.log(
                    "download failed with incorrect digest: "
                        + artifact
                        + " - actual: "
                        + byteArrayDigestToHexString(r.getDigest()),
                    Project.MSG_ERR);
                return;
              }
            }
            artifact.setStatus(Artifact.Status.DOWNLOADED);
          }
        } else {
          artifact.setStatus(Artifact.Status.UPTODATE);
        }

        project.log(
            "download successful: " + artifact,
            (artifact.getStatus() != Artifact.Status.UPTODATE)
                ? Project.MSG_ERR
                : Project.MSG_VERBOSE);
        return;
      } catch (Exception e) {
        if (!YankTask.SOURCE_CLASSIFIER.equals(artifact.getClassifier())) {
          project.log(e.getMessage(), e, Project.MSG_VERBOSE);
          project.log("download failed: " + artifact, Project.MSG_ERR);
        }
        artifact.setStatus(Artifact.Status.FAILED);
      } finally {
        Closer.close(bis);
        Closer.close(bos);
        Closer.close(con);
      }
    }
  }