org.apache.tools.ant.BuildException Java Examples

The following examples show how to use org.apache.tools.ant.BuildException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CheckHelpSets.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void execute() throws BuildException {
    for(FileSet fs: filesets) {
        FileScanner scanner = fs.getDirectoryScanner(getProject());
        File dir = scanner.getBasedir();
        String[] files = scanner.getIncludedFiles();
        for (int i = 0; i < files.length; i++) {
            File helpset = new File(dir, files[i]);
            try {
                checkHelpSet(helpset);
            } catch (BuildException be) {
                throw be;
            } catch (Exception e) {
                throw new BuildException("Error checking helpset", e, new Location(helpset.getAbsolutePath()));
            }
        }
    }
}
 
Example #2
Source File: ParseManifest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    if (manifest == null) {
        throw new BuildException("Must specify parameter 'manifest'.");
    }
    if (property == null) {
        throw new BuildException("Must specify parameter 'property'.");
    }
    if (attribute == null) {
        throw new BuildException("Must specify parameter 'attribute'.");
    }
    try {
        try (BufferedInputStream is = new BufferedInputStream(new FileInputStream(manifest))) {
            Manifest mf = new Manifest(is);
            String attr = mf.getMainAttributes().getValue(attribute);
            if (attr == null)
                return;
            getProject().setProperty(property, attr);
        }
    } catch (Exception x) {
        throw new BuildException("Reading manifest " + manifest + ": " + x, x, getLocation());
    }
}
 
Example #3
Source File: CopyTemplatePageTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    checkParameters();
    try {
        final BufferedReader in = new BufferedReader(new FileReader(template)); //todo: encoding
        try {
            final PrintWriter out = new PrintWriter (new FileWriter(destFile)); //todo: encoding
            try {
                copy (in,out);
            } finally {
                out.close();
            }
        } finally {
            in.close();
        }
    } catch (IOException ioe) {
        throw new BuildException(ioe, getLocation());
    }
}
 
Example #4
Source File: WebtestTask.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
public final void execute() throws BuildException {
    ClassLoader defaultCL = ServiceFactory.replaceClassloader();
    try {
        executeInternal();
    } catch (Throwable e) {
        if (e instanceof BuildException) {
            log("Build exception " + e.getMessage(), 0);
            throw (BuildException) e;
        } else {
            if (e instanceof WebtestTaskException) {
                // just a message carrier
                throwBuildException(e.getMessage());
            } else {
                throwBuildException(null, e);
            }
        }
    } finally {
        Thread.currentThread().setContextClassLoader(defaultCL);
        log(ServiceFactory.getHeapInfo());
    }
}
 
Example #5
Source File: MithraObjectXmlGenerator.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public Map<String, TableInfo> processTableInfo()
{
    Connection connection = null;
    try
    {
        initialize();
        connection = getConnection();

        DatabaseMetaData metaData = connection.getMetaData();
        this.log("getting table information.", Project.MSG_DEBUG);
        ArrayList<String> tableNameList = this.getTableNameListByTypes(metaData, includeList, new String[]{"TABLE"});
        this.populateTableInfoMap(metaData, tableNameList);
        return this.tables;
    }
    catch (SQLException e)
    {
        this.log(e.getMessage(), Project.MSG_ERR);
        throw new BuildException();
    }
    finally
    {
        this.closeConnection(connection);
    }

}
 
Example #6
Source File: XtendCompilerAntTask.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
private void validateArgs() {
	if (getDestdir() == null) {
		throw new BuildException("Destination directory 'destdir' is required.");
	}
	Path srcDirs = getSrcdir();
	if (srcDirs == null) {
		throw new BuildException("Sources directory 'srcdir' is required.");
	}
	Iterator<?> pathIter = srcDirs.iterator();
	while (pathIter.hasNext()) {
		Object next = pathIter.next();
		if (!(next instanceof Resource && ((Resource) next).isDirectory())) {
			throw new BuildException("Source directory must be a directory. Check 'srcdir' entry: " + next);
		}
	}
}
 
