Java Code Examples for org.apache.tools.ant.Project#init()

The following examples show how to use org.apache.tools.ant.Project#init() . 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: AntHarnessTest.java    From ExpectIt with Apache License 2.0 6 votes vote down vote up
private static Project newProject() throws IOException {
    setupBuildFile();
    Project project = new Project();
    project.setUserProperty("ant.file", buildFile.getAbsolutePath());
    project.init();
    DefaultLogger listener = new DefaultLogger();
    listener.setErrorPrintStream(System.err);
    listener.setOutputPrintStream(System.out);
    listener.setMessageOutputLevel(Project.MSG_INFO);
    ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference("ant.projectHelper", helper);
    project.setProperty("ftp.port", String.valueOf(ftpPort));
    project.setProperty("ssh.port", String.valueOf(sshPort));
    helper.parse(project, buildFile);
    project.addBuildListener(listener);
    return project;
}
 
Example 2
Source File: DeliverTest.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    cache = new File("build/cache");
    System.setProperty("ivy.cache.dir", cache.getAbsolutePath());
    createCache();

    deliverDir = new File("build/test/deliver");
    deliverDir.mkdirs();

    Project project = TestHelper.newProject();
    project.init();

    ivyDeliver = new IvyDeliver();
    ivyDeliver.setProject(project);
    ivyDeliver.setDeliverpattern(deliverDir.getAbsolutePath()
            + "/[type]s/[artifact]-[revision](-[classifier]).[ext]");
}
 
Example 3
Source File: ShuffleModel.java    From Shuffle-Move with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Constructs the Project and returns it.
 * 
 * @return The Project
 * @throws Exception
 *            If anything goes wrong.
 */
private Project getErrorProject() throws Exception {
   Path buildFilePath = Paths.get(BUILD_REPORT_FILE);
   LOG.finer("Build file path set to " + String.valueOf(buildFilePath));
   Project p = new Project();
   p.setSystemProperties();
   p.setUserProperty("ant.file", buildFilePath.toAbsolutePath().toString());
   LOG.finer("Project ant.file property set.");
   p.init();
   LOG.finer("Project.init() called.");
   ProjectHelper helper = ProjectHelper.getProjectHelper();
   LOG.finer("ProjectHelper created.");
   p.addReference("ant.projectHelper", helper);
   LOG.finer("Project ant.projectHelper reference set.");
   p.addReference("user.dir", System.getProperty("user.dir"));
   LOG.finer("Project user.dir reference set.");
   helper.parse(p, buildFilePath.toAbsolutePath().toFile());
   LOG.finer("PrjectHelper.parse() called.");
   errorProject = p;
   p.addBuildListener(getBuildListener());
   LOG.finer("BuildListener added.");
   return errorProject;
}
 
Example 4
Source File: AntBuilder.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * @return Factory method to create new Project instances
 */
protected static Project createProject() {
    final Project project = new Project();

    final ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
    helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty 

    final BuildLogger logger = new NoBannerLogger();

    logger.setMessageOutputLevel(org.apache.tools.ant.Project.MSG_INFO);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.err);

    project.addBuildListener(logger);

    project.init();
    project.getBaseDir();
    return project;
}
 
Example 5
Source File: GroovycTest.java    From groovy with Apache License 2.0 6 votes vote down vote up
protected void setUp() {
    project = new Project();
    project.init();
    ProjectHelper.getProjectHelper().parse(project, antFile);
    project.executeTarget("clean");

    String altJavaHome = System.getProperty("java.home");
    if (altJavaHome.lastIndexOf("jre") >= 0) {
        altJavaHome = altJavaHome.substring(0, altJavaHome.lastIndexOf("jre"));
    } else {
        altJavaHome = altJavaHome + File.separator + "jre";
    }
    try {
        File altFile = new File(altJavaHome);
        if (altFile.exists()) {
            project.setProperty("alt.java.home", altJavaHome);
        }
    } catch (Exception ignore) {
        // could be security, io, etc.
        // End result is as if .exists() returned null
    }
}
 
Example 6
Source File: AntUtil.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @return Factory method to create new Project instances
 */
