Java Code Examples for org.apache.tools.ant.BuildException

The following examples show how to use org.apache.tools.ant.BuildException. These examples are extracted from open source projects. 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 Project: Tomcat8-Source-Read   Source File: JMXQueryTask.java    License: 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 2
Source Project: development   Source File: WebtestTask.java    License: 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 3
Source Project: reladomo   Source File: MithraObjectXmlGenerator.java    License: 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 4
/**
 * 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 5
Source Project: netbeans   Source File: BasicStyleCheckerTask.java    License: 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 6
Source Project: xtext-xtend   Source File: XtendCompilerAntTask.java    License: 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 Project: ExpectIt   Source File: AntHarnessTest.java    License: 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 8
Source Project: netbeans   Source File: JNLPUpdateManifestStartup.java    License: 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 9
Source Project: development   Source File: LicensesPackageTask.java    License: 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 10
@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 11
Source Project: ph-schematron   Source File: Issue50Test.java    License: 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 12
Source Project: tomcatsrc   Source File: JMXAccessorTask.java    License: 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 13
Source Project: netbeans   Source File: MakeJNLP.java    License: 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 14
Source Project: ant-git-tasks   Source File: GitSettingsTask.java    License: 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 15
Source Project: netbeans   Source File: CheckHelpSets.java    License: 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 16
Source Project: camunda-bpm-platform   Source File: LaunchTask.java    License: 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 17
/**
 * 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 Project: scriptella-etl   Source File: EtlTemplateTaskTest.java    License: 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 19
Source Project: netbeans   Source File: NativeUntar.java    License: 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 20
Source Project: warnings-ng-plugin   Source File: FileFinder.java    License: 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 Project: netbeans   Source File: ParseManifest.java    License: 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 22
Source Project: netbeans   Source File: CopyTemplatePageTask.java    License: 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 23
Source Project: gemfirexd-oss   Source File: DropTablesCommand.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void execute(DatabaseTaskBase task, Database model) throws BuildException
{
    BasicDataSource dataSource = getDataSource();

    if (dataSource == null)
    {
        throw new BuildException("No database specified.");
    }

    Platform platform    = getPlatform();
    Database targetModel = new Database();

    if ((_tableNames != null) || (_tableNameRegExp != null))
    {
        targetModel = new CloneHelper().clone(model);
        targetModel.initialize();

        Table[] tables = _tableNames != null ? targetModel.findTables(_tableNames, task.isUseDelimitedSqlIdentifiers())
                                             : targetModel.findTables(_tableNameRegExp, task.isUseDelimitedSqlIdentifiers());

        new ModelHelper().removeForeignKeysToAndFromTables(targetModel, tables);
        targetModel.removeTables(tables);
    }
    try
    {
        platform.alterModel(model, targetModel, isFailOnError());

        _log.info("Dropped tables");
    }
    catch (Exception ex)
    {
        handleException(ex, ex.getMessage());
    }
}
 
Example 24
Source Project: netbeans   Source File: FileCRC32Calculator.java    License: Apache License 2.0 5 votes vote down vote up
public @Override void execute() throws BuildException {

        try {
            CRC32 crc32 = new CRC32();
            try(FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ)) {
                MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
                crc32.update(mbb);
            }
            getProject().setProperty(property, Long.toString(crc32.getValue()));
        } catch (IOException ex) {
            throw new BuildException(ex);
        }
    }
 
Example 25
Source Project: netbeans   Source File: ExclusionsFromLicenseInfo.java    License: Apache License 2.0 5 votes vote down vote up
public @Override void execute() throws BuildException {
    try (FileOutputStream fos = new FileOutputStream(new File(getProject().getBaseDir(), exclusionFile));
            OutputStreamWriter osw = new OutputStreamWriter(fos);
            BufferedWriter bw = new BufferedWriter(osw)) {
        Path nballPath = nball.toPath();
        List<File> licenseinfofiles = Files.walk(nballPath)
                .filter(p -> p.endsWith("licenseinfo.xml"))
                .map(p -> p.toFile())
                .collect(Collectors.toList());

        FileSet licenseinfoFileset = new FileSet();
        licenseinfoFileset.setProject(getProject());
        licenseinfoFileset.setDir(nball.getAbsoluteFile());

        for(File licenseInfoFile: licenseinfofiles) {
            Licenseinfo li = Licenseinfo.parse(licenseInfoFile);
            for(Fileset fs: li.getFilesets()) {
                for(File f: fs.getFiles()) {
                    Path relativePath = nball.toPath().relativize(f.toPath());
                    licenseinfoFileset.appendIncludes(new String[]{relativePath.toString()});
                    bw.write(relativePath.toString());
                    bw.newLine();
                }
            }
        }
        
        getProject().addReference(this.licenseinfoFileset, licenseinfoFileset);
    } catch (IOException ex) {
        throw new BuildException(ex);
    }
}
 
Example 26
Source Project: aws-ant-tasks   Source File: CreateInstanceTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the root device type of this instance. Not required.
 * 
 * @param rootDeviceType
 *            The root device type of this instance
 */
public void setRootDeviceType(String rootDeviceType) {
    try {
        this.rootDeviceType = RootDeviceType.valueOf(rootDeviceType);
    } catch (IllegalArgumentException e) {
        throw new BuildException(e.getMessage(), e);
    }
}
 
Example 27
@Override
protected void checkParameters() {
    super.checkParameters();

    if (outputFile == null) {
        throw new BuildException("output attribute is required", getLocation());
    }

    if (inputFile == null) {
        throw new BuildException("inputFile element is required");
    }

    checkBoolean(withMessages, "withMessages");
    checkBoolean(resetSource, "resetSource");
}
 
Example 28
public DataFile createDataFile() {
    if (inputFile != null) {
        throw new BuildException("only one dataFile element is allowed", getLocation());
    }
    inputFile = new DataFile();
    return inputFile;
}
 
Example 29
Source Project: groovy   Source File: SpoofTask.java    License: Apache License 2.0 5 votes vote down vote up
public void execute() throws BuildException {
    SpoofTaskContainer.spoof("begin SpoofTask execute");
    SpoofTaskContainer.spoof("tag name from wrapper: " + getWrapper().getElementTag());
    // don't rely on Map.toString(), behaviour is not documented
    SpoofTaskContainer.spoof("attributes map from wrapper: "
            + InvokerHelper.toMapString(getWrapper().getAttributeMap()));
    SpoofTaskContainer.spoof("param foo: " + foo);

    SpoofTaskContainer.spoof("end SpoofTask execute");
}
 
Example 30
Source Project: Tomcat7.0.67   Source File: JMXAccessorGetTask.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Execute the specified command, based on the configured properties. The
 * input stream will be closed upon completion of this task, whether it was
 * executed successfully or not.
 * 
 * @exception BuildException
 *                if an error occurs
 */
@Override
public String jmxExecute(MBeanServerConnection jmxServerConnection)
    throws Exception {

    if (getName() == null) {
        throw new BuildException("Must specify a 'name'");
    }
    if ((attribute == null)) {
        throw new BuildException(
                "Must specify a 'attribute' for get");
    }
    return  jmxGet(jmxServerConnection, getName());
 }