Example #7
Source File: BasicStyleCheckerTask.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    BasicStyleCheckerEngine engine = new BasicStyleCheckerEngine();
    
    try {
        for (FileSet fileset: filesets) {
            final DirectoryScanner scanner =
                    fileset.getDirectoryScanner(getProject());
            
            for (String filename: scanner.getIncludedFiles()) {
                final File file =
                        new File(fileset.getDir(getProject()), filename);
                
                System.out.println(file.getCanonicalPath());
                engine.check(file);
            }
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
 
Example #8
Source File: BundleMvnAntTask.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Set an attribute on the named target element. The target element must exist
 * and be a child of the project-element.
 *
 * @param el
 *          The element owning the target element to be updated.
 * @param name
 *          The name of the target-element to set an attribute for.
 * @param attrName
 *          The name of the attribute to set.
 * @param attrValue
 *          The new attribute value.
 */
private void setTargetAttr(final Element el, final String name, final String attrName, final String attrValue) {
  final NodeList propertyNL = el.getElementsByTagName("target");
  boolean found = false;
  for (int i = 0; i<propertyNL.getLength(); i++) {
    final Element target = (Element) propertyNL.item(i);
    if (name.equals(target.getAttribute("name"))) {
      log("Setting <target name=\"" +name +"\" attrName =\"" +attrValue +"\" ...>.", Project.MSG_DEBUG);
      target.setAttribute(attrName, attrValue);
      found = true;
      break;
    }
  }
  if (!found) {
    throw new BuildException("No <property name=\"" +name +"\" ...> in XML document " +el);
  }
}
 
Example #9
Source File: JMXQueryTask.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Execute the requested operation.
 *
 * @exception BuildException if an error occurs
 */
@Override
public void execute() throws BuildException {
    super.execute();
    String queryString;
    if (query == null) {
        queryString = "";
    } else {
        try {
            queryString = "?qry=" + URLEncoder.encode(query, getCharset());
        } catch (UnsupportedEncodingException e) {
            throw new BuildException
                ("Invalid 'charset' attribute: " + getCharset());
        }
    }
    log("Query string is " + queryString);
    execute ("/jmxproxy/" + queryString);
}
 
Example #10
Source File: AntHarnessTest.java    From ExpectIt with Apache License 2.0 6 votes vote down vote up
@Test
public void runTarget() throws IOException {
    Project project = newProject();
    project.log("started: " + target);
    // prepare
    project.executeTarget("");
    boolean negative = target.endsWith("-negative");
    // run test
    try {
        project.executeTarget(target);
        if (negative) {
            fail("Negative test fails");
        }
    } catch (BuildException e) {
        e.printStackTrace();
        if (!negative) {
            fail("Positive test fails");
        }
    } finally {
        project.log("finished");
    }
}
 
Example #11
Source File: JNLPUpdateManifestStartup.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    File tmpFile = null;
    try {
        if (isSigned(jar) == null) {
            tmpFile = extendLibraryManifest(getProject(), jar, destJar, codebase, permissions, appName);
        }
    } catch (IOException | ManifestException ex) {
        getProject().log(
                "Failed to extend libraries manifests: " + ex.getMessage(), //NOI18N
                Project.MSG_WARN);
    }
    if (tmpFile != null) {
        sign(tmpFile, destJar);
        deleteTmpFile(tmpFile);
    } else {
        sign(jar, destJar);
    }
}
 
Example #12
Source File: Bundle.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void execute()
{
  try {
    handleClassPath();

    analyze();

    handleActivator();

    addPackageHeader(IMPORT_PACKAGE_KEY, importPackage);
    addPackageHeader(EXPORT_PACKAGE_KEY, exportPackage);

    // TODO: better merge may be needed, currently overwrites
    // pre-existing headers
    addConfiguredManifest(generatedManifest);
  } catch (final ManifestException me) {
    throw new BuildException("Error merging manifest headers", me);
  }
  super.execute();
}
 
Example #13
Source File: NativeUntar.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    try {
        Utils.setProject(getProject());
        log("trying native untar");
        
        Utils.nativeUntar(source, dest);
    } catch (IOException e) {
        log("native untar failed, falling back to java implementation");
        
        Utils.delete(dest);
        UntarCompressionMethod compression = new UntarCompressionMethod();
        if(source.getName().endsWith(".tar.gz") || source.getName().endsWith(".tgz")) {
            compression.setValue("gzip");
        } else if(source.getName().endsWith(".tar.bz2") || source.getName().endsWith(".tar.bzip2")) {
            compression.setValue("bzip2");
        } else {
            compression.setValue("none");
        }
        setCompression(compression);
        super.execute();
    }
}
 