public static Project createProject() {
    final Project project = new Project();

    final ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
    helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty

    project.addBuildListener(new AntLoggingAdapter());

    project.init();
    project.getBaseDir();
    return project;
}
 
Example 7
Source File: AntDecorator.java    From oodt with Apache License 2.0 5 votes vote down vote up
public Deleter() {
    project = new Project();
    project.init();
    taskType = "delete";
    taskName = "delete";
    target = new Target();
}
 
Example 8
Source File: MyBuildFileRule.java    From ph-schematron with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up to run the named project
 *
 * @param filename
 *        name of project file to run
 * @param logLevel
 *        Log level
 * @throws BuildException
 *         on error
 */
public void configureProject (final String filename, final int logLevel) throws BuildException
{
  logBuffer = new StringBuffer ();
  fullLogBuffer = new StringBuffer ();
  project = new Project ();
  project.init ();
  final File antFile = new File (System.getProperty ("root"), filename);
  project.setProperty ("ant.processid", ProcessUtil.getProcessId ("<Process>"));
  project.setProperty ("ant.threadname", Thread.currentThread ().getName ());
  project.setUserProperty ("ant.file", antFile.getAbsolutePath ());
  project.addBuildListener (new AntTestListener (logLevel));
  ProjectHelper.configureProject (project, antFile);
}
 
Example 9
Source File: AntUtil.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @return Factory method to create new Project instances
 */
public static Project createProject() {
    final Project project = new Project();

    final ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
    helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty

    project.addBuildListener(new AntLoggingAdapter());

    project.init();
    project.getBaseDir();
    return project;
}
 
Example 10
Source File: AntUtil.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @return Factory method to create new Project instances
 */
public static Project createProject() {
    final Project project = new Project();

    final ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
    helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty

    project.addBuildListener(new AntLoggingAdapter());

    project.init();
    project.getBaseDir();
    return project;
}
 
Example 11
Source File: GroovyTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
protected void setUp() throws Exception {
    super.setUp();
    project = new Project();
    project.init();
    ProjectHelper.getProjectHelper().parse(project, antFile);
    FLAG = null;
}
 
Example 12
Source File: XtendCompilerAntTaskTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets up to run the named project
 * 
 * @param filename
 *            name of project file to run
 */
protected void configureProject(String filename) throws BuildException {
	project = new Project();
	project.init();
	File antFile = new File(System.getProperty("root"), filename);
	File depsFolder = new File(System.getProperty("root"), "target/antDeps");
	project.setUserProperty("deps.dir", depsFolder.getAbsolutePath());
	project.setUserProperty("ant.file", antFile.getAbsolutePath());
	antTestListener = new AntTestListener(Project.MSG_ERR);
	project.addBuildListener(antTestListener);
	ProjectHelper.configureProject(project, antFile);
}
 
Example 13
Source File: AntUtil.java    From pushfish-android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * @return Factory method to create new Project instances
 */
public static Project createProject() {
    final Project project = new Project();

    final ProjectHelper helper = ProjectHelper.getProjectHelper();
    project.addReference(ProjectHelper.PROJECTHELPER_REFERENCE, helper);
    helper.getImportStack().addElement("AntBuilder"); // import checks that stack is not empty

    project.addBuildListener(new AntLoggingAdapter());

    project.init();
    project.getBaseDir();
    return project;
}
 
Example 14
Source File: PackagerCacheEntry.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
/**
 * Attempt to build this entry.
 *
 * @param packagerResource
 *            packager metadata resource
 * @param properties
 *            a map of properties to pass to the child Ant build responsible for dependency
 *            packaging
 *
 * @throws IOException
 *             if this entry has already been built
 */