Example #14
Source File: EtlTemplateTaskTest.java    From scriptella-etl with Apache License 2.0 6 votes vote down vote up
public void test() {
    EtlTemplateTask t = new EtlTemplateTask() {
        @Override//Verify that data migrator template is used
        protected void create(TemplateManager tm, Map<String, ?> properties) throws IOException {
            assertTrue(tm instanceof DataMigrator);
            props = properties;
        }

        @Override//Return mock properties to isolate from Ant
        protected Map<String, ?> getProperties() {
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("a", "AA");
            m.put("b", "BB");
            return m;
        }
    };
    try {
        t.execute();
        fail("Required attribute exception expected");
    } catch (BuildException e) {
        //OK
    }
    t.setName(DataMigrator.class.getSimpleName());
    t.execute();
    assertTrue(props != null && "AA".equals(props.get("a")) && props.size() == 2);
}
 
Example #15
Source File: Issue50Test.java    From ph-schematron with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureFatal ()
{
  try
  {
    m_aBuildRule.configureProject ("src/test/resources/issues/50/build-fail-fatal.xml");
    m_aBuildRule.getProject ().setBaseDir (new File ("src/test/resources/issues/50"));
    m_aBuildRule.getProject ().addBuildListener (new LoggingBuildListener ());
    m_aBuildRule.getProject ().executeTarget ("schematron");
    fail ();
  }
  catch (final BuildException ex)
  {
    // Expected
  }
}
 
Example #16
Source File: JMXAccessorTask.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Execute the specified command. This logic only performs the common
 * attribute validation required by all subclasses; it does not perform any
 * functional logic directly.
 * 
 * @exception BuildException
 *                if a validation error occurs
 */
@Override
public void execute() throws BuildException {
    if (testIfCondition() && testUnlessCondition()) {
        try {
            String error = null;

            MBeanServerConnection jmxServerConnection = getJMXConnection();
            error = jmxExecute(jmxServerConnection);
            if (error != null && isFailOnError()) {
                // exception should be thrown only if failOnError == true
                // or error line will be logged twice
                throw new BuildException(error);
            }
        } catch (Exception e) {
            if (isFailOnError()) {
                throw new BuildException(e);
            } else {
                handleErrorOutput(e.getMessage());
            }
        } finally {
            closeRedirector();
        }
    }
}
 
Example #17
Source File: MemberSpecificationElement.java    From proguard with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parses the given string as a value or value range of the given primitive
 * type. For example, values "123" or "100..199" of type "int" ("I").
 */
private Number[] parseValues(String externalType,
                             String internalType,
                             String string)
throws BuildException
{
    int rangeIndex = string.lastIndexOf("..");
    return rangeIndex >= 0 ?
        new Number[]
        {
            parseValue(externalType, internalType, string.substring(0, rangeIndex)),
            parseValue(externalType, internalType, string.substring(rangeIndex + 2))
        } :
        new Number[]
        {
            parseValue(externalType, internalType, string)
        };
}
 
Example #18
Source File: MakeJNLP.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void processIndirectFiles(Writer fileWriter, String dashcnb) throws IOException, BuildException {
    if (indirectFiles == null) {
        return;
    }
    DirectoryScanner scan = indirectFiles.getDirectoryScanner(getProject());
    Map<String,File> entries = new LinkedHashMap<>();
    for (String f : scan.getIncludedFiles()) {
        entries.put(f.replace(File.separatorChar, '/'), new File(scan.getBasedir(), f));
    }
    if (entries.isEmpty()) {
        return;
    }
    File ext = new File(new File(targetFile, dashcnb), "extra-files.jar");
    Zip jartask = (Zip) getProject().createTask("jar");
    jartask.setDestFile(ext);
    for (Map.Entry<String,File> entry : entries.entrySet()) {
        ZipFileSet zfs = new ZipFileSet();
        zfs.setFile(entry.getValue());
        zfs.setFullpath("META-INF/files/" + entry.getKey());
        jartask.addZipfileset(zfs);
    }
    jartask.execute();
    fileWriter.write(constructJarHref(ext, dashcnb));
    signOrCopy(ext, null);
}
 
Example #19
Source File: LaunchTask.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
public String getExecutable() {
  String os = System.getProperty("os.name").toLowerCase();
  String dirPath = dir.getAbsolutePath();
  String base = dirPath+FILESEPARATOR+script;
  if (exists(base)) {
    return base;
  }
  
  if (os.indexOf("windows")!=-1) {
    if (exists(base+".exe")) {
      return base+".exe";
    }
    if (exists(base+".bat")) {
      return base+".bat";
    }
  }
    
  if (os.indexOf("linux")!=-1 || os.indexOf("mac")!=-1) {
    if (exists(base+".sh")) {
      return base+".sh";
    }
  }

  throw new BuildException("couldn't find executable for script "+base);
}
 
Example #20
Source File: FileFinder.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
/**
 * Returns an array with the file names of the specified file pattern that have been found in the workspace.
 *
 * @param workspace
 *         root directory of the workspace
 *
 * @return the file names of all found files
 */
public String[] find(final File workspace) {
    try {
        FileSet fileSet = new FileSet();
        Project antProject = new Project();
        fileSet.setProject(antProject);
        fileSet.setDir(workspace);
        fileSet.setIncludes(includesPattern);
        TypeSelector selector = new TypeSelector();
        FileType fileType = new FileType();
        fileType.setValue(FileType.FILE);
        selector.setType(fileType);
        fileSet.addType(selector);
        if (StringUtils.isNotBlank(excludesPattern)) {
            fileSet.setExcludes(excludesPattern);
        }
        fileSet.setFollowSymlinks(followSymlinks);

        return fileSet.getDirectoryScanner(antProject).getIncludedFiles();
    }
    catch (BuildException ignored) {
        return new String[0]; // as fallback do not return any file
    }
}
 
Example #21
Source File: GitSettingsTask.java    From ant-git-tasks with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
        final GitSettings settings = new GitSettings();

        if (!GitTaskUtils.isNullOrBlankString(username) && !GitTaskUtils.isNullOrBlankString(password)) {
                settings.setCredentials(username, password);
        }

        if (!GitTaskUtils.isNullOrBlankString(name) && !GitTaskUtils.isNullOrBlankString(email)) {
                settings.setIdentity(name, email);
        }

        getProject().addReference(refId, new Reference(getProject(), refId) {
                        public GitSettings getReferencedObject(Project fallback) throws BuildException {
                                return settings;
                        }
                });
}
 
Example #22
Source File: LicensesPackageTask.java    From development with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws BuildException {
    if (packagefile == null) {
        throw new BuildException("No package file set.");
    }
    if (packagefile == null) {
        throw new BuildException("No licenses location set.");
    }
    if (outputdir == null) {
        throw new BuildException("No output location set.");
    }
    Set<String> references = findProjectReferences();

    IFileSet fileset = createFileSet(references);
    writeFiles(fileset);
}
 
Example #23
Source File: RccTask.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private void doCompile(File file) throws BuildException {
  String[] args = new String[5];
  args[0] = "--language";
  args[1] = this.language;
  args[2] = "--destdir";
  args[3] = this.dest.getPath();
  args[4] = file.getPath();
  int retVal = Rcc.driver(args);
  if (retVal != 0 && failOnError) {
    throw new BuildException("Hadoop record compiler returned error code "+retVal);
  }
}
 
Example #24
Source File: FindBugsTask.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Check that all required attributes have been set
 */
@Override
protected void checkParameters() {
    super.checkParameters();

    if (projectFile == null && classLocations.size() == 0 && filesets.size() == 0 && dirsets.size() == 0 && auxAnalyzepath == null) {
        throw new BuildException("either projectfile, <class/>, <fileset/> or <auxAnalyzepath/> child "
                + "elements must be defined for task <" + getTaskName() + "/>", getLocation());
    }

    if (outputFormat != null
            && !("xml".equalsIgnoreCase(outputFormat.trim()) || "xml:withMessages".equalsIgnoreCase(outputFormat.trim())
                    || "html".equalsIgnoreCase(outputFormat.trim()) || "text".equalsIgnoreCase(outputFormat.trim())
                    || "xdocs".equalsIgnoreCase(outputFormat.trim()) || "emacs".equalsIgnoreCase(outputFormat.trim()))) {
        throw new BuildException("output attribute must be either " + "'text', 'xml', 'html', 'xdocs' or 'emacs' for task <"
                + getTaskName() + "/>", getLocation());
    }

    if (reportLevel != null
            && !("experimental".equalsIgnoreCase(reportLevel.trim()) || "low".equalsIgnoreCase(reportLevel.trim())
                    || "medium".equalsIgnoreCase(reportLevel.trim()) || "high".equalsIgnoreCase(reportLevel.trim()))) {
        throw new BuildException("reportlevel attribute must be either "
                + "'experimental' or 'low' or 'medium' or 'high' for task <" + getTaskName() + "/>", getLocation());
    }

    // FindBugs allows both, so there's no apparent reason for this check
    // if ( excludeFile != null && includeFile != null ) {
    // throw new BuildException("only one of excludeFile and includeFile " +
    // " attributes may be used in task <" + getTaskName() + "/>",
    // getLocation());
    // }

    List<String> efforts = Arrays.asList("min", "less", "default", "more", "max");
    if (effort != null && !efforts.contains(effort)) {
        throw new BuildException("effort attribute must be one of " + efforts);
    }
}
 