public synchronized void build(Resource packagerResource, Map<String, String> properties) throws IOException {
    // Sanity check
    if (this.built) {
        throw new IllegalStateException("build in directory `" + this.dir
                + "' already completed");
    }

    // Remove work directory if it exists (e.g. left over from last time)
    if (this.dir.exists()) {
        if (!cleanup()) {
            throw new IOException("can't remove directory `" + this.dir + "'");
        }
    }

    // Create work directory
    if (!this.dir.mkdirs()) {
        throw new IOException("can't create directory `" + this.dir + "'");
    }

    // Write out packager XML
    InputStream packagerXML = packagerResource.openStream();
    saveFile("packager.xml", packagerXML);

    // Write packager XSLT
    saveFile("packager.xsl");

    // Write packager XSD
    saveFile("packager-1.0.xsd");

    // Write master Ant build file
    saveFile("build.xml");

    // Execute the Ant build file
    Project project = new Project();
    project.init();
    project.setUserProperty("ant.file", new File(dir, "build.xml").getAbsolutePath());
    ProjectHelper.configureProject(project, new File(dir, "build.xml"));
    project.setBaseDir(dir);

    // Configure logging verbosity
    BuildLogger logger = new DefaultLogger();
    logger.setMessageOutputLevel(this.verbose ? Project.MSG_VERBOSE
            : this.quiet ? Project.MSG_WARN : Project.MSG_INFO);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.err);
    project.addBuildListener(logger);

    // Set properties
    project.setUserProperty("ivy.packager.organisation", ""
            + this.mr.getModuleId().getOrganisation());
    project.setUserProperty("ivy.packager.module", "" + this.mr.getModuleId().getName());
    project.setUserProperty("ivy.packager.revision", "" + this.mr.getRevision());
    project.setUserProperty("ivy.packager.branch", "" + this.mr.getBranch());
    if (this.resourceCache != null) {
        project.setUserProperty("ivy.packager.resourceCache",
            "" + this.resourceCache.getCanonicalPath());
    }
    if (this.resourceURL != null) {
        project.setUserProperty("ivy.packager.resourceURL", "" + getResourceURL());
    }
    if (this.validate) {
        project.setUserProperty("ivy.packager.validate", "true");
    }
    project.setUserProperty("ivy.packager.restricted", "" + this.restricted);
    project.setUserProperty("ivy.packager.quiet", String.valueOf(quiet));
    if (properties != null) {
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            project.setUserProperty(entry.getKey(), entry.getValue());
        }
    }

    // Execute task
    Message.verbose("performing packager resolver build in " + this.dir);
    try {
        project.executeTarget("build");
        this.built = true;
    } catch (BuildException e) {
        Message.verbose("packager resolver build failed: " + e);
        throw e;
    }
}
 
Example 15
Source File: SqlUtils.java    From keycloak with Apache License 2.0 4 votes vote down vote up
/**
 * Run given SQL Script against specified DB
 *
 * @param sqlFilePath absolute path to the SQL file
 * @param jdbcDriverClass must be on the classpath
 * @param dbUrl
 * @param dbUsername
 * @param dbPassword
 */
public static void runSqlScript(String sqlFilePath, String jdbcDriverClass,
                           String dbUrl, String dbUsername, String dbPassword) {
    log.infof("Running SQL script from file '%s'\n jdbcDriverClass=%s\n dbUrl=%s\n dbUsername=%s\n dbPassword=%s\n",
            sqlFilePath, jdbcDriverClass, dbUrl, dbUsername, dbPassword);

    final class SqlExecuter extends SQLExec {
        public SqlExecuter() {
            Project project = new Project();
            project.init();
            setProject(project);
            setTaskType("sql");
            setTaskName("sql");
        }
    }

    SqlExecuter executer = new SqlExecuter();
    executer.setSrc(new File(sqlFilePath));
    executer.setDriver(jdbcDriverClass);
    executer.setPassword(dbPassword);
    executer.setUserid(dbUsername);
    executer.setUrl(dbUrl);

    if (dbUrl.contains("mssql") || jdbcDriverClass.contains("mssql") || jdbcDriverClass.contains("sqlserver")) {
        log.info("Using alternative delimiter due the MSSQL");
        executer.setDelimiter("GO");
        SQLExec.DelimiterType dt = new SQLExec.DelimiterType();
        dt.setValue(SQLExec.DelimiterType.ROW);
        executer.setDelimiterType(dt);
    }

    // See KEYCLOAK-3876
    if (dbUrl.contains("oracle") || jdbcDriverClass.contains("oracle")) {
        log.info("Removing 'SET DEFINE OFF' from the SQL script due the Oracle");
        try {
            String content = IOUtils.toString(new FileInputStream(sqlFilePath), StandardCharsets.UTF_8);
            content = content.replaceAll("SET DEFINE OFF;", "");
            IOUtils.write(content, new FileOutputStream(sqlFilePath), StandardCharsets.UTF_8);
        } catch (IOException fnfe) {
            throw new RuntimeException(fnfe);
        }
    }

    try {
        executer.execute();
    } catch (Exception e) {
        try {
            String sqlScript = IOUtils.toString(new FileInputStream(sqlFilePath), StandardCharsets.UTF_8);
            log.errorf("Exception during manual migration. Content of the SQL file: \n%s\n", sqlScript);
        } catch (Exception e2) {
            log.error("Exception when trying to log content of SQL file", e2);
        }

        throw e;
    }
}
 
Example 16
Source File: AntCallTriggerTest.java    From ant-ivy with Apache License 2.0 4 votes vote down vote up
private void runBuild(File buildFile, Vector<String> targets, int messageLevel) throws BuildException {

        final Project project = new Project();
        project.setCoreLoader(null);

        Throwable error = null;

        try {
            addBuildListeners(project, messageLevel);
            addInputHandler(project, null);

            PrintStream err = System.err;
            PrintStream out = System.out;
            InputStream in = System.in;

            // use a system manager that prevents from System.exit()
            SecurityManager oldsm = null;
            oldsm = System.getSecurityManager();

            // SecurityManager can not be installed here for backwards
            // compatibility reasons (PD). Needs to be loaded prior to
            // ant class if we are going to implement it.
            // System.setSecurityManager(new NoExitSecurityManager());
            try {
                project.setDefaultInputStream(System.in);
                System.setIn(new DemuxInputStream(project));
                System.setOut(new PrintStream(new DemuxOutputStream(project, false)));
                System.setErr(new PrintStream(new DemuxOutputStream(project, true)));

                project.fireBuildStarted();

                project.init();
                project.setUserProperty("ant.version", Main.getAntVersion());

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

                ProjectHelper.configureProject(project, buildFile);

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

                project.executeTargets(targets);
            } finally {
                // put back the original security manager
                // The following will never eval to true. (PD)
                if (oldsm != null) {
                    System.setSecurityManager(oldsm);
                }

                System.setOut(out);
                System.setErr(err);
                System.setIn(in);
            }
        } catch (RuntimeException | Error exc) {
            error = exc;
            throw exc;
        } finally {
            project.fireBuildFinished(error);
        }
    }
 
Example 17
Source File: ProGuardMojo.java    From code-hidding-plugin with GNU Lesser General Public License v2.1 4 votes vote down vote up
private static void proguardMain(File proguardJar, ArrayList argsList, ProGuardMojo mojo)
                                                                                         throws MojoExecutionException {

    Java java = new Java();

    Project antProject = new Project();
    antProject.setName(mojo.mavenProject.getName());
    antProject.init();

    DefaultLogger antLogger = new DefaultLogger();
    antLogger.setOutputPrintStream(System.out);
    antLogger.setErrorPrintStream(System.err);
    antLogger.setMessageOutputLevel(mojo.log.isDebugEnabled() ? Project.MSG_DEBUG
        : Project.MSG_INFO);

    antProject.addBuildListener(antLogger);
    antProject.setBaseDir(mojo.mavenProject.getBasedir());

    java.setProject(antProject);
    java.setTaskName("proguard");

    mojo.getLog().info("proguard jar: " + proguardJar);

    java.createClasspath().setLocation(proguardJar);
    // java.createClasspath().setPath(System.getProperty("java.class.path"));
    java.setClassname(mojo.proguardMainClass);

    java.setFailonerror(true);

    java.setFork(true);

    // get the maxMemory setting
    if (mojo.maxMemory != null) {
        java.setMaxmemory(mojo.maxMemory);
    }

    for (Iterator i = argsList.iterator(); i.hasNext();) {
        java.createArg().setValue(i.next().toString());
    }

    int result = java.executeJava();
    if (result != 0) {
        throw new MojoExecutionException("Obfuscation failed (result=" + result + ")");
    }
}
 