Example #25
Source File: CslJar.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element mkdirs(Document doc, String path) throws BuildException {
    String tagName = doc.getDocumentElement().getTagName();
    if (!tagName.equals(FILESYSTEM)) { // NOI18N
        throw new BuildException("Unexpected layer root element: " + tagName);
    }

    return mkdirs(doc.getDocumentElement(), path);
}
 
Example #26
Source File: BundlePackagesInfo.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Try to assign a version to the Java that the given
 * <code>packageinfo</code>-file resides in. This code assumes that
 * the resource has been created in such a way that
 * <code>res.getName()</code> returns a relative path to the
 * <code>packageinfo</code>-file that starts in its package
 * root. I.e., the path is the Java package that the
 * <code>packageinfo</code>-file provides data for.
 *
 * @param res Resource encapsulating a <code>packageinfo</code>-file.
 * @return The package name or <code>null</code> if no valid version was
 *         found.
 */
public String setPackageVersion(final Resource res)
{
  // The relative path to packageinfo-file starting from the root of
  // its classpath. Allways using forward slash as separator char.
  final String pkgInfoPath = res.getName().replace(File.separatorChar, '/');
  // 12 = "/packageinfo".lenght()
  final String pkgName = pkgInfoPath.substring(0, pkgInfoPath.length()-12);

  // Currently registered path for version providing packageinfo
  // file, if any.
  final String curPkgInfoPath = packageToInfofile.get(pkgName);

  if (null==curPkgInfoPath || !curPkgInfoPath.equals(pkgInfoPath)) {
    final Version newVersion = getVersion(res);
    if (null!=newVersion) {
      final Version curVersion = getProvidedPackageVersion(pkgName);

      if (null==curVersion) {
        packageToVersion.put(pkgName, newVersion);
        packageToInfofile.put(pkgName, pkgInfoPath);
        task.log("Package version for '" +pkgName +"' set to "
                 +newVersion +" based on data from '" +pkgInfoPath +"'.",
                 Project.MSG_VERBOSE);
        return pkgName;
      } else if (!newVersion.equals(curVersion)) {
        // May happen when the classes of a package are in two
        // different directories on the class path.
        throw new BuildException("Conflicting versions for '"
                                 +pkgName +"' previous  '"
                                 +curVersion +"' from '"
                                 +curPkgInfoPath +"', new '"
                                 +newVersion +"' in '"
                                 +pkgInfoPath +"'.");
      }
    }
  }
  return null;
}
 
Example #27
Source File: ModuleTestDependencies.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element getConfig(File projectXml, Document pDoc) throws BuildException {
    Element e = pDoc.getDocumentElement();
    Element c = XMLUtil.findElement(e, "configuration", ParseProjectXml.PROJECT_NS);
    if (c == null) {
        throw new BuildException("No <configuration>", getLocation());
    }
    Element d = ParseProjectXml.findNBMElement(c, "data");
    if (d == null) {
        throw new BuildException("No <data> in " + projectXml, getLocation());
    }
    return d;
}
 
Example #28
Source File: LayerIndex.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public InputStream getInputStream() throws IOException {
    final ZipFile z = new ZipFile(getZipfile(), ZipFile.OPEN_READ);
    ZipEntry ze = z.getEntry(super.getName());
    if (ze == null) {
        z.close();
        throw new BuildException("no entry " + getName() + " in "
                                 + getArchive());
    }
    return z.getInputStream(ze);
}
 
Example #29
Source File: GenerateJnlpFileTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void checkParameters() {
    if (destFile == null) {
        throw new BuildException("Destination file is not set, jnlp file cannot be created."); //NOI18N
    }
    if (destDir == null) {
        throw new BuildException("Destination directory is not set, jnlp file cannot be created."); //NOI18N
    }
    if (template == null) {
        throw new BuildException("Template file is not set, jnlp file cannot be created."); //NOI18N
    }
}
 
Example #30
Source File: DataConverterRegistration.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the converter class.
 *
 * @param converterClassName The fully qualified converter class name
 */
public void setClassName(String converterClassName) throws BuildException
{
    try
    {
        _converter = (SqlTypeConverter)getClass().getClassLoader().loadClass(converterClassName).newInstance();
    }
    catch (Exception ex)
    {
        throw new BuildException(ex);
    }
}