Example 18
Source File: Main.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
public static void main(String[] args) {

		Vector<Target> targets = new Vector<Target>();

		Target m2mTarget = new Target();
		m2mTarget.setName(M2M);
		Target m2tTarget = new Target();
		m2tTarget.setName(M2T);
		Target setupTarget = new Target();
		setupTarget.setName(SETUP);

		File buildFile = new File(BUILD_XML);
		Project p = new Project();
		p.setUserProperty(ANT_FILE, buildFile.getAbsolutePath());
		p.init();
		ProjectHelper helper = ProjectHelper.getProjectHelper();
		p.addReference(ANT_PROJECT_HELPER, helper);
		helper.parse(p, buildFile);

		Scanner scanner = new Scanner(System.in);
		while (true){
			System.out.println("Which transformation would you like to start? (M2M / M2T) : ");
			String target = scanner.next();
			if (target.equals(M2M)){
				System.out.println("Select the OpenAPI JSON schema to transform.");
				try {
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				chooser.setCurrentDirectory(new File(SCHEMAS_DIR));
				
				chooser.showOpenDialog(null);
				File selectedFile = chooser.getSelectedFile();
				if (selectedFile.isFile() && selectedFile.getName().endsWith(".json")){
					System.out.println(selectedFile.getName());
					
					targets.add(m2mTarget);
					break;
				} else {
					chooser = null;
					System.out.println("Something went wrong");
				}
				//p.executeSortedTargets(targets);
			} else if (target.equals(M2M)){
				//p.executeTarget(p.getDefaultTarget());
				break;
			} else { 
				System.out.println("Invalid");
			}

		}
		scanner.close();

	}
 
Example 19
Source File: InsertModuleAllTargetsTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void setUp() throws Exception {
    clearWorkDir();

    String prop = System.getProperty("nb_all");
    assertNotNull("${nb_all} defined", prop);
    nball = new File(prop);
    
    File baseDir = new File(getWorkDir(), "basedir");
    baseDir.mkdirs();
    
    File destDir = new File(getWorkDir(), "destdir");
    destDir.mkdirs();
    
    p = new Project();
    p.init();
    p.setBaseDir(nball);
    p.setProperty("netbeans.dest.dir", destDir.getAbsolutePath());
    p.setProperty("nb_all", nball.getAbsolutePath());
    
    File clusters = new File(new File(nball, "nbbuild"), "cluster.properties");
    assertTrue("cluster.properties file exists", clusters.exists());
    
    Properties clusterProps = new Properties();
    try (FileInputStream is = new FileInputStream(clusters)) {
        clusterProps.load(is);
    }
    
    for (Entry<Object, Object> en : clusterProps.entrySet()) {
        String key = en.getKey().toString();
        String value = en.getValue().toString();
        while(true) {
            Matcher m = VARIABLE_SUBST.matcher(value);
            StringBuffer sb = new StringBuffer(value.length());
            boolean modified = false;
            while (m.find()) {
                modified = true;
                String searchKey = m.group(1);
                m.appendReplacement(sb, Matcher.quoteReplacement(clusterProps.getProperty(searchKey)));
            }
            m.appendTail(sb);
            value = sb.toString();
            if(! modified) {
                break;
            }
        }
        p.setProperty(key, value);
    }
}
 
Example 20
Source File: CCGBankConvert.java    From openccg with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void main(String[] args) {
	File baseDir = new File(System.getProperty("user.dir"));
	File buildFile = new File(baseDir, "build.xml");
	
	Project project = new Project();
	
	project.init();
	
	project.setBaseDir(baseDir);
	
	ProjectHelper helper = ProjectHelper.getProjectHelper();
	
	project.setProjectReference(helper);
	
	helper.parse(project, buildFile);
	
	DefaultLogger logger = new DefaultLogger();
	logger.setErrorPrintStream(System.err);
	logger.setOutputPrintStream(System.out);
	
	project.addBuildListener(logger);
	
	project.executeTarget("convert-base");		
}