Java Examples for org.apache.tools.ant.types.Path

The following java examples will help you to understand the usage of org.apache.tools.ant.types.Path. These source code samples are taken from different open source projects.

Example 1
Project: betsy-master  File: CamundaResourcesGenerator.java View source code
public Path generateWar() {
    //directory structure
    Path pomDir = destDir.resolve("META-INF/maven").resolve(groupId).resolve(processName);
    Path classesDir = destDir.resolve("WEB-INF/classes");
    Path srcDestDir = destDir.resolve("../src").normalize().toAbsolutePath();
    //setup infrastructure
    FileTasks.mkdirs(pomDir);
    FileTasks.mkdirs(classesDir);
    FileTasks.mkdirs(srcDestDir);
    //generate pom.properties
    FileTasks.createFile(pomDir.resolve("pom.properties"), "version=" + version + "\ngroupId=" + groupId + "\nartifactId=" + processName);
    //generate pom
    generatePom(pomDir);
    generateProcessesXml(classesDir);
    // dirty hack - as this has to be done once for the whole system
    new BPMNTester().setupPathToToolsJarForJavacAntTask();
    NetworkTasks.downloadFileFromBetsyRepo("javaee-api-7.0.jar");
    NetworkTasks.downloadFileFromBetsyRepo("camunda-engine-7.0.0-Final.jar");
    // generate and compile sources
    generateServletProcessApplication(srcDestDir);
    compileServletProcessApplication(srcDestDir, classesDir);
    return createWar();
}
Example 2
Project: jaxb2-commons-master  File: XJC2Task.java View source code
protected void hack() {
    try {
        final Field declaredField = getClass().getSuperclass().getDeclaredField("classpath");
        declaredField.setAccessible(true);
        final Path path = (Path) declaredField.get(this);
        if (path != null) {
            for (String pathElement : path.list()) {
                options.classpaths.add(new File(pathElement).toURI().toURL());
            }
        }
    } catch (Exception ex) {
        throw new BuildException(ex);
    }
}
Example 3
Project: android-gradle-plugin-master  File: ApkBuilderTask.java View source code
@Override
public void execute() throws BuildException {
    File outputFile;
    if (mApkFilepath != null) {
        outputFile = new File(mApkFilepath);
    } else {
        throw new BuildException("missing attribute 'apkFilepath'");
    }
    if (mResourceFile == null) {
        throw new BuildException("missing attribute 'resourcefile'");
    }
    if (mOutFolder == null) {
        throw new BuildException("missing attribute 'outfolder'");
    }
    // check dexPath is only one file.
    File dexFile = null;
    if (mHasCode) {
        String[] dexFiles = mDexPath.list();
        if (dexFiles.length != 1) {
            throw new BuildException(String.format("Expected one dex file but path value resolve to %d files.", dexFiles.length));
        }
        dexFile = new File(dexFiles[0]);
    }
    try {
        // build list of input files/folders to compute dependencies
        // add the content of the zip files.
        List<InputPath> inputPaths = new ArrayList<InputPath>();
        // resource file
        InputPath resourceInputPath = new InputPath(new File(mOutFolder, mResourceFile));
        inputPaths.add(resourceInputPath);
        // dex file
        if (dexFile != null) {
            inputPaths.add(new InputPath(dexFile));
        }
        // zip input files
        List<File> zipFiles = new ArrayList<File>();
        for (Path pathList : mZipList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                zipFiles.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now go through the list of source folders used to add non java files.
        List<File> sourceFolderList = new ArrayList<File>();
        if (mHasCode) {
            for (Path pathList : mSourceList) {
                for (String path : pathList.list()) {
                    File f = new File(path);
                    sourceFolderList.add(f);
                    // because this is a source folder but we only care about non
                    // java files.
                    inputPaths.add(new SourceFolderInputPath(f));
                }
            }
        }
        // now go through the list of jar folders.
        List<File> jarFileList = new ArrayList<File>();
        for (Path pathList : mJarfolderList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    String[] filenames = folder.list(new FilenameFilter() {

                        @Override
                        public boolean accept(File dir, String name) {
                            return PATTERN_JAR_EXT.matcher(name).matches();
                        }
                    });
                    for (String filename : filenames) {
                        File f = new File(folder, filename);
                        jarFileList.add(f);
                        inputPaths.add(new InputPath(f));
                    }
                }
            }
        }
        // now go through the list of jar files.
        for (Path pathList : mJarfileList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                jarFileList.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now the native lib folder.
        List<FileEntry> nativeFileList = new ArrayList<FileEntry>();
        for (Path pathList : mNativeList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    List<FileEntry> entries = ApkBuilder.getNativeFiles(folder, mDebugPackaging);
                    // add the list to the list of native files and then create an input
                    // path for each file
                    nativeFileList.addAll(entries);
                    for (FileEntry entry : entries) {
                        inputPaths.add(new InputPath(entry.mFile));
                    }
                }
            }
        }
        // Finally figure out the path to the dependency file.
        String depFile = outputFile.getAbsolutePath() + ".d";
        // check dependencies
        if (initDependencies(depFile, inputPaths) && dependenciesHaveChanged() == false) {
            System.out.println("No changes. No need to create apk.");
            return;
        }
        if (mDebugSigning) {
            System.out.println(String.format("Creating %s and signing it with a debug key...", outputFile.getName()));
        } else {
            System.out.println(String.format("Creating %s for release...", outputFile.getName()));
        }
        ApkBuilder apkBuilder = new ApkBuilder(outputFile, resourceInputPath.getFile(), dexFile, mDebugSigning ? ApkBuilder.getDebugKeystore() : null, mVerbose ? System.out : null);
        apkBuilder.setDebugMode(mDebugPackaging);
        // add the content of the zip files.
        for (File f : zipFiles) {
            if (mVerbose) {
                System.out.println("Zip Input: " + f.getAbsolutePath());
            }
            apkBuilder.addZipFile(f);
        }
        // now go through the list of file to directly add the to the list.
        for (File f : sourceFolderList) {
            if (mVerbose) {
                System.out.println("Source Folder Input: " + f.getAbsolutePath());
            }
            apkBuilder.addSourceFolder(f);
        }
        // now go through the list of jar files.
        for (File f : jarFileList) {
            if (mVerbose) {
                System.out.println("Jar Input: " + f.getAbsolutePath());
            }
            apkBuilder.addResourcesFromJar(f);
        }
        // and finally the native files
        apkBuilder.addNativeLibraries(nativeFileList);
        // close the archive
        apkBuilder.sealApk();
        // and generate the dependency file
        generateDependencyFile(depFile, inputPaths, outputFile.getAbsolutePath());
    } catch (DuplicateFileException e) {
        System.err.println(String.format("Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()));
        throw new BuildException(e);
    } catch (ApkCreationException e) {
        throw new BuildException(e);
    } catch (SealedApkException e) {
        throw new BuildException(e);
    } catch (IllegalArgumentException e) {
        throw new BuildException(e);
    }
}
Example 4
Project: android-platform-tools-base-master  File: ApkBuilderTask.java View source code
@Override
public void execute() throws BuildException {
    File outputFile;
    if (mApkFilepath != null) {
        outputFile = new File(mApkFilepath);
    } else {
        throw new BuildException("missing attribute 'apkFilepath'");
    }
    if (mResourceFile == null) {
        throw new BuildException("missing attribute 'resourcefile'");
    }
    if (mOutFolder == null) {
        throw new BuildException("missing attribute 'outfolder'");
    }
    // check dexPath is only one file.
    File dexFile = null;
    if (mHasCode) {
        String[] dexFiles = mDexPath.list();
        if (dexFiles.length != 1) {
            throw new BuildException(String.format("Expected one dex file but path value resolve to %d files.", dexFiles.length));
        }
        dexFile = new File(dexFiles[0]);
    }
    try {
        // build list of input files/folders to compute dependencies
        // add the content of the zip files.
        List<InputPath> inputPaths = new ArrayList<InputPath>();
        // resource file
        InputPath resourceInputPath = new InputPath(new File(mOutFolder, mResourceFile));
        inputPaths.add(resourceInputPath);
        // dex file
        if (dexFile != null) {
            inputPaths.add(new InputPath(dexFile));
        }
        // zip input files
        List<File> zipFiles = new ArrayList<File>();
        for (Path pathList : mZipList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                zipFiles.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now go through the list of source folders used to add non java files.
        List<File> sourceFolderList = new ArrayList<File>();
        if (mHasCode) {
            for (Path pathList : mSourceList) {
                for (String path : pathList.list()) {
                    File f = new File(path);
                    sourceFolderList.add(f);
                    // because this is a source folder but we only care about non
                    // java files.
                    inputPaths.add(new SourceFolderInputPath(f));
                }
            }
        }
        // now go through the list of jar folders.
        List<File> jarFileList = new ArrayList<File>();
        for (Path pathList : mJarfolderList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    String[] filenames = folder.list(new FilenameFilter() {

                        @Override
                        public boolean accept(File dir, String name) {
                            return PATTERN_JAR_EXT.matcher(name).matches();
                        }
                    });
                    for (String filename : filenames) {
                        File f = new File(folder, filename);
                        jarFileList.add(f);
                        inputPaths.add(new InputPath(f));
                    }
                }
            }
        }
        // now go through the list of jar files.
        for (Path pathList : mJarfileList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                jarFileList.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now the native lib folder.
        List<FileEntry> nativeFileList = new ArrayList<FileEntry>();
        for (Path pathList : mNativeList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    List<FileEntry> entries = ApkBuilder.getNativeFiles(folder, mDebugPackaging);
                    // add the list to the list of native files and then create an input
                    // path for each file
                    nativeFileList.addAll(entries);
                    for (FileEntry entry : entries) {
                        inputPaths.add(new InputPath(entry.mFile));
                    }
                }
            }
        }
        // Finally figure out the path to the dependency file.
        String depFile = outputFile.getAbsolutePath() + ".d";
        // check dependencies
        if (initDependencies(depFile, inputPaths) && dependenciesHaveChanged() == false) {
            System.out.println("No changes. No need to create apk.");
            return;
        }
        if (mDebugSigning) {
            System.out.println(String.format("Creating %s and signing it with a debug key...", outputFile.getName()));
        } else {
            System.out.println(String.format("Creating %s for release...", outputFile.getName()));
        }
        ApkBuilder apkBuilder = new ApkBuilder(outputFile, resourceInputPath.getFile(), dexFile, mDebugSigning ? ApkBuilder.getDebugKeystore() : null, mVerbose ? System.out : null);
        apkBuilder.setDebugMode(mDebugPackaging);
        // add the content of the zip files.
        for (File f : zipFiles) {
            if (mVerbose) {
                System.out.println("Zip Input: " + f.getAbsolutePath());
            }
            apkBuilder.addZipFile(f);
        }
        // now go through the list of file to directly add the to the list.
        for (File f : sourceFolderList) {
            if (mVerbose) {
                System.out.println("Source Folder Input: " + f.getAbsolutePath());
            }
            apkBuilder.addSourceFolder(f);
        }
        // now go through the list of jar files.
        for (File f : jarFileList) {
            if (mVerbose) {
                System.out.println("Jar Input: " + f.getAbsolutePath());
            }
            apkBuilder.addResourcesFromJar(f);
        }
        // and finally the native files
        apkBuilder.addNativeLibraries(nativeFileList);
        // close the archive
        apkBuilder.sealApk();
        // and generate the dependency file
        generateDependencyFile(depFile, inputPaths, outputFile.getAbsolutePath());
    } catch (DuplicateFileException e) {
        System.err.println(String.format("Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()));
        throw new BuildException(e);
    } catch (ApkCreationException e) {
        throw new BuildException(e);
    } catch (SealedApkException e) {
        throw new BuildException(e);
    } catch (IllegalArgumentException e) {
        throw new BuildException(e);
    }
}
Example 5
Project: platform_sdk-master  File: ApkBuilderTask.java View source code
@Override
public void execute() throws BuildException {
    File outputFile;
    if (mApkFilepath != null) {
        outputFile = new File(mApkFilepath);
    } else {
        throw new BuildException("missing attribute 'apkFilepath'");
    }
    if (mResourceFile == null) {
        throw new BuildException("missing attribute 'resourcefile'");
    }
    if (mOutFolder == null) {
        throw new BuildException("missing attribute 'outfolder'");
    }
    // check dexPath is only one file.
    File dexFile = null;
    if (mHasCode) {
        String[] dexFiles = mDexPath.list();
        if (dexFiles.length != 1) {
            throw new BuildException(String.format("Expected one dex file but path value resolve to %d files.", dexFiles.length));
        }
        dexFile = new File(dexFiles[0]);
    }
    try {
        // build list of input files/folders to compute dependencies
        // add the content of the zip files.
        List<InputPath> inputPaths = new ArrayList<InputPath>();
        // resource file
        InputPath resourceInputPath = new InputPath(new File(mOutFolder, mResourceFile));
        inputPaths.add(resourceInputPath);
        // dex file
        if (dexFile != null) {
            inputPaths.add(new InputPath(dexFile));
        }
        // zip input files
        List<File> zipFiles = new ArrayList<File>();
        for (Path pathList : mZipList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                zipFiles.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now go through the list of source folders used to add non java files.
        List<File> sourceFolderList = new ArrayList<File>();
        if (mHasCode) {
            for (Path pathList : mSourceList) {
                for (String path : pathList.list()) {
                    File f = new File(path);
                    sourceFolderList.add(f);
                    // because this is a source folder but we only care about non
                    // java files.
                    inputPaths.add(new SourceFolderInputPath(f));
                }
            }
        }
        // now go through the list of jar folders.
        List<File> jarFileList = new ArrayList<File>();
        for (Path pathList : mJarfolderList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    String[] filenames = folder.list(new FilenameFilter() {

                        @Override
                        public boolean accept(File dir, String name) {
                            return PATTERN_JAR_EXT.matcher(name).matches();
                        }
                    });
                    for (String filename : filenames) {
                        File f = new File(folder, filename);
                        jarFileList.add(f);
                        inputPaths.add(new InputPath(f));
                    }
                }
            }
        }
        // now go through the list of jar files.
        for (Path pathList : mJarfileList) {
            for (String path : pathList.list()) {
                File f = new File(path);
                jarFileList.add(f);
                inputPaths.add(new InputPath(f));
            }
        }
        // now the native lib folder.
        List<FileEntry> nativeFileList = new ArrayList<FileEntry>();
        for (Path pathList : mNativeList) {
            for (String path : pathList.list()) {
                // it's ok if top level folders are missing
                File folder = new File(path);
                if (folder.isDirectory()) {
                    List<FileEntry> entries = ApkBuilder.getNativeFiles(folder, mDebugPackaging);
                    // add the list to the list of native files and then create an input
                    // path for each file
                    nativeFileList.addAll(entries);
                    for (FileEntry entry : entries) {
                        inputPaths.add(new InputPath(entry.mFile));
                    }
                }
            }
        }
        // Finally figure out the path to the dependency file.
        String depFile = outputFile.getAbsolutePath() + ".d";
        // check dependencies
        if (initDependencies(depFile, inputPaths) && dependenciesHaveChanged() == false) {
            System.out.println("No changes. No need to create apk.");
            return;
        }
        if (mDebugSigning) {
            System.out.println(String.format("Creating %s and signing it with a debug key...", outputFile.getName()));
        } else {
            System.out.println(String.format("Creating %s for release...", outputFile.getName()));
        }
        ApkBuilder apkBuilder = new ApkBuilder(outputFile, resourceInputPath.getFile(), dexFile, mDebugSigning ? ApkBuilder.getDebugKeystore() : null, mVerbose ? System.out : null);
        apkBuilder.setDebugMode(mDebugPackaging);
        // add the content of the zip files.
        for (File f : zipFiles) {
            if (mVerbose) {
                System.out.println("Zip Input: " + f.getAbsolutePath());
            }
            apkBuilder.addZipFile(f);
        }
        // now go through the list of file to directly add the to the list.
        for (File f : sourceFolderList) {
            if (mVerbose) {
                System.out.println("Source Folder Input: " + f.getAbsolutePath());
            }
            apkBuilder.addSourceFolder(f);
        }
        // now go through the list of jar files.
        for (File f : jarFileList) {
            if (mVerbose) {
                System.out.println("Jar Input: " + f.getAbsolutePath());
            }
            apkBuilder.addResourcesFromJar(f);
        }
        // and finally the native files
        apkBuilder.addNativeLibraries(nativeFileList);
        // close the archive
        apkBuilder.sealApk();
        // and generate the dependency file
        generateDependencyFile(depFile, inputPaths, outputFile.getAbsolutePath());
    } catch (DuplicateFileException e) {
        System.err.println(String.format("Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s", e.getArchivePath(), e.getFile1(), e.getFile2()));
        throw new BuildException(e);
    } catch (ApkCreationException e) {
        throw new BuildException(e);
    } catch (SealedApkException e) {
        throw new BuildException(e);
    } catch (IllegalArgumentException e) {
        throw new BuildException(e);
    }
}
Example 6
Project: eclipse.platform-master  File: XMLTextHover.java View source code
private String getAntModelHoverMessage(AntModel antModel, IRegion hoverRegion, ITextViewer textViewer) {
    try {
        IDocument document = textViewer.getDocument();
        int offset = hoverRegion.getOffset();
        int length = hoverRegion.getLength();
        String text = document.get(offset, length);
        String value;
        AntElementNode node = antModel.getNode(offset, false);
        if (//$NON-NLS-1$
        document.get(offset - 2, 2).equals("${") || node instanceof AntPropertyNode) {
            AntStackFrame frame = getFrame();
            if (// active Ant debug session
            frame != null) {
                AntProperty property = frame.findProperty(text);
                if (property != null) {
                    return ((AntValue) property.getValue()).getValueString();
                }
            }
            value = antModel.getPropertyValue(text);
            if (value != null) {
                return formatMessage(HTMLPrinter.convertToHTMLContent(value));
            }
        }
        value = antModel.getTargetDescription(text);
        if (value != null) {
            return formatMessage(HTMLPrinter.convertToHTMLContent(value));
        }
        Object referencedObject = antModel.getReferenceObject(text);
        if (referencedObject != null) {
            if (referencedObject instanceof Path) {
                return formatPathMessage(((Path) referencedObject).list());
            } else if (referencedObject instanceof PatternSet) {
                return formatPatternSetMessage((PatternSet) referencedObject);
            } else if (referencedObject instanceof AbstractFileSet) {
                return formatFileSetMessage((AbstractFileSet) referencedObject);
            }
        }
    } catch (BadLocationException e) {
    } catch (BuildException be) {
        return be.getMessage();
    }
    return null;
}
Example 7
Project: phing-eclipse-master  File: AntModelProject.java View source code
/* (non-Javadoc)
     * @see org.apache.tools.ant.Project#createClassLoader(org.apache.tools.ant.types.Path)
     */
public AntClassLoader createClassLoader(Path path) {
    synchronized (loaderLock) {
        if (loaders == null) {
            loaders = new Hashtable(8);
        }
        Path p = path;
        if (p == null) {
            p = new Path(this);
        }
        String pstr = p.toString();
        AntClassLoader loader = (AntClassLoader) loaders.get(pstr);
        if (loader == null) {
            loader = super.createClassLoader(path);
            if (path == null) {
                //use the "fake" Eclipse runtime classpath for Ant
                loader.setClassPath(Path.systemClasspath);
            }
            loaders.put(pstr, loader);
        }
        return loader;
    }
}
Example 8
Project: eclipse-publisher-refactoring-master  File: AntUtils.java View source code
private static void setupClasspath() {
    URL[] antClasspath = AntCorePlugin.getPlugin().getPreferences().getURLs();
    StringBuffer buff = new StringBuffer();
    File file = null;
    for (int i = 0; i < antClasspath.length; i++) {
        try {
            file = new File(FileLocator.toFileURL(antClasspath[i]).getPath());
        } catch (IOException e) {
            continue;
        }
        buff.append(file.getAbsolutePath());
        //$NON-NLS-1$
        buff.append("; ");
    }
    org.apache.tools.ant.types.Path systemClasspath = new org.apache.tools.ant.types.Path(null, buff.substring(0, buff.length() - 2));
    org.apache.tools.ant.types.Path.systemClasspath = systemClasspath;
}
Example 9
Project: ant-ivy-master  File: IvyBuildListTest.java View source code
private String[] getFiles(IvyBuildList buildlist) {
    buildlist.setReference("ordered.build.files");
    buildlist.execute();
    Object o = buildlist.getProject().getReference("ordered.build.files");
    assertNotNull(o);
    assertTrue(o instanceof Path);
    Path path = (Path) o;
    String[] files = path.list();
    assertNotNull(files);
    return files;
}
Example 10
Project: apache_ant-master  File: MSVSSTest.java View source code
@Test
public void testGetCommandLine() {
    String[] sTestCmdLine = { MSVSS.SS_EXE, MSVSS.COMMAND_GET, DS_VSS_PROJECT_PATH, MSVSS.FLAG_OVERRIDE_WORKING_DIR + project.getBaseDir().getAbsolutePath() + File.separator + LOCAL_PATH, MSVSS.FLAG_AUTORESPONSE_DEF, MSVSS.FLAG_RECURSION, MSVSS.FLAG_VERSION + VERSION, MSVSS.FLAG_LOGIN + VSS_USERNAME + "," + VSS_PASSWORD, FLAG_FILETIME_UPDATED, FLAG_SKIP_WRITABLE };
    // Set up a VSSGet task
    MSVSSGET vssGet = new MSVSSGET();
    vssGet.setProject(project);
    vssGet.setRecursive(true);
    vssGet.setLocalpath(new Path(project, LOCAL_PATH));
    vssGet.setLogin(VSS_USERNAME + "," + VSS_PASSWORD);
    vssGet.setVersion(VERSION);
    vssGet.setQuiet(false);
    vssGet.setDate(DATE);
    vssGet.setLabel(SRC_LABEL);
    vssGet.setVsspath(VSS_PROJECT_PATH);
    MSVSS.CurrentModUpdated cmu = new MSVSS.CurrentModUpdated();
    cmu.setValue(TIME_UPDATED);
    vssGet.setFileTimeStamp(cmu);
    MSVSS.WritableFiles wf = new MSVSS.WritableFiles();
    wf.setValue(WRITABLE_SKIP);
    vssGet.setWritableFiles(wf);
    commandline = vssGet.buildCmdLine();
    checkCommandLines(sTestCmdLine, commandline.getCommandline());
}
Example 11
Project: axis2-java-master  File: WSDL2JavaSuccessTestBase.java View source code
/** @param outputLocation  */
private void compile(String outputLocation) {
    String cp = null;
    try {
        BufferedReader br = new BufferedReader(new FileReader(System.getProperty("basedir", ".") + "/target/cp.txt"));
        cp = br.readLine();
    } catch (Exception e) {
    }
    if (cp == null) {
        cp = "";
    }
    //using the ant javac task for compilation
    Javac javaCompiler = new Javac();
    Project codeGenProject = new Project();
    Target compileTarget = new Target();
    compileTarget.setName(COMPILE_TARGET_NAME);
    compileTarget.addTask(javaCompiler);
    codeGenProject.addTarget(compileTarget);
    codeGenProject.setSystemProperties();
    javaCompiler.setProject(codeGenProject);
    javaCompiler.setIncludejavaruntime(true);
    javaCompiler.setIncludeantruntime(true);
    /*
          This harmless looking setFork is actually very important. unless the compiler is
          forked it wont work!
        */
    javaCompiler.setFork(true);
    //Create classpath - The generated output directories also become part of the classpath
    //reason for this is that some codegenerators(XMLBeans) produce compiled classes as part of
    //generated artifacts
    File outputLocationFile = new File(outputLocation);
    Path classPath = new Path(codeGenProject, outputLocation);
    classPath.addExisting(classPath.concatSystemClasspath(), false);
    for (int i = 0; i < moduleNames.length; i++) {
        classPath.add(new Path(codeGenProject, MODULE_PATH_PREFIX + moduleNames[i] + CLASSES_DIR));
    }
    classPath.add(new Path(codeGenProject, cp));
    javaCompiler.setClasspath(classPath);
    //set sourcePath - The generated output directories also become part of the sourcepath
    Path sourcePath = new Path(codeGenProject, outputLocation);
    sourcePath.setLocation(outputLocationFile);
    javaCompiler.setSrcdir(sourcePath);
    //output the classes into the output dir as well
    javaCompiler.setDestdir(outputLocationFile);
    javaCompiler.setVerbose(true);
    javaCompiler.execute();
}
Example 12
Project: buckminster-master  File: ImportResource.java View source code
/**
	 * This relies on the task order model.
	 */
@Override
public void execute() {
    try {
        if (resource == null) {
            throw new BuildException("import requires resource attribute");
        }
        if (this.getOwningTarget() == null || !"".equals(getOwningTarget().getName())) {
            throw new BuildException("import only allowed as a top-level task");
        }
        Project p = this.getProject();
        ProjectHelper helper = (ProjectHelper) p.getReference("ant.projectHelper");
        Vector<?> importStack = helper.getImportStack();
        if (importStack.size() == 0) {
            // helper that doesn't set the import.
            throw new BuildException("import requires support in ProjectHelper");
        }
        p.log("Importing resource " + resource, Project.MSG_VERBOSE);
        if (classpath != null) {
            p.log("using user supplied classpath: " + classpath, Project.MSG_DEBUG);
            classpath = classpath.concatSystemClasspath("ignore");
        } else {
            classpath = new Path(p);
            classpath = classpath.concatSystemClasspath("only");
            p.log("using system classpath: " + classpath, Project.MSG_DEBUG);
        }
        AntClassLoader loader = new AntClassLoader(p.getCoreLoader(), p, classpath, false);
        URL resourceURL = loader.getResource(resource);
        if (resourceURL == null) {
            String message = "Cannot find resource " + resource;
            if (optional) {
                p.log(message, Project.MSG_VERBOSE);
                return;
            }
            throw new BuildException(message);
        }
        File resourceFile;
        boolean isLocal = "file".equalsIgnoreCase(resourceURL.getProtocol());
        if (isLocal)
            resourceFile = new File(resourceURL.getPath());
        else {
            InputStream input = null;
            OutputStream output = null;
            try {
                byte[] buffer = new byte[4096];
                int count;
                input = resourceURL.openStream();
                resourceFile = File.createTempFile("import-", ".ant");
                resourceFile.deleteOnExit();
                output = new FileOutputStream(resourceFile);
                while ((count = input.read(buffer)) > 0) output.write(buffer, 0, count);
            } catch (IOException e) {
                throw new BuildException(e.getMessage());
            } finally {
                closeStream(input);
                closeStream(output);
            }
        }
        helper.parse(p, resourceFile);
        if (!isLocal)
            resourceFile.delete();
    } catch (BuildException ex) {
        throw ProjectHelper.addLocationToBuildException(ex, getLocation());
    }
}
Example 13
Project: carrot2-master  File: SwitchClassLoader.java View source code
/**
     * Execute all nestedTasks.
     * 
     * @throws BuildException if one of the nested tasks fails.
     */
public void execute() throws BuildException {
    final Object referenced = reference.getReferencedObject();
    final ClassLoader cl;
    if (referenced instanceof ClassLoader) {
        cl = (ClassLoader) referenced;
    } else if (referenced instanceof Path) {
        cl = getProject().createClassLoader((Path) referenced);
    } else {
        throw new BuildException("Reference to a path or a classloader expected.");
    }
    final Thread self = Thread.currentThread();
    final ClassLoader previous = self.getContextClassLoader();
    try {
        self.setContextClassLoader(cl);
        for (Task task : nestedTasks) {
            task.perform();
        }
    } finally {
        self.setContextClassLoader(previous);
    }
}
Example 14
Project: crux-master  File: ServiceMapperTask.java View source code
/**
	 * 
	 */
private void generateMap() {
    log("Generating map...");
    Java javatask = (Java) getProject().createTask("java");
    javatask.setClassname(ServiceMapper.class.getCanonicalName());
    javatask.setFork(true);
    javatask.setFailonerror(true);
    javatask.createJvmarg().setValue("-Dfile.encoding=" + this.inputCharset);
    for (Argument arg : jvmArgs) {
        if (arg != null) {
            javatask.createJvmarg().setValue(arg.getParts()[0]);
        }
    }
    addServiceMapperParameters(javatask);
    for (Argument arg : args) {
        if (arg != null) {
            javatask.createArg().setValue(arg.getParts()[0]);
        }
    }
    for (Path path : this.classpath) {
        javatask.setClasspath(path);
    }
    int resultCode = javatask.executeJava();
    if (resultCode != 0) {
        if (this.failOnError) {
            throw new ServiceMapperException("Crux Service Mapper returned errors.");
        } else {
            log("Crux Service Mapper returned errors.", Project.MSG_ERR);
        }
    }
}
Example 15
Project: ant-easyant-core-master  File: AbstractImport.java View source code
/**
     * Import a module
     * 
     * @param moduleRevisionId
     *            {@link ModuleRevisionId} of main artifact
     * @param report
     *            a resolved report of the module to import
     */
protected void importModule(ModuleRevisionId moduleRevisionId, ResolveReport report) {
    // Check dependency on core
    checkCoreCompliance(report, providedConf);
    Path path = createModulePath(moduleRevisionId.getModuleId());
    File antFile = null;
    for (int j = 0; j < report.getConfigurationReport(mainConf).getAllArtifactsReports().length; j++) {
        ArtifactDownloadReport artifact = report.getConfigurationReport(mainConf).getAllArtifactsReports()[j];
        if ("ant".equals(artifact.getType())) {
            antFile = artifact.getLocalFile();
        } else if (shouldBeAddedToClasspath(artifact)) {
            path.createPathElement().setLocation(artifact.getLocalFile());
        } else {
            handleOtherResourceFile(moduleRevisionId, artifact.getName(), artifact.getExt(), artifact.getLocalFile());
        }
    }
    // effective import should be executed AFTER any other resource files has been handled
    if (antFile != null && antFile.exists()) {
        doEffectiveImport(antFile);
    }
}
Example 16
Project: AndroidDynamicLoader-master  File: ComputeDependency.java View source code
@Override
public void execute() throws BuildException {
    if (dir == null) {
        throw new BuildException("dir is missing");
    }
    if (!dir.isDirectory()) {
        throw new BuildException(dir + " not exists");
    }
    if (refid == null || refid.length() == 0) {
        throw new BuildException("refid is missing");
    }
    ArrayList<File> deps = new ArrayList<File>();
    if (new File(dir, "AndroidManifest.xml").isFile()) {
        // it's a project
        appendDependency(dir, deps);
    } else {
        // it's a workspace
        for (File proj : dir.listFiles()) {
            appendDependency(proj, deps);
        }
    }
    Path p = new Path(getProject());
    for (File f : deps) {
        p.createPathElement().setLocation(f);
    }
    getProject().addReference(refid, p);
}
Example 17
Project: ant-contrib-master  File: CompileWithWalls.java View source code
public void execute() throws BuildException {
    if (cachedIOException != null)
        throw new BuildException(cachedIOException, getLocation());
    else if (cachedSAXException != null)
        throw new BuildException(cachedSAXException, getLocation());
    else if (tempBuildDir == null)
        throw new BuildException("intermediaryBuildDir attribute must be specified on the compilewithwalls element", getLocation());
    else if (javac == null)
        throw new BuildException("There must be a nested javac element", getLocation());
    else if (walls == null)
        throw new BuildException("There must be a nested walls element", getLocation());
    else if (setWallsTwice)
        throw new BuildException("compilewithwalls task only supports one nested walls element or one walls attribute", getLocation());
    else if (setJavacTwice)
        throw new BuildException("compilewithwalls task only supports one nested javac element", getLocation());
    getProject().addTaskDefinition("SilentMove", SilentMove.class);
    getProject().addTaskDefinition("SilentCopy", SilentCopy.class);
    File destDir = javac.getDestdir();
    Path src = javac.getSrcdir();
    if (src == null)
        throw new BuildException("Javac inside compilewithwalls must have a srcdir specified");
    String[] list = src.list();
    File[] tempSrcDirs1 = new File[list.length];
    for (int i = 0; i < list.length; i++) {
        tempSrcDirs1[i] = getProject().resolveFile(list[i]);
    }
    String[] classpaths = new String[0];
    if (javac.getClasspath() != null)
        classpaths = javac.getClasspath().list();
    File temp = null;
    for (int i = 0; i < classpaths.length; i++) {
        temp = new File(classpaths[i]);
        if (temp.isDirectory()) {
            for (int n = 0; n < tempSrcDirs1.length; n++) {
                if (tempSrcDirs1[n].compareTo(temp) == 0)
                    throw new BuildException("The classpath cannot contain any of the\n" + "src directories, but it does.\n" + "srcdir=" + tempSrcDirs1[n]);
            }
        }
    }
    //get rid of non-existent srcDirs
    List srcDirs2 = new ArrayList();
    for (int i = 0; i < tempSrcDirs1.length; i++) {
        if (tempSrcDirs1[i].exists())
            srcDirs2.add(tempSrcDirs1[i]);
    }
    if (destDir == null)
        throw new BuildException("destdir was not specified in nested javac task", getLocation());
    //make sure tempBuildDir is not inside destDir or we are in trouble!!
    if (file1IsChildOfFile2(tempBuildDir, destDir))
        throw new BuildException("intermediaryBuildDir attribute cannot be specified\n" + "to be the same as destdir or inside desdir of the javac task.\n" + "This is an intermediary build directory only used by the\n" + "compilewithwalls task, not the class file output directory.\n" + "The class file output directory is specified in javac's destdir attribute", getLocation());
    //create the tempBuildDir if it doesn't exist.
    if (!tempBuildDir.exists()) {
        tempBuildDir.mkdirs();
        log("created direction=" + tempBuildDir, Project.MSG_VERBOSE);
    }
    Iterator iter = walls.getPackagesToCompile();
    while (iter.hasNext()) {
        Package toCompile = (Package) iter.next();
        File buildSpace = toCompile.getBuildSpace(tempBuildDir);
        if (!buildSpace.exists()) {
            buildSpace.mkdir();
            log("created directory=" + buildSpace, Project.MSG_VERBOSE);
        }
        FileSet javaIncludes2 = toCompile.getJavaCopyFileSet(getProject(), getLocation());
        for (int i = 0; i < srcDirs2.size(); i++) {
            File srcDir = (File) srcDirs2.get(i);
            javaIncludes2.setDir(srcDir);
            log(toCompile.getPackage() + ": sourceDir[" + i + "]=" + srcDir + " destDir=" + buildSpace, Project.MSG_VERBOSE);
            copyFiles(srcDir, buildSpace, javaIncludes2);
        }
        Path srcDir2 = toCompile.getSrcPath(tempBuildDir, getProject());
        Path classPath = toCompile.getClasspath(tempBuildDir, getProject());
        if (javac.getClasspath() != null)
            classPath.addExisting(javac.getClasspath());
        //unfortunately, we cannot clear the SrcDir in Javac, so we have to clone 
        //instead of just reusing the other Javac....this means added params in
        //future releases will be missed unless this task is kept up to date.
        //need to convert to reflection later so we don't need to keep this up to 
        //date.
        Javac buildSpaceJavac = new Javac();
        buildSpaceJavac.setProject(getProject());
        buildSpaceJavac.setOwningTarget(getOwningTarget());
        buildSpaceJavac.setTaskName(getTaskName());
        log(toCompile.getPackage() + ": Compiling");
        log(toCompile.getPackage() + ": sourceDir=" + srcDir2, Project.MSG_VERBOSE);
        log(toCompile.getPackage() + ": classPath=" + classPath, Project.MSG_VERBOSE);
        log(toCompile.getPackage() + ": destDir=" + buildSpace, Project.MSG_VERBOSE);
        buildSpaceJavac.setSrcdir(srcDir2);
        buildSpaceJavac.setDestdir(buildSpace);
        //includes not used...ie. ignored
        //includesfile not used
        //excludes not used
        //excludesfile not used
        buildSpaceJavac.setClasspath(classPath);
        //sourcepath not used
        buildSpaceJavac.setBootclasspath(javac.getBootclasspath());
        //classpath not used..redefined by us
        //sourcepathref not used...redefined by us.
        //bootclasspathref was already copied above(see javac and you will understand)
        buildSpaceJavac.setExtdirs(javac.getExtdirs());
        buildSpaceJavac.setEncoding(javac.getEncoding());
        buildSpaceJavac.setNowarn(javac.getNowarn());
        buildSpaceJavac.setDebug(javac.getDebug());
        buildSpaceJavac.setDebugLevel(javac.getDebugLevel());
        buildSpaceJavac.setOptimize(javac.getOptimize());
        buildSpaceJavac.setDeprecation(javac.getDeprecation());
        buildSpaceJavac.setTarget(javac.getTarget());
        buildSpaceJavac.setVerbose(javac.getVerbose());
        buildSpaceJavac.setDepend(javac.getDepend());
        buildSpaceJavac.setIncludeantruntime(javac.getIncludeantruntime());
        buildSpaceJavac.setIncludejavaruntime(javac.getIncludejavaruntime());
        buildSpaceJavac.setFork(javac.isForkedJavac());
        buildSpaceJavac.setExecutable(javac.getJavacExecutable());
        buildSpaceJavac.setMemoryInitialSize(javac.getMemoryInitialSize());
        buildSpaceJavac.setMemoryMaximumSize(javac.getMemoryMaximumSize());
        buildSpaceJavac.setFailonerror(javac.getFailonerror());
        buildSpaceJavac.setSource(javac.getSource());
        buildSpaceJavac.setCompiler(javac.getCompiler());
        Javac.ImplementationSpecificArgument arg;
        String[] args = javac.getCurrentCompilerArgs();
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                arg = buildSpaceJavac.createCompilerArg();
                arg.setValue(args[i]);
            }
        }
        buildSpaceJavac.setProject(getProject());
        buildSpaceJavac.perform();
        //copy class files to javac's destDir where the user wants the class files
        copyFiles(buildSpace, destDir, toCompile.getClassCopyFileSet(getProject(), getLocation()));
    }
}
Example 18
Project: eclipse.jdt.core-master  File: JdtApt.java View source code
public void execute() throws BuildException {
    if (workspace == null) {
        //$NON-NLS-1$
        throw new BuildException("Must set a workspace");
    }
    if (startupJar == null) {
        //$NON-NLS-1$
        throw new BuildException("Must set eclipse home");
    }
    setFork(true);
    setLogError(true);
    setClasspath(new Path(null, startupJar.getAbsolutePath()));
    setClassname(APP_CLASSNAME);
    //$NON-NLS-1$
    createArg().setValue("-noupdate");
    //$NON-NLS-1$
    createArg().setValue("-application");
    createArg().setValue(APP_PLUGIN);
    //$NON-NLS-1$
    createArg().setValue("-data");
    createArg().setValue(workspace.getAbsolutePath());
    super.execute();
}
Example 19
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: EclipseClasspathTask.java View source code
@Override
public void execute() throws BuildException {
    Path uberPath = new Path(getProject());
    for (Path path : paths) {
        uberPath.add(path);
    }
    String eclipsepaths = "";
    for (String path : uberPath.list()) {
        // avoid placing modules on classpath
        if (!path.contains("jboss-seam")) {
            String sourcePath = path.substring(0, path.lastIndexOf(".jar")) + "-sources.jar";
            String javadocPath = path.substring(0, path.lastIndexOf(".jar")) + "-javadoc.jar";
            String eclipsepath = "\t<classpathentry kind=\"lib\" path=\"" + path + "\"";
            if (new File(sourcePath).exists()) {
                eclipsepath += " sourcepath=\"" + sourcePath + "\"";
            }
            if (new File(javadocPath).exists()) {
                eclipsepath += ">\r\n";
                eclipsepath += "\t\t<attributes>\n";
                eclipsepath += "\t\t\t<attribute name=\"javadoc_location\" value=\"jar:file:" + javadocPath + "!/\"/>\n";
                eclipsepath += "\t\t</attributes>\n";
                eclipsepath += "\t</classpathentry>\n";
            } else {
                eclipsepath += "/>\r\n";
            }
            eclipsepaths += eclipsepath;
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(toFile)));
        while (reader.ready()) {
            String line = reader.readLine();
            if (line.contains(filterProperty)) {
                line = line.replace("@" + filterProperty + "@", eclipsepaths);
            }
            writer.write(line + "\r\n");
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
Example 20
Project: mkgmap-master  File: MKGMapTask.java View source code
public void execute() {
    List<String> args = new ArrayList<String>();
    try {
        CommandArgsReader argsReader = new CommandArgsReader(new Main());
        if (configFile != null)
            args.add("--read-config=" + configFile);
        for (Path path : paths) {
            String[] includedFiles = path.list();
            for (String filename : includedFiles) {
                log("processing " + filename);
                args.add("--input-file=" + filename);
            }
        }
        argsReader.readArgs(args.toArray(new String[args.size()]));
    } catch (Exception ex) {
        throw new BuildException(ex);
    }
}
Example 21
Project: moxie-master  File: MxTask.java View source code
public Path getSharedPaths() {
    Path path = new Path(getProject());
    String paths = getProject().getProperty("mxshared.path");
    if (!StringUtils.isEmpty(paths)) {
        for (String fp : paths.split(File.pathSeparator)) {
            FileSet fs = new FileSet();
            fs.setProject(getProject());
            File file = new File(fp);
            if (file.isDirectory()) {
                fs.setDir(file);
            } else {
                fs.setFile(file);
            }
            path.add(fs);
        }
    }
    return path;
}
Example 22
Project: seam-2.2-master  File: EclipseClasspathTask.java View source code
@Override
public void execute() throws BuildException {
    Path uberPath = new Path(getProject());
    for (Path path : paths) {
        uberPath.add(path);
    }
    String eclipsepaths = "";
    for (String path : uberPath.list()) {
        // avoid placing modules on classpath
        if (!path.contains("jboss-seam")) {
            String sourcePath = path.substring(0, path.lastIndexOf(".jar")) + "-sources.jar";
            String javadocPath = path.substring(0, path.lastIndexOf(".jar")) + "-javadoc.jar";
            String eclipsepath = "\t<classpathentry kind=\"lib\" path=\"" + path + "\"";
            if (new File(sourcePath).exists()) {
                eclipsepath += " sourcepath=\"" + sourcePath + "\"";
            }
            if (new File(javadocPath).exists()) {
                eclipsepath += ">\r\n";
                eclipsepath += "\t\t<attributes>\n";
                eclipsepath += "\t\t\t<attribute name=\"javadoc_location\" value=\"jar:file:" + javadocPath + "!/\"/>\n";
                eclipsepath += "\t\t</attributes>\n";
                eclipsepath += "\t</classpathentry>\n";
            } else {
                eclipsepath += "/>\r\n";
            }
            eclipsepaths += eclipsepath;
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(toFile)));
        while (reader.ready()) {
            String line = reader.readLine();
            if (line.contains(filterProperty)) {
                line = line.replace("@" + filterProperty + "@", eclipsepaths);
            }
            writer.write(line + "\r\n");
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
Example 23
Project: seam-revisited-master  File: EclipseClasspathTask.java View source code
@Override
public void execute() throws BuildException {
    Path uberPath = new Path(getProject());
    for (Path path : paths) {
        uberPath.add(path);
    }
    String eclipsepaths = "";
    for (String path : uberPath.list()) {
        // avoid placing modules on classpath
        if (!path.contains("jboss-seam")) {
            String sourcePath = path.substring(0, path.lastIndexOf(".jar")) + "-sources.jar";
            String javadocPath = path.substring(0, path.lastIndexOf(".jar")) + "-javadoc.jar";
            String eclipsepath = "\t<classpathentry kind=\"lib\" path=\"" + path + "\"";
            if (new File(sourcePath).exists()) {
                eclipsepath += " sourcepath=\"" + sourcePath + "\"";
            }
            if (new File(javadocPath).exists()) {
                eclipsepath += ">\r\n";
                eclipsepath += "\t\t<attributes>\n";
                eclipsepath += "\t\t\t<attribute name=\"javadoc_location\" value=\"jar:file:" + javadocPath + "!/\"/>\n";
                eclipsepath += "\t\t</attributes>\n";
                eclipsepath += "\t</classpathentry>\n";
            } else {
                eclipsepath += "/>\r\n";
            }
            eclipsepaths += eclipsepath;
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(toFile)));
        while (reader.ready()) {
            String line = reader.readLine();
            if (line.contains(filterProperty)) {
                line = line.replace("@" + filterProperty + "@", eclipsepaths);
            }
            writer.write(line + "\r\n");
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
Example 24
Project: seam2jsf2-master  File: EclipseClasspathTask.java View source code
@Override
public void execute() throws BuildException {
    Path uberPath = new Path(getProject());
    for (Path path : paths) {
        uberPath.add(path);
    }
    String eclipsepaths = "";
    for (String path : uberPath.list()) {
        // avoid placing modules on classpath
        if (!path.contains("jboss-seam")) {
            String sourcePath = path.substring(0, path.lastIndexOf(".jar")) + "-sources.jar";
            String javadocPath = path.substring(0, path.lastIndexOf(".jar")) + "-javadoc.jar";
            String eclipsepath = "\t<classpathentry kind=\"lib\" path=\"" + path + "\"";
            if (new File(sourcePath).exists()) {
                eclipsepath += " sourcepath=\"" + sourcePath + "\"";
            }
            if (new File(javadocPath).exists()) {
                eclipsepath += ">\r\n";
                eclipsepath += "\t\t<attributes>\n";
                eclipsepath += "\t\t\t<attribute name=\"javadoc_location\" value=\"jar:file:" + javadocPath + "!/\"/>\n";
                eclipsepath += "\t\t</attributes>\n";
                eclipsepath += "\t</classpathentry>\n";
            } else {
                eclipsepath += "/>\r\n";
            }
            eclipsepaths += eclipsepath;
        }
    }
    try {
        BufferedReader reader = new BufferedReader(new FileReader(new File(file)));
        BufferedWriter writer = new BufferedWriter(new FileWriter(new File(toFile)));
        while (reader.ready()) {
            String line = reader.readLine();
            if (line.contains(filterProperty)) {
                line = line.replace("@" + filterProperty + "@", eclipsepaths);
            }
            writer.write(line + "\r\n");
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        throw new BuildException(e);
    }
}
Example 25
Project: sonar-plugins-master  File: Launcher.java View source code
private List<String> getPathAsList(Path path) {
    List<String> result = new ArrayList<String>();
    for (Iterator<?> i = path.iterator(); i.hasNext(); ) {
        Resource resource = (Resource) i.next();
        if (resource instanceof FileResource) {
            File fileResource = ((FileResource) resource).getFile();
            result.add(fileResource.getAbsolutePath());
        }
    }
    return result;
}
Example 26
Project: spring-modules-master  File: ExtendClasspathTask.java View source code
public void execute() {
    ClassLoader loader;
    for (loader = getProject().getClass().getClassLoader(); !(loader instanceof URLClassLoader); ) {
        loader = loader.getParent();
        if (loader == null)
            throw new BuildException("Unable to find a URLClassLoader to which path may be added");
    }
    FileUtils fu = FileUtils.newFileUtils();
    for (Iterator iterator = paths.iterator(); iterator.hasNext(); ) {
        Path path = (Path) iterator.next();
        String pathElements[] = path.list();
        int i = 0;
        while (i < pathElements.length) {
            String pathElement = pathElements[i];
            URL url;
            try {
                url = new URL(fu.toURI(pathElement));
            } catch (MalformedURLException e) {
                throw new BuildException("Unable to load class path at path=" + pathElement, e);
            }
            List urls = Arrays.asList(((URLClassLoader) loader).getURLs());
            if (!urls.contains(url)) {
                addURL((URLClassLoader) loader, url);
            }
            i++;
        }
    }
}
Example 27
Project: codehaus-mojo-master  File: JwscMojo.java View source code
/**
     * This method will run the jswc on the target files
     *
     * @throws MojoExecutionException Thrown if we fail to obtain the WSDL.
     */
public void execute() throws MojoExecutionException {
    super.execute();
    if (getLog().isInfoEnabled()) {
        getLog().info("Weblogic jwsc beginning for output " + this.outputName);
    }
    if (getLog().isDebugEnabled()) {
        getLog().debug("inputDir=" + this.inputDir + "  contextPath=" + this.contextPath);
    }
    if (this.contextPath == null) {
        getLog().warn("Context path is null. It will be required if " + "more than one web service is present.");
    }
    try {
        Iterator iter = getDependencies().iterator();
        while (iter.hasNext()) {
            getLog().debug(iter.next().toString());
        }
        final JwscTask task = new JwscTask();
        addToolsJar(ClassLoader.getSystemClassLoader());
        final Project project = new Project();
        project.addBuildListener(getDefaultLogger());
        project.setName("jwsc");
        final Path path = new Path(project, WeblogicMojoUtilities.getDependencies(this.getArtifacts(), this.getPluginArtifacts()));
        if (getLog().isDebugEnabled()) {
            getLog().debug("Path=" + path.toString());
        }
        task.setProject(project);
        task.setTaskName(project.getName());
        task.setNowarn(false);
        // Set the class path
        task.setClasspath(path);
        task.setDestdir(new File(this.outputDir));
        task.setVerbose(this.verbose);
        task.setOptimize(this.optimize);
        task.setDebug(this.debug);
        task.setSrcdir(new File(this.inputDir));
        task.setKeepGenerated(this.keepGenerated);
        final MultipleJwsModule module = task.createModule();
        final JwsFileSet jwsFileSet = module.createJwsFileSet();
        jwsFileSet.setProject(project);
        jwsFileSet.setSrcdir(new Path(project, this.inputDir));
        PatternSet ps = null;
        if (this.sourceIncludes != null && this.sourceIncludes.length() > 0) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Using source includes " + this.sourceIncludes);
            }
            ps = jwsFileSet.createPatternSet();
            ps.setIncludes(this.sourceIncludes);
        }
        if (this.sourceExcludes != null && this.sourceExcludes.length() > 0) {
            if (getLog().isDebugEnabled()) {
                getLog().debug("Using source excludes " + this.sourceExcludes);
            }
            if (ps == null) {
                ps = jwsFileSet.createPatternSet();
            }
            ps.setExcludes(this.sourceExcludes);
        }
        if (getLog().isInfoEnabled()) {
            getLog().info("fileset=" + jwsFileSet.getSrcdir().toString());
        }
        if (this.descriptor != null) {
            final String[] descriptors = this.descriptor.split(",");
            for (int i = 0; i < descriptors.length; i++) {
                final File file = new File(descriptors[i]);
                if (file.exists()) {
                    final Descriptor d = module.createDescriptor();
                    d.setFile(file);
                } else {
                    getLog().warn("Descriptor file " + file + " does not exist. Ignoring this file.");
                }
            }
        }
        module.setName(this.outputName);
        module.setExplode(this.explode);
        module.setContextPath(this.contextPath);
        task.execute();
    } catch (Exception ex) {
        getLog().error("Exception encountered during jwsc", ex);
        throw new MojoExecutionException("Exception encountered during jwsc", ex);
    } finally {
        WeblogicMojoUtilities.unsetWeblogicProtocolHandler();
    }
}
Example 28
Project: discobot-master  File: GroovycTask.java View source code
protected void compile() {
    Path path = getClasspath();
    if (path != null) {
        config.setClasspath(path.toString());
    }
    config.setTargetDirectory(destdir);
    GroovyClassLoader gcl = createClassLoader();
    CompilationUnit compilation = new CompilationUnit(config, null, gcl);
    GlobPatternMapper mapper = new GlobPatternMapper();
    mapper.setFrom("*.groovy");
    mapper.setTo("*.class");
    int count = 0;
    String[] list = src.list();
    for (int i = 0; i < list.length; i++) {
        File basedir = getProject().resolveFile(list[i]);
        if (!basedir.exists()) {
            throw new BuildException("Source directory does not exist: " + basedir, getLocation());
        }
        DirectoryScanner scanner = getDirectoryScanner(basedir);
        String[] includes = scanner.getIncludedFiles();
        if (force) {
            log.debug("Forcefully including all files from: " + basedir);
            for (int j = 0; j < includes.length; j++) {
                File file = new File(basedir, includes[j]);
                log.debug("    " + file);
                compilation.addSource(file);
                count++;
            }
        } else {
            log.debug("Including changed files from: " + basedir);
            SourceFileScanner sourceScanner = new SourceFileScanner(this);
            File[] files = sourceScanner.restrictAsFiles(includes, basedir, destdir, mapper);
            for (int j = 0; j < files.length; j++) {
                log.debug("    " + files[j]);
                compilation.addSource(files[j]);
                count++;
            }
        }
    }
    if (count > 0) {
        log.info("Compiling " + count + " source file" + (count > 1 ? "s" : "") + " to " + destdir);
        compilation.compile();
    } else {
        log.info("No sources found to compile");
    }
}
Example 29
Project: error-prone-master  File: ErrorProneExternalCompilerAdapter.java View source code
@Override
public boolean execute() throws BuildException {
    if (getJavac().isForkedJavac()) {
        attributes.log("Using external Error Prone compiler", Project.MSG_VERBOSE);
        Commandline cmd = new Commandline();
        cmd.setExecutable(JavaEnvUtils.getJdkExecutable("java"));
        if (memoryStackSize != null) {
            cmd.createArgument().setValue("-Xss" + memoryStackSize);
        }
        String memoryParameterPrefix = "-X";
        if (memoryInitialSize != null) {
            cmd.createArgument().setValue(memoryParameterPrefix + "ms" + this.memoryInitialSize);
            // Prevent setupModernJavacCommandlineSwitches() from doing it also
            memoryInitialSize = null;
        }
        if (memoryMaximumSize != null) {
            cmd.createArgument().setValue(memoryParameterPrefix + "mx" + this.memoryMaximumSize);
            // Prevent setupModernJavacCommandlineSwitches() from doing it also
            memoryMaximumSize = null;
        }
        for (Argument arg : jvmArgs) {
            for (String part : arg.getParts()) {
                cmd.createArgument().setValue(part);
            }
        }
        Path bootclasspath = new Path(getProject());
        addResourceSource(bootclasspath, "com/google/errorprone/ErrorProneExternalCompilerAdapter.class");
        cmd.createArgument().setValue("-Xbootclasspath/p:" + bootclasspath);
        if (classpath != null) {
            cmd.createArgument().setValue("-classpath");
            cmd.createArgument().setPath(classpath);
        }
        cmd.createArgument().setValue(ErrorProneCompiler.class.getName());
        setupModernJavacCommandlineSwitches(cmd);
        int firstFile = cmd.size();
        logAndAddFilesToCompile(cmd);
        return executeExternalCompile(cmd.getCommandline(), firstFile, true) == 0;
    } else {
        attributes.log("You must set fork=\"yes\" to use the external Error Prone compiler", Project.MSG_ERR);
        return false;
    }
}
Example 30
Project: groovy-core-master  File: CompileTaskSupport.java View source code
protected GroovyClassLoader createClassLoader() {
    ClassLoader parent = ClassLoader.getSystemClassLoader();
    GroovyClassLoader gcl = new GroovyClassLoader(parent, config);
    Path path = getClasspath();
    if (path != null) {
        final String[] filePaths = path.list();
        for (int i = 0; i < filePaths.length; i++) {
            String filePath = filePaths[i];
            gcl.addClasspath(filePath);
        }
    }
    return gcl;
}
Example 31
Project: groovy-master  File: CompileTaskSupport.java View source code
protected GroovyClassLoader createClassLoader() {
    ClassLoader parent = ClassLoader.getSystemClassLoader();
    GroovyClassLoader gcl = new GroovyClassLoader(parent, config);
    Path path = getClasspath();
    if (path != null) {
        final String[] filePaths = path.list();
        for (int i = 0; i < filePaths.length; i++) {
            String filePath = filePaths[i];
            gcl.addClasspath(filePath);
        }
    }
    return gcl;
}
Example 32
Project: Jnario-master  File: CompileTask.java View source code
private Path createClasspath() {
    Path _xblockexpression = null;
    {
        boolean _equals = Objects.equal(this.classPath, null);
        if (_equals) {
            Project _project = this.getProject();
            Path _path = new Path(_project);
            this.classPath = _path;
        }
        _xblockexpression = this.classPath;
    }
    return _xblockexpression;
}
Example 33
Project: liferay-gradle-plugin-master  File: BuildThumbnail.java View source code
/**
     * Performs the build thumbnail task.
     */
@TaskAction
public void buildThumbnail() {
    if (getWidth() <= 0) {
        throw new InvalidUserDataException("Please specify a valid width");
    }
    if (getHeight() <= 0) {
        throw new InvalidUserDataException("Please specify a valid height");
    }
    Java javaTask = new Java();
    javaTask.setClassname("com.liferay.portal.tools.ThumbnailBuilder");
    Project antProject = getAnt().getAntProject();
    Path antClasspath = new Path(antProject);
    for (File dep : getClasspath()) {
        antClasspath.createPathElement().setLocation(dep);
    }
    javaTask.setProject(antProject);
    javaTask.setClasspath(antClasspath);
    javaTask.createArg().setLine("thumbnail.original.file=" + getOriginalFile().getAbsolutePath());
    javaTask.createArg().setLine("thumbnail.thumbnail.file=" + getThumbnailFile().getAbsolutePath());
    javaTask.createArg().setLine("thumbnail.height=" + getHeight());
    javaTask.createArg().setLine("thumbnail.width=" + getWidth());
    javaTask.createArg().setLine("thumbnail.overwrite=" + getOverwrite());
    javaTask.execute();
//						<java
//							classname="com.liferay.portal.tools.ThumbnailBuilder"
//							classpathref="portal.classpath"
//						>
//							<arg value="thumbnail.original.file=@{file}" />
//							<arg value="thumbnail.thumbnail.file=${thumbnail.file}" />
//							<arg value="thumbnail.height=120" />
//							<arg value="thumbnail.width=160" />
//							<arg value="thumbnail.overwrite=false" />
//						</java>
}
Example 34
Project: spring-framework-2.5.x-master  File: CommonsAttributeCompilerUtils.java View source code
public static void ideAttributeCompile(String testWildcards) {
    System.out.println("Compiling attributes under IDE");
    Project project = new Project();
    //URL markerUrl = CommonsAttributeCompilerUtils.class.getResource(MARKER_FILE);
    //File markerFile = new File(markerUrl.getFile());
    // we know marker is in /target/test-classes
    File root = new File("./");
    project.setBaseDir(root);
    project.init();
    AttributeCompiler commonsAttributesCompiler = new AttributeCompiler();
    commonsAttributesCompiler.setProject(project);
    //commonsAttributesCompiler.setSourcepathref("test");
    String tempPath = "target/generated-commons-attributes-src";
    commonsAttributesCompiler.setDestdir(new File(tempPath));
    FileSet fileset = new FileSet();
    fileset.setDir(new File(root.getPath() + File.separator + "test"));
    String attributeClasses = testWildcards;
    fileset.setIncludes(attributeClasses);
    commonsAttributesCompiler.addFileset(fileset);
    commonsAttributesCompiler.execute();
    System.out.println("Compiling Java sources generated by Commons Attributes using Javac: requires tools.jar on Eclipse project classpath");
    // We now have the generated Java source: compile it.
    // This requires Javac on the source path
    Javac javac = new Javac();
    javac.setProject(project);
    //project.setCoreLoader(Thread.currentThread().getContextClassLoader());
    Path path = new Path(project, tempPath);
    javac.setSrcdir(path);
    // Couldn't get this to work: trying to use Eclipse
    //javac.setCompiler("org.eclipse.jdt.core.JDTCompilerAdapter");
    File destDir = new File(root.getPath() + File.separator + "target/test-classes");
    if (!destDir.exists()) {
        destDir.mkdir();
    }
    javac.setDestdir(destDir);
    javac.setIncludes(attributeClasses);
    javac.execute();
}
Example 35
Project: cobertura-master  File: WebAppFunctionalTest.java View source code
private void createCoberturaServlet() {
    File webappsDir = new File(TestUtils.getTempDir(), "webapps");
    File war = new File(webappsDir, "coberturaFlush.war");
    File classesDir = new File("target/build/warClasses");
    if (!classesDir.exists())
        classesDir.mkdirs();
    Javac javac = new Javac();
    javac.setProject(TestUtils.project);
    javac.setSrcdir(new Path(TestUtils.project, "src/main/java"));
    javac.setDestdir(classesDir);
    javac.setDebug(true);
    Path classpath = new Path(TestUtils.project);
    FileSet jettyFileSet = new FileSet();
    jettyFileSet.setDir(new File("src/test/resources/jetty"));
    jettyFileSet.setIncludes("**/*.jar");
    classpath.addFileset(jettyFileSet);
    javac.setIncludes("**/FlushCoberturaServlet.java");
    javac.setClasspath(classpath);
    javac.execute();
    War antWar = new War();
    antWar.setProject(TestUtils.project);
    antWar.setDestFile(war);
    antWar.setWebxml(new File("src/main/java/net/sourceforge/cobertura/webapp/web.xml"));
    ZipFileSet classesFileSet = new ZipFileSet();
    classesFileSet.setDir(classesDir);
    antWar.addClasses(classesFileSet);
    antWar.execute();
}
Example 36
Project: WS171-development-master  File: SetupTask.java View source code
@Override
public void execute() throws BuildException {
    Project antProject = getProject();
    // get the SDK location
    String sdkLocation = antProject.getProperty(ProjectProperties.PROPERTY_SDK);
    // check if it's valid and exists
    if (sdkLocation == null || sdkLocation.length() == 0) {
        throw new BuildException("SDK Location is not set.");
    }
    File sdk = new File(sdkLocation);
    if (sdk.isDirectory() == false) {
        throw new BuildException(String.format("SDK Location '%s' is not valid.", sdkLocation));
    }
    // get the target property value
    String targetHashString = antProject.getProperty(ProjectProperties.PROPERTY_TARGET);
    if (targetHashString == null) {
        throw new BuildException("Android Target is not set.");
    }
    // load up the sdk targets.
    final ArrayList<String> messages = new ArrayList<String>();
    SdkManager manager = SdkManager.createManager(sdkLocation, new ISdkLog() {

        public void error(Throwable t, String errorFormat, Object... args) {
            if (errorFormat != null) {
                messages.add(String.format("Error: " + errorFormat, args));
            }
            if (t != null) {
                messages.add("Error: " + t.getMessage());
            }
        }

        public void printf(String msgFormat, Object... args) {
            messages.add(String.format(msgFormat, args));
        }

        public void warning(String warningFormat, Object... args) {
            messages.add(String.format("Warning: " + warningFormat, args));
        }
    });
    if (manager == null) {
        // since we failed to parse the SDK, lets display the parsing output.
        for (String msg : messages) {
            System.out.println(msg);
        }
        throw new BuildException("Failed to parse SDK content.");
    }
    // resolve it
    IAndroidTarget androidTarget = manager.getTargetFromHashString(targetHashString);
    if (androidTarget == null) {
        throw new BuildException(String.format("Unable to resolve target '%s'", targetHashString));
    }
    // display it
    System.out.println("Project Target: " + androidTarget.getName());
    if (androidTarget.isPlatform() == false) {
        System.out.println("Vendor: " + androidTarget.getVendor());
        System.out.println("Platform Version: " + androidTarget.getApiVersionName());
    }
    System.out.println("API level: " + androidTarget.getApiVersionNumber());
    // sets up the properties to find android.jar/framework.aidl/target tools
    String androidJar = androidTarget.getPath(IAndroidTarget.ANDROID_JAR);
    antProject.setProperty(PROPERTY_ANDROID_JAR, androidJar);
    antProject.setProperty(PROPERTY_ANDROID_AIDL, androidTarget.getPath(IAndroidTarget.ANDROID_AIDL));
    antProject.setProperty(PROPERTY_AAPT, androidTarget.getPath(IAndroidTarget.AAPT));
    antProject.setProperty(PROPERTY_AIDL, androidTarget.getPath(IAndroidTarget.AIDL));
    antProject.setProperty(PROPERTY_DX, androidTarget.getPath(IAndroidTarget.DX));
    // sets up the boot classpath
    // create the Path object
    Path bootclasspath = new Path(antProject);
    // create a PathElement for the framework jar
    PathElement element = bootclasspath.createPathElement();
    element.setPath(androidJar);
    // create PathElement for each optional library.
    IOptionalLibrary[] libraries = androidTarget.getOptionalLibraries();
    if (libraries != null) {
        HashSet<String> visitedJars = new HashSet<String>();
        for (IOptionalLibrary library : libraries) {
            String jarPath = library.getJarPath();
            if (visitedJars.contains(jarPath) == false) {
                visitedJars.add(jarPath);
                element = bootclasspath.createPathElement();
                element.setPath(library.getJarPath());
            }
        }
    }
    // finally sets the path in the project with a reference
    antProject.addReference(REF_CLASSPATH, bootclasspath);
    // find the file to import, and import it.
    String templateFolder = androidTarget.getPath(IAndroidTarget.TEMPLATES);
    // Now the import section. This is only executed if the task actually has to import a file.
    if (mDoImport) {
        // make sure the file exists.
        File templates = new File(templateFolder);
        if (templates.isDirectory() == false) {
            throw new BuildException(String.format("Template directory '%s' is missing.", templateFolder));
        }
        // now check the rules file exists.
        File rules = new File(templateFolder, ANDROID_RULES);
        if (rules.isFile() == false) {
            throw new BuildException(String.format("Build rules file '%s' is missing.", templateFolder));
        }
        // set the file location to import
        setFile(rules.getAbsolutePath());
        // and import
        super.execute();
    }
}
Example 37
Project: aether-ant-master  File: ResolveTest.java View source code
public void testResolvePath() {
    executeTarget("testResolvePath");
    Map<?, ?> refs = getProject().getReferences();
    Object obj = refs.get("out");
    assertThat("ref 'out' is no path", obj, instanceOf(Path.class));
    Path path = (Path) obj;
    String[] elements = path.list();
    assertThat("no aether-api on classpath", elements, hasItemInArray(allOf(containsString("aether-api"), endsWith(".jar"))));
}
Example 38
Project: android-platform_sdk-master  File: AaptExecLoopTask.java View source code
/**
     * Sets the value of the "resources" attribute.
     * @param resources the value.
     *
     * @deprecated Use nested element(s) <res path="value" />
     */
@Deprecated
public void setResources(Path resources) {
    System.out.println("WARNNG: Using deprecated 'resources' attribute in AaptExecLoopTask." + "Use nested element(s) <res path=\"value\" /> instead.");
    if (mResources == null) {
        mResources = new ArrayList<Path>();
    }
    mResources.add(new Path(getProject(), resources.toString()));
}
Example 39
Project: animal-sniffer-master  File: CheckSignatureTask.java View source code
public void execute() throws BuildException {
    validate();
    try {
        log("Checking unresolved references to " + signature, Project.MSG_INFO);
        if (!signature.isFile()) {
            throw new BuildException("Could not find signature: " + signature);
        }
        final Set<String> ignoredPackages = buildPackageList();
        for (Ignore ignore : ignores) {
            if (ignore == null || ignore.getClassName() == null) {
                continue;
            }
            ignoredPackages.add(ignore.getClassName().replace('.', '/'));
        }
        final SignatureChecker signatureChecker = new SignatureChecker(new FileInputStream(signature), ignoredPackages, new AntLogger(this));
        final List<File> tmp = new ArrayList<File>();
        if (sourcepath != null) {
            Iterator<?> i = sourcepath.iterator();
            while (i.hasNext()) {
                Object next = i.next();
                if (next instanceof FileResource) {
                    final File file = ((FileResource) next).getFile();
                    tmp.add(file);
                }
            }
        }
        signatureChecker.setSourcePath(tmp);
        final Collection<String> annotationTypes = new HashSet<String>();
        for (Annotation annotation : annotations) {
            if (annotation != null && annotation.getClassName() != null) {
                annotationTypes.add(annotation.getClassName());
            }
        }
        signatureChecker.setAnnotationTypes(annotationTypes);
        for (Path path : paths) {
            final String[] files = path.list();
            for (int j = 0; j < files.length; j++) {
                signatureChecker.process(new File(files[j]));
            }
        }
        if (signatureChecker.isSignatureBroken()) {
            throw new BuildException("Signature errors found. Verify them and ignore them with the " + "proper annotation if needed.", getLocation());
        }
    } catch (IOException e) {
        throw new BuildException("Failed to check signatures", e);
    }
}
Example 40
Project: ant-webstart-master  File: ResourcesElement.java View source code
@Override
public void appendXml(JnlpTask task, Element parentElement) {
    Element resourcesElement = ConfigurationHelper.appendElement(parentElement, "resources");
    ConfigurationHelper.appendAttributeIfNotNull(resourcesElement, "os", this.getOs());
    ConfigurationHelper.appendAttributeIfNotNull(resourcesElement, "arch", this.getArch());
    ConfigurationHelper.appendAttributeIfNotNull(resourcesElement, "locale", this.getLocale());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getJava());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getJar());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getNativelib());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getExtension());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getPackage());
    ConfigurationHelper.appendElements(task, resourcesElement, this.getProperty());
    // Now compute the dynamic path
    Path dynamicPath = new Path(task.getProject());
    if (this.getPath() != null) {
        dynamicPath.append(this.getPath());
    }
    if (this.getPathref() != null) {
        dynamicPath.setRefid(this.getPathref());
    }
    // Since all entries within the JNLP should be relative to it's location,
    // we compute the locations of the files found in the dynamic path against
    // the URI of the destination file of the JNLP XML document
    URI pathBaseUri = task.getDestfile().getParentFile().toURI();
    for (String dynamicPathEntry : dynamicPath.list()) {
        File resourceFile = new File(dynamicPathEntry);
        if (resourceFile.isFile() && resourceFile.exists()) {
            URI resourceUriAbsolute = resourceFile.toURI();
            URI resourceUriRelative = pathBaseUri.relativize(resourceUriAbsolute);
            if (resourceUriRelative.isAbsolute()) {
                task.log("Computed resource entry is not relative! >> " + resourceUriRelative, Project.MSG_WARN);
            }
            JarElement jarElement = new JarElement();
            jarElement.setHref(resourceUriRelative.toString());
            jarElement.setSize((int) resourceFile.length());
            jarElement.appendXml(task, resourcesElement);
        }
    }
}
Example 41
Project: ant4eclipse-master  File: JavacCompilerAdapter.java View source code
/**
   * Creates a list with commandline arguments shared among all source files.
   * 
   * @param description
   *          The description used for the compilation process. Not <code>null</code>.
   * 
   * @return The list with commandline arguments. Not <code>null</code>.
   */
private List<String> createCommonArgs(CompileJobDescription description) {
    Map<String, String> options = description.getCompilerOptions();
    List<String> result = new ArrayList<String>();
    result.add(getCompileOptions(description));
    Path bootclasspath = getJavac().getBootclasspath();
    if (bootclasspath != null) {
        result.add("-bootclasspath");
        result.add(getConcatenatedPath(bootclasspath.list()));
    }
    Path extdirs = getJavac().getExtdirs();
    if (extdirs != null) {
        result.add("-extdirs");
        result.add(getConcatenatedPath(extdirs.list()));
    }
    result.add("-classpath");
    result.add(getClasspath(description));
    result.add(String.format("-g:%s", getDebugOptions(description)));
    if (A4ELogging.isDebuggingEnabled()) {
        result.add("-verbose");
    }
    if (options.containsKey(CompilerOptions.OPTION_Source)) {
        result.add("-source");
        result.add(options.get(CompilerOptions.OPTION_Source));
    }
    if (options.containsKey(CompilerOptions.OPTION_Compliance)) {
        result.add("-target");
        result.add(options.get(CompilerOptions.OPTION_Compliance));
    }
    if (options.containsKey(CompilerOptions.OPTION_Encoding)) {
        result.add("-encoding");
        result.add(options.get(CompilerOptions.OPTION_Encoding));
    }
    if (options.containsKey(CompilerOptions.OPTION_ReportDeprecation) || options.containsKey(CompilerOptions.OPTION_ReportDeprecationInDeprecatedCode) || options.containsKey(CompilerOptions.OPTION_ReportDeprecationWhenOverridingDeprecatedMethod)) {
        result.add("-deprecation");
    }
    return result;
}
Example 42
Project: Banana-master  File: JVMSpawn.java View source code
public static int spawn(String jvmName, String className, String vmArgs, String[] args) {
    int ret = -1;
    // global ant project settings
    Project project = new Project();
    project.setBaseDir(new File(System.getProperty("user.dir")));
    project.init();
    BuildLogger logger = new MyLogger();
    project.addBuildListener(logger);
    logger.setOutputPrintStream(System.out);
    logger.setErrorPrintStream(System.err);
    logger.setMessageOutputLevel(Project.MSG_INFO);
    project.fireBuildStarted();
    Throwable caught = null;
    try {
        Java javaTask = new Java();
        javaTask.setNewenvironment(true);
        javaTask.setTaskName(jvmName);
        javaTask.setProject(project);
        javaTask.setFork(true);
        javaTask.setFailonerror(true);
        javaTask.setClassname(className);
        Argument jvmArgs = javaTask.createJvmarg();
        jvmArgs.setLine(vmArgs);
        Argument taskArgs = javaTask.createArg();
        taskArgs.setLine(Util.implode(args, " "));
        // use same classpath as current jvm
        Path classPath = new Path(project, System.getProperty("java.class.path"));
        javaTask.setClasspath(classPath);
        javaTask.init();
        ret = javaTask.executeJava();
    } catch (BuildException e) {
        caught = e;
    }
    project.fireBuildFinished(caught);
    return ret;
}
Example 43
Project: castor-master  File: AntJavaCompiler.java View source code
/**
     * Creates and returns a Ant Javac compiler.
     * @param srcDir Source directory for compiation.
     * @param destDir Destination directory for compilation.
     *
     * @return Ant Javac compiler
     */
private Javac makeCompiler(final File srcDir, final File destDir) {
    Project project = new Project();
    project.init();
    project.setBasedir(srcDir.getAbsolutePath());
    Javac compiler = new Javac();
    compiler.setProject(project);
    compiler.setDestdir(destDir.getAbsoluteFile());
    compiler.setOptimize(false);
    compiler.setDebug(true);
    compiler.setDebugLevel("lines,vars,source");
    compiler.setIncludejavaruntime(true);
    if (XMLTestCase._verbose) {
        compiler.setListfiles(true);
        compiler.setVerbose(true);
    } else {
        compiler.setNowarn(true);
    }
    if (_javaVersion != null) {
        compiler.setSource(_javaVersion);
    }
    Path classpath = compiler.createClasspath();
    classpath.setPath(System.getProperty("java.class.path"));
    classpath.add(new Path(project, destDir.getAbsolutePath()));
    compiler.setClasspath(classpath);
    return compiler;
}
Example 44
Project: cayenne-master  File: CayenneGeneratorTaskCrossMapRelationshipsTest.java View source code
/**
	 * Tests pairs generation with a cross-DataMap relationship.
	 */
@Test
public void testCrossDataMapRelationships() throws Exception {
    CayenneGeneratorTask task = new CayenneGeneratorTask();
    task.setProject(new Project());
    task.setTaskName("Test");
    task.setLocation(Location.UNKNOWN_LOCATION);
    // prepare destination directory
    File destDir = new File(FileUtil.baseTestDirectory(), "cgen12");
    // prepare destination directory
    if (!destDir.exists()) {
        assertTrue(destDir.mkdirs());
    }
    File map = new File(destDir, "cgen-dependent.map.xml");
    ResourceUtil.copyResourceToFile("org/apache/cayenne/tools/cgen-dependent.map.xml", map);
    File additionalMaps[] = new File[1];
    additionalMaps[0] = new File(destDir, "cgen.map.xml");
    ResourceUtil.copyResourceToFile("org/apache/cayenne/tools/cgen.map.xml", additionalMaps[0]);
    FileList additionalMapsFilelist = new FileList();
    additionalMapsFilelist.setDir(additionalMaps[0].getParentFile());
    additionalMapsFilelist.setFiles(additionalMaps[0].getName());
    Path additionalMapsPath = new Path(task.getProject());
    additionalMapsPath.addFilelist(additionalMapsFilelist);
    // setup task
    task.setMap(map);
    task.setAdditionalMaps(additionalMapsPath);
    task.setMakepairs(true);
    task.setOverwrite(false);
    task.setMode("entity");
    task.setIncludeEntities("MyArtGroup");
    task.setDestDir(destDir);
    task.setSuperpkg("org.apache.cayenne.testdo.cgen2.auto");
    task.setUsepkgpath(true);
    // run task
    task.execute();
    // check results
    File a = new File(destDir, convertPath("org/apache/cayenne/testdo/cgen2/MyArtGroup.java"));
    assertTrue(a.isFile());
    assertContents(a, "MyArtGroup", "org.apache.cayenne.testdo.cgen2", "_MyArtGroup");
    File _a = new File(destDir, convertPath("org/apache/cayenne/testdo/cgen2/auto/_MyArtGroup.java"));
    assertTrue(_a.exists());
    assertContents(_a, "_MyArtGroup", "org.apache.cayenne.testdo.cgen2.auto", "CayenneDataObject");
    assertContents(_a, "import org.apache.cayenne.testdo.testmap.ArtGroup;");
    assertContents(_a, " ArtGroup getToParentGroup()");
    assertContents(_a, "setToParentGroup(ArtGroup toParentGroup)");
}
Example 45
Project: CodingSpectator-master  File: ConvertPath.java View source code
protected void convertFileSystemPathToResourcePath(IPath path) {
    IResource resource;
    if (Platform.getLocation().equals(path)) {
        resource = ResourcesPlugin.getWorkspace().getRoot();
    } else {
        resource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(path);
        if (resource == null)
            throw new //$NON-NLS-1$
            BuildException(//$NON-NLS-1$
            Policy.bind("exception.noProjectMatchThePath", fileSystemPath.toOSString()));
    }
    if (property != null)
        getProject().setUserProperty(property, resource.getFullPath().toString());
    if (pathID != null) {
        Path newPath = new Path(getProject(), resource.getFullPath().toString());
        getProject().addReference(pathID, newPath);
    }
}
Example 46
Project: cuke4duke-master  File: AbstractJRubyMojo.java View source code
protected Project getProject() throws MojoExecutionException {
    Project project = new Project();
    project.setBaseDir(mavenProject.getBasedir());
    project.setProperty("jruby.home", jrubyHome().getAbsolutePath());
    project.addBuildListener(new LogAdapter());
    Path jrubyClasspath = new Path(project);
    project.addReference("jruby.classpath", jrubyClasspath);
    try {
        append(jrubyClasspath, testClasspathElements);
        append(jrubyClasspath, compileClasspathElements);
        append(jrubyClasspath, pluginArtifacts);
        return project;
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("error resolving dependencies", e);
    }
}
Example 47
Project: deadmethods-master  File: ClassRepository.java View source code
private static final ClassLoader createClassLoader(final Path classpath, final Path auxClassPath) {
    return AccessController.<URLClassLoader>doPrivileged(new PrivilegedAction<URLClassLoader>() {

        @Override
        public URLClassLoader run() {
            Set<URL> urls = new HashSet<URL>();
            urls.addAll(convertPathToURLs(classpath));
            urls.addAll(convertPathToURLs(auxClassPath));
            return new URLClassLoader(urls.toArray(new URL[urls.size()]));
        }
    });
}
Example 48
Project: dgrid-master  File: AntJobTask.java View source code
public void execute() throws BuildException {
    System.out.println("execute()");
    try {
        Path classPath = getClasspath();
        if (classPath == null) {
            String cRef = getClasspathRef();
            if (cRef != null) {
                classPath = (Path) getProject().getReference(cRef);
                if (classPath == null) {
                    throw new BuildException("The reference " + cRef + " is not set.", getLocation());
                }
            }
        }
        AntClassLoader acl;
        if (classPath == null) {
            acl = null;
        } else {
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            if (cl == null) {
                cl = getClass().getClassLoader();
                if (cl == null) {
                    cl = ClassLoader.getSystemClassLoader();
                }
            }
            acl = new AntClassLoader(cl, getProject(), classPath, true);
            acl.setThreadContextLoader();
        }
        Job job = getJob();
        DGridTransport transport = getTransport();
        transport.submitJob(job);
    } catch (Exception e) {
        throw (new BuildException(e));
    }
}
Example 49
Project: dot-emacs-master  File: JavaCommand.java View source code
/**
   * {@inheritDoc}
   * @see org.eclim.command.Command#execute(CommandLine)
   */
public Object execute(CommandLine commandLine) throws Exception {
    String projectName = commandLine.getValue(Options.PROJECT_OPTION);
    String mainClass = commandLine.getValue(Options.CLASSNAME_OPTION);
    boolean debug = commandLine.hasOption(Options.DEBUG_OPTION);
    String workingDir = commandLine.getValue(WORKINGDIR_OPTION);
    IProject project = ProjectUtils.getProject(projectName);
    IJavaProject javaProject = JavaUtils.getJavaProject(project);
    Project antProject = new Project();
    BuildLogger buildLogger = new DefaultLogger();
    buildLogger.setMessageOutputLevel(debug ? Project.MSG_DEBUG : Project.MSG_INFO);
    buildLogger.setOutputPrintStream(getContext().out);
    buildLogger.setErrorPrintStream(getContext().err);
    antProject.addBuildListener(buildLogger);
    antProject.setBasedir(ProjectUtils.getPath(project));
    antProject.setDefaultInputStream(System.in);
    if (mainClass == null) {
        mainClass = ProjectUtils.getSetting(project, "org.eclim.java.run.mainclass");
    }
    if (mainClass == null || mainClass.trim().equals(StringUtils.EMPTY) || mainClass.trim().equals("none")) {
        // first try to locate a main method.
        mainClass = findMainClass(javaProject);
        if (mainClass == null) {
            throw new RuntimeException(Services.getMessage("setting.not.set", "org.eclim.java.run.mainclass"));
        }
    }
    if (mainClass.endsWith(".java") || mainClass.endsWith(".class")) {
        mainClass = mainClass.substring(0, mainClass.lastIndexOf('.'));
    }
    Java java = new MyJava();
    java.setTaskName("java");
    java.setProject(antProject);
    java.setClassname(mainClass);
    java.setFork(true);
    if (workingDir != null) {
        java.setDir(new File(workingDir));
    }
    // construct classpath
    Path classpath = new Path(antProject);
    String[] paths = ClasspathUtils.getClasspath(javaProject);
    for (String path : paths) {
        Path.PathElement pe = classpath.createPathElement();
        pe.setPath(path);
    }
    java.setClasspath(classpath);
    // add default vm args
    String setting = ProjectUtils.getSetting(project, "org.eclim.java.run.jvmargs");
    if (setting != null && !setting.trim().equals(StringUtils.EMPTY)) {
        String[] defaultArgs = (String[]) new Gson().fromJson(setting, String[].class);
        if (defaultArgs != null && defaultArgs.length > 0) {
            for (String vmarg : defaultArgs) {
                if (!vmarg.startsWith("-")) {
                    continue;
                }
                Argument a = java.createJvmarg();
                a.setValue(vmarg);
            }
        }
    }
    // add any supplied vm args
    String[] vmargs = commandLine.getValues(VMARGS_OPTION);
    if (vmargs != null && vmargs.length > 0) {
        for (String vmarg : vmargs) {
            if (!vmarg.startsWith("-")) {
                continue;
            }
            Argument a = java.createJvmarg();
            a.setValue(vmarg);
        }
    }
    // add any supplied system properties
    String[] props = commandLine.getValues(SYSPROPS_OPTION);
    if (props != null && props.length > 0) {
        for (String prop : props) {
            String[] sysprop = StringUtils.split(prop, "=", 2);
            if (sysprop.length != 2) {
                continue;
            }
            if (sysprop[0].startsWith("-D")) {
                sysprop[0] = sysprop[0].substring(2);
            }
            Variable var = new Variable();
            var.setKey(sysprop[0]);
            var.setValue(sysprop[1]);
            java.addSysproperty(var);
        }
    }
    // add any env vars
    String[] envs = commandLine.getValues(ENVARGS_OPTION);
    if (envs != null && envs.length > 0) {
        for (String env : envs) {
            String[] envvar = StringUtils.split(env, "=", 2);
            if (envvar.length != 2) {
                continue;
            }
            Variable var = new Variable();
            var.setKey(envvar[0]);
            var.setValue(envvar[1]);
            java.addEnv(var);
        }
    }
    // add any supplied command line args
    String[] args = commandLine.getValues(Options.ARGS_OPTION);
    if (args != null && args.length > 0) {
        for (String arg : args) {
            Argument a = java.createArg();
            a.setValue(arg);
        }
    }
    java.execute();
    return null;
}
Example 50
Project: ecl-master  File: JUnitCommand.java View source code
private JUnitTask createJUnitTask(IJavaProject javaProject, boolean debug, boolean halt) throws Exception {
    Project antProject = new Project();
    BuildLogger buildLogger = new DefaultLogger();
    buildLogger.setEmacsMode(true);
    buildLogger.setMessageOutputLevel(debug ? Project.MSG_DEBUG : Project.MSG_INFO);
    buildLogger.setOutputPrintStream(getContext().out);
    buildLogger.setErrorPrintStream(getContext().err);
    antProject.addBuildListener(buildLogger);
    antProject.setBasedir(ProjectUtils.getPath(javaProject.getProject()));
    // construct classpath
    Path classpath = new Path(antProject);
    String[] paths = ClasspathUtils.getClasspath(javaProject);
    for (String path : paths) {
        Path.PathElement pe = classpath.createPathElement();
        pe.setPath(path);
    }
    // add some ant jar files otherwise ant will fail to load them.
    Bundle bundle = Platform.getBundle("org.apache.ant");
    String pathName = FileLocator.getBundleFile(bundle).getPath();
    classpath.createPathElement().setPath(pathName + "/lib/ant.jar");
    classpath.createPathElement().setPath(pathName + "/lib/ant-junit.jar");
    classpath.createPathElement().setPath(pathName + "/lib/ant-junit4.jar");
    bundle = Platform.getBundle("org.eclim.jdt");
    pathName = FileLocator.getBundleFile(bundle).getPath();
    classpath.createPathElement().setPath(pathName + "/eclim.jdt.jar");
    JUnitTask junit = new JUnitTask();
    junit.setProject(antProject);
    junit.setTaskName("junit");
    junit.setFork(true);
    IProject project = javaProject.getProject();
    String cwd = getPreferences().getValue(project, "org.eclim.java.junit.cwd");
    junit.setDir(new File(cwd != null && cwd.trim().length() > 0 ? cwd : ProjectUtils.getPath(project)));
    junit.setHaltonerror(halt);
    junit.setHaltonfailure(halt);
    junit.createClasspath().append(classpath);
    // we need to add ant.jar to the classpath for the ant test runner to work,
    // but then JUnitTask will complain about multiple ant jars, so prevent
    // that.
    Field forkedPathChecked = JUnitTask.class.getDeclaredField("forkedPathChecked");
    forkedPathChecked.setAccessible(true);
    forkedPathChecked.set(junit, true);
    FormatterElement formatter = new FormatterElement();
    junit.addFormatter(formatter);
    formatter.setClassname("org.eclim.plugin.jdt.command.junit.ResultFormatter");
    formatter.setUseFile(false);
    return junit;
}
Example 51
Project: eclim-master  File: JUnitCommand.java View source code
private JUnitTask createJUnitTask(IJavaProject javaProject, boolean debug, boolean halt) throws Exception {
    Project antProject = new Project();
    BuildLogger buildLogger = new DefaultLogger();
    buildLogger.setEmacsMode(true);
    buildLogger.setMessageOutputLevel(debug ? Project.MSG_DEBUG : Project.MSG_INFO);
    buildLogger.setOutputPrintStream(getContext().out);
    buildLogger.setErrorPrintStream(getContext().err);
    antProject.addBuildListener(buildLogger);
    antProject.setBasedir(ProjectUtils.getPath(javaProject.getProject()));
    // construct classpath
    Path classpath = new Path(antProject);
    String[] paths = ClasspathUtils.getClasspath(javaProject);
    for (String path : paths) {
        Path.PathElement pe = classpath.createPathElement();
        pe.setPath(path);
    }
    // add some ant jar files otherwise ant will fail to load them.
    Bundle bundle = Platform.getBundle("org.apache.ant");
    String pathName = FileLocator.getBundleFile(bundle).getPath();
    classpath.createPathElement().setPath(pathName + "/lib/ant.jar");
    classpath.createPathElement().setPath(pathName + "/lib/ant-junit.jar");
    classpath.createPathElement().setPath(pathName + "/lib/ant-junit4.jar");
    bundle = Platform.getBundle("org.eclim.jdt");
    pathName = FileLocator.getBundleFile(bundle).getPath();
    classpath.createPathElement().setPath(pathName + "/eclim.jdt.jar");
    JUnitTask junit = new JUnitTask();
    junit.setProject(antProject);
    junit.setTaskName("junit");
    junit.setFork(true);
    IProject project = javaProject.getProject();
    String cwd = getPreferences().getValue(project, "org.eclim.java.junit.cwd");
    junit.setDir(new File(cwd != null && cwd.trim().length() > 0 ? cwd : ProjectUtils.getPath(project)));
    junit.setHaltonerror(halt);
    junit.setHaltonfailure(halt);
    junit.createClasspath().append(classpath);
    // we need to add ant.jar to the classpath for the ant test runner to work,
    // but then JUnitTask will complain about multiple ant jars, so prevent
    // that.
    Field forkedPathChecked = JUnitTask.class.getDeclaredField("forkedPathChecked");
    forkedPathChecked.setAccessible(true);
    forkedPathChecked.set(junit, true);
    FormatterElement formatter = new FormatterElement();
    junit.addFormatter(formatter);
    formatter.setClassname("org.eclim.plugin.jdt.command.junit.ResultFormatter");
    formatter.setUseFile(false);
    return junit;
}
Example 52
Project: eclipse-core-resources-master  File: ConvertPath.java View source code
protected void convertFileSystemPathToResourcePath(IPath path) {
    IResource resource;
    if (Platform.getLocation().equals(path)) {
        resource = ResourcesPlugin.getWorkspace().getRoot();
    } else {
        resource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(path);
        if (resource == null)
            throw new //$NON-NLS-1$
            BuildException(//$NON-NLS-1$
            Policy.bind("exception.noProjectMatchThePath", fileSystemPath.toOSString()));
    }
    if (property != null)
        getProject().setUserProperty(property, resource.getFullPath().toString());
    if (pathID != null) {
        Path newPath = new Path(getProject(), resource.getFullPath().toString());
        getProject().addReference(pathID, newPath);
    }
}
Example 53
Project: eclipse.platform.resources-master  File: ConvertPath.java View source code
protected void convertFileSystemPathToResourcePath(IPath path) {
    IResource resource;
    if (Platform.getLocation().equals(path)) {
        resource = ResourcesPlugin.getWorkspace().getRoot();
    } else {
        resource = ResourcesPlugin.getWorkspace().getRoot().getContainerForLocation(path);
        if (resource == null)
            throw new //$NON-NLS-1$
            BuildException(//$NON-NLS-1$
            Policy.bind("exception.noProjectMatchThePath", fileSystemPath.toOSString()));
    }
    if (property != null)
        getProject().setUserProperty(property, resource.getFullPath().toString());
    if (pathID != null) {
        Path newPath = new Path(getProject(), resource.getFullPath().toString());
        getProject().addReference(pathID, newPath);
    }
}
Example 54
Project: eucalyptus-fork-2.0-master  File: BuildBindings.java View source code
public void execute() {
    PrintStream buildLog;
    try {
        buildLog = new PrintStream(new FileOutputStream("bind.log", false));
        System.setOut(buildLog);
        System.setErr(buildLog);
    } catch (FileNotFoundException e2) {
        System.setOut(oldOut);
        System.setErr(oldErr);
    }
    if (this.classFileSets.isEmpty()) {
        throw new BuildException("No classes were provided to bind.");
    } else if (this.bindingFileSets.isEmpty()) {
        throw new BuildException("No bindings were provided to bind.");
    } else {
        try {
            System.setProperty("java.class.path", ((AntClassLoader) BuildBindings.class.getClassLoader()).getClasspath());
        } catch (Exception e) {
            System.err.println("Failed setting classpath from Ant task");
        }
        Path path = new Path(getProject());
        for (String p : paths()) {
            path.add(new Path(getProject(), p));
        }
        for (File f : new File("lib").listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
            }
        })) {
            path.add(new Path(getProject(), f.getAbsolutePath()));
        }
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        List<BindingGenerator> generators = BindingGenerator.getGenerators();
        try {
            AntClassLoader loader = this.getProject().createClassLoader(path);
            Thread.currentThread().setContextClassLoader(loader);
            //        System.err.print( "class path: " + loader.getClasspath( ) );
            BindingGenerator.MSG_TYPE = loader.forceLoadClass("edu.ucsb.eucalyptus.msgs.BaseMessage");
            BindingGenerator.DATA_TYPE = loader.forceLoadClass("edu.ucsb.eucalyptus.msgs.EucalyptusData");
            loader.forceLoadClass("org.jibx.binding.model.JiBX_bindingFactory");
            for (FileSet fs : this.classFileSets) {
                for (String classFileName : fs.getDirectoryScanner(getProject()).getIncludedFiles()) {
                    try {
                        if (!classFileName.endsWith("class"))
                            continue;
                        Class c = loader.forceLoadClass(classFileName.replaceFirst("[^/]*/[^/]*/", "").replaceAll("/", ".").replaceAll("\\.class.{0,1}", ""));
                        if (BindingGenerator.MSG_TYPE.isAssignableFrom(c) || BindingGenerator.DATA_TYPE.isAssignableFrom(c)) {
                            for (BindingGenerator gen : generators) {
                                gen.processClass(c);
                            }
                        }
                    } catch (ClassNotFoundException e) {
                        error(e);
                    }
                }
            }
        } catch (ClassNotFoundException e1) {
            error(e1);
        } finally {
            try {
                for (BindingGenerator gen : generators) {
                    gen.close();
                }
            } catch (Throwable e) {
                error(e);
            }
            Thread.currentThread().setContextClassLoader(old);
        }
        try {
            Compile compiler = new Compile(true, true, false, false, false);
            compiler.compile(paths(), bindings());
        } catch (Throwable e) {
            error(e);
        } finally {
            System.setOut(oldOut);
            System.setErr(oldErr);
        }
    }
}
Example 55
Project: intellij-community-master  File: GenerateGroovyDocAction.java View source code
private static void generateGroovydoc(final GroovyDocConfiguration configuration, final Project project) {
    Runnable groovyDocRun = () -> {
        Groovydoc groovydoc = new Groovydoc();
        groovydoc.setProject(new org.apache.tools.ant.Project());
        groovydoc.setDestdir(new File(configuration.OUTPUT_DIRECTORY));
        groovydoc.setPrivate(configuration.OPTION_IS_PRIVATE);
        groovydoc.setUse(configuration.OPTION_IS_USE);
        groovydoc.setWindowtitle(configuration.WINDOW_TITLE);
        final Path path = new Path(new org.apache.tools.ant.Project());
        path.setPath(configuration.INPUT_DIRECTORY);
        groovydoc.setSourcepath(path);
        String packages = "";
        for (int i = 0; i < configuration.PACKAGES.length; i++) {
            final String s = configuration.PACKAGES[i];
            if (s != null && s.isEmpty())
                continue;
            if (i > 0) {
                packages += ",";
            }
            packages += s;
        }
        groovydoc.setPackagenames(packages);
        final ProgressIndicator progressIndicator = ProgressManager.getInstance().getProgressIndicator();
        progressIndicator.setIndeterminate(true);
        progressIndicator.setText(GroovyDocBundle.message("groovy.doc.progress.indication.text"));
        groovydoc.execute();
    };
    ProgressManager.getInstance().runProcessWithProgressSynchronously(groovyDocRun, GroovyDocBundle.message("groovy.documentation.generating"), false, project);
    if (configuration.OPEN_IN_BROWSER) {
        File url = new File(configuration.OUTPUT_DIRECTORY, INDEX_HTML);
        if (url.exists()) {
            BrowserUtil.browse(url);
        }
    }
}
Example 56
Project: japi-checker-master  File: BytecodeBackwardCompatibilityCheckerTask.java View source code
public void execute() {
    if (getReferenceFile() == null) {
        throw new BuildException("The 'referenceFile' attribute is not defined.");
    }
    if (getFile() == null) {
        throw new BuildException("The 'file' attribute is not defined.");
    }
    log("Checking " + getFile().getAbsolutePath() + " backward compatibility against " + getReferenceFile().getAbsolutePath());
    try {
        BCChecker checker = new BCChecker();
        // Configuring the reporting
        MuxReporter mux = new MuxReporter();
        mux.add(new AntReporter(this));
        SeverityCountReporter ec = new SeverityCountReporter();
        mux.add(ec);
        // Setting up the classpaths for the reference and new version.
        for (Path path : this.referenceClasspaths) {
            for (String filename : path.list()) {
                checker.addToReferenceClasspath(new File(filename));
            }
        }
        for (Path path : this.classpaths) {
            for (String filename : path.list()) {
                checker.addToNewArtifactClasspath(new File(filename));
            }
        }
        // Load rules
        List<Rule> rules = new ArrayList<Rule>();
        for (RuleSet ruleSet : ruleSets) {
            for (com.googlecode.japi.checker.ant.Rule rule : ruleSet.getRules()) {
                try {
                    @SuppressWarnings("unchecked") Class<Rule> clazz = (Class<Rule>) this.getClass().getClassLoader().loadClass(rule.getClassname());
                    rules.add(clazz.newInstance());
                } catch (ClassNotFoundException e) {
                    throw new BuildException(e.getMessage(), e);
                } catch (InstantiationException e) {
                    throw new BuildException(e.getMessage(), e);
                } catch (IllegalAccessException e) {
                    throw new BuildException(e.getMessage(), e);
                }
            }
        }
        // Running the check...
        checker.setReporter(mux);
        checker.setRules(rules);
        checker.checkBacwardCompatibility(getReferenceFile(), getFile());
        // Summary, failing ant in case of error...
        if (ec.hasSeverity()) {
            log("You have " + ec.getCount() + " backward compatibility issues.", Project.MSG_ERR);
            if (failOnError) {
                throw new BuildException("You have " + ec.getCount() + " backward compatibility issues.");
            }
        } else {
            log("No backward compatibility issue found.");
        }
    } catch (IOException e) {
        throw new BuildException(e.getMessage(), e);
    }
}
Example 57
Project: jaxb-master  File: SchemaGenBase.java View source code
void setupForkCommand(String className) {
    ClassLoader loader = this.getClass().getClassLoader();
    while (loader != null && !(loader instanceof AntClassLoader)) {
        loader = loader.getParent();
    }
    String antcp = loader != null ? //taskedef cp
    ((AntClassLoader) loader).getClasspath() : //system classloader, ie. env CLASSPATH=...
    System.getProperty("java.class.path");
    // try to find tools.jar and add it to the cp
    // so the behaviour on all JDKs is the same
    // (avoid creating MaskingClassLoader on non-Mac JDKs)
    File jreHome = new File(System.getProperty("java.home"));
    File toolsJar = new File(jreHome.getParent(), "lib/tools.jar");
    if (toolsJar.exists()) {
        antcp += File.pathSeparatorChar + toolsJar.getAbsolutePath();
    }
    cmd.createClasspath(getProject()).append(new Path(getProject(), antcp));
    cmd.setClassname(className);
}
Example 58
Project: jaxws-master  File: WsGen2.java View source code
@Override
protected CommandlineJava setupCommand() {
    CommandlineJava cmd = super.setupCommand();
    Path classpath = getClasspath();
    if (classpath != null && !classpath.toString().equals("")) {
        cmd.createArgument().setValue("-classpath");
        cmd.createArgument().setPath(classpath);
    }
    //-Xnocompile option
    if (isXnocompile()) {
        cmd.createArgument().setValue("-Xnocompile");
    }
    if (getGenwsdl()) {
        String tmp = "-wsdl";
        if (protocol.length() > 0) {
            tmp += ":" + protocol;
        }
        cmd.createArgument().setValue(tmp);
        if (serviceName != null && serviceName.length() > 0) {
            cmd.createArgument().setValue("-servicename");
            cmd.createArgument().setValue(serviceName);
        }
        if (portName != null && portName.length() > 0) {
            cmd.createArgument().setValue("-portname");
            cmd.createArgument().setValue(portName);
        }
        if (getInlineSchemas()) {
            cmd.createArgument().setValue("-inlineSchemas");
        }
    }
    // r option
    if (null != getResourcedestdir() && !getResourcedestdir().getName().equals("")) {
        cmd.createArgument().setValue("-r");
        cmd.createArgument().setFile(getResourcedestdir());
    }
    if (externalMetadataFiles != null) {
        for (ExternalMetadata file : externalMetadataFiles) {
            cmd.createArgument().setValue("-x");
            cmd.createArgument().setValue(file.file);
        }
    }
    for (String a : getJavacargs().getArguments()) {
        cmd.createArgument().setValue("-J" + a);
    }
    if (getSei() != null) {
        cmd.createArgument().setValue(getSei());
    }
    return cmd;
}
Example 59
Project: jruby-maven-plugins-master  File: AntLauncher.java View source code
@Override
protected void doExecute(final File launchDirectory, final List<String> args, final File outputFile) {
    final Java java = new Java();
    java.setProject(this.project);
    java.setClassname("org.jruby.Main");
    java.setFailonerror(true);
    java.setFork(true);
    java.setDir(launchDirectory);
    for (final Map.Entry<String, String> entry : this.factory.environment().entrySet()) {
        Variable v = new Variable();
        v.setKey(entry.getKey());
        v.setValue(entry.getValue());
        java.addEnv(v);
    }
    // TODO add isDebugable to the logger and log only when debug is needed
    this.logger.debug("java classpath  : " + this.project.getReference(MAVEN_CLASSPATH));
    if (this.factory.environment().size() > 0) {
        this.logger.debug("environment     :");
        for (final Map.Entry<String, String> entry : this.factory.environment().entrySet()) {
            this.logger.debug("\t\t" + entry.getKey() + " => " + entry.getValue());
        }
    }
    for (final String arg : factory.switches.list) {
        java.createArg().setValue(arg);
    }
    for (final String arg : args) {
        java.createArg().setValue(arg);
    }
    Path temp = (Path) this.project.getReference(MAVEN_CLASSPATH);
    if (this.factory.jrubyJar != null) {
        temp.add(new Path(project, this.factory.jrubyJar.getAbsolutePath()));
    }
    java.createJvmarg().setValue("-cp");
    java.createJvmarg().setPath(temp);
    for (String arg : factory.jvmArgs.list) {
        java.createJvmarg().setValue(arg);
    }
    // hack to avoid jruby-core in bootclassloader where as the dependent jars are in system classloader
    if (this.factory.jrubyJar != null && this.factory.jrubyJar.equals(this.factory.jrubyStdlibJar)) {
        java.createJvmarg().setValue("-Xbootclasspath/a:" + this.factory.jrubyJar.getAbsolutePath());
    }
    if (this.factory.jrubyJar == null && System.getProperty("jruby.home") != null) {
        Variable v = new Variable();
        v.setKey("jruby.home");
        v.setValue(System.getProperty("jruby.home"));
        java.addSysproperty(v);
        File lib = System.getProperty("jruby.lib") != null ? new File(System.getProperty("jruby.lib")) : new File(System.getProperty("jruby.home"), "lib");
        File jrubyJar = new File(lib, "jruby.jar");
        java.createJvmarg().setValue("-Xbootclasspath/a:" + jrubyJar.getAbsolutePath());
    }
    if (outputFile != null) {
        java.setOutput(outputFile);
    }
    java.execute();
}
Example 60
Project: narayana-master  File: ClasspathBuilder.java View source code
public void execute() throws BuildException {
    if (_filename == null) {
        throw new BuildException("No filename specified to store built classpath!");
    }
    if (_paths.size() > 0) {
        try {
            for (int filenameCount = 0; filenameCount < _filename.length; filenameCount++) {
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(_filename[filenameCount], !_clear)));
                for (int count = 0; count < _paths.size(); count++) {
                    Object obj = _paths.get(count);
                    if (obj instanceof Path) {
                        Path path = (Path) obj;
                        String[] paths = path.list();
                        for (int pathCount = 0; pathCount < paths.length; pathCount++) {
                            out.write(paths[pathCount] + "\n");
                        }
                    }
                }
                out.close();
            }
        } catch (java.io.IOException e) {
            throw new BuildException("Failed to update file (reason: " + e + ")");
        }
    } else if (_clear) {
        /**
             * If a request to clear the file has been made but no entries have been
             * given then we need to delete the classpath builder file.
             */
        for (int filenameCount = 0; filenameCount < _filename.length; filenameCount++) {
            new File(_filename[filenameCount]).delete();
        }
    }
    if (_property != null) {
        putClasspathInProperty(_filename, _property);
    }
}
Example 61
Project: oceano-master  File: CheckSignatureTask.java View source code
public void execute() throws BuildException {
    validate();
    try {
        log("Checking unresolved references to " + signature, Project.MSG_INFO);
        if (!signature.isFile()) {
            throw new BuildException("Could not find signature: " + signature);
        }
        final Set ignoredPackages = buildPackageList();
        Iterator i = ignores.iterator();
        while (i.hasNext()) {
            Ignore ignore = (Ignore) i.next();
            if (ignore == null || ignore.getClassName() == null)
                continue;
            ignoredPackages.add(ignore.getClassName().replace('.', '/'));
        }
        final SignatureChecker signatureChecker = new SignatureChecker(new FileInputStream(signature), ignoredPackages, new AntLogger(this));
        i = paths.iterator();
        while (i.hasNext()) {
            Path path = (Path) i.next();
            final String[] files = path.list();
            for (int j = 0; j < files.length; j++) {
                signatureChecker.process(new File(files[j]));
            }
        }
        if (signatureChecker.isSignatureBroken()) {
            throw new BuildException("Signature errors found. Verify them and put @IgnoreJRERequirement on them.", getLocation());
        }
    } catch (IOException e) {
        throw new BuildException("Failed to check signatures", e);
    }
}
Example 62
Project: platform_external_emma-master  File: reportTask.java View source code
public void execute() throws BuildException {
    if (isEnabled()) {
        final String[] reportTypes = m_reportCfg.getReportTypes();
        if (// no "txt" default for report processor
        (reportTypes == null) || (reportTypes.length == 0))
            throw (BuildException) newBuildException(getTaskName() + ": no report types specified: provide at least one of <txt>, <html>, <lcov>, <xml> nested elements", location).fillInStackTrace();
        String[] files = getDataPath(true);
        if ((files == null) || (files.length == 0))
            throw (BuildException) newBuildException(getTaskName() + ": no valid input data files have been specified", location).fillInStackTrace();
        final Path srcpath = m_reportCfg.getSourcepath();
        // combine report and all generic settings:
        final IProperties settings;
        {
            final IProperties taskSettings = getTaskSettings();
            final IProperties reportSettings = m_reportCfg.getReportSettings();
            // named report settings override generic named settings and file
            // settings have lower priority than any explicitly named overrides:
            settings = IProperties.Factory.combine(reportSettings, taskSettings);
        }
        final ReportProcessor processor = ReportProcessor.create();
        processor.setDataPath(files);
        files = null;
        processor.setSourcePath(srcpath != null ? srcpath.list() : null);
        processor.setReportTypes(reportTypes);
        processor.setPropertyOverrides(settings);
        processor.run();
    }
}
Example 63
Project: rapid-framework-master  File: BaseGeneratorTask.java View source code
private void setContextClassLoader() {
    if (classpath == null) {
        String cp = ((AntClassLoader) getClass().getClassLoader()).getClasspath();
        classpath = new Path(getProject(), cp);
    }
    AntClassLoader classloader = new AntClassLoader(getProject(), classpath, true);
    Thread.currentThread().setContextClassLoader(classloader);
}
Example 64
Project: WhileyCompiler-master  File: AntTask.java View source code
// =======================================================================
// Execute
// =======================================================================
@Override
public void execute() throws BuildException {
    try {
        List<Path.Entry<WhileyFile>> files = command.getModifiedSourceFiles();
        Compile.Result r = command.execute(files);
        if (r == Compile.Result.SUCCESS) {
            if (command.getVerify()) {
                log("Compiled and Verified " + files.size() + " source file(s)");
            } else {
                log("Compiled " + files.size() + " source file(s)");
            }
        } else {
            throw new BuildException();
        }
    } catch (Exception e) {
        throw new BuildException(e);
    }
}
Example 65
Project: cobertura-java7-master  File: FunctionalTest.java View source code
/**
	 * Use the ant 'java' task to run the test.xml
	 * file and the specified target.
	 */
private static void runTestAntScript(String testName, String target) throws IOException {
    Java task = new Java();
    task.setTaskName("java");
    task.setProject(new Project());
    task.init();
    // Call ant launcher.  Requires ant-lancher.jar.
    task.setClassname("org.apache.tools.ant.launch.Launcher");
    task.setFork(true);
    AntUtil.transferCoberturaDataFileProperty(task);
    if (forkedJVMDebugPort > 0) {
        task.createJvmarg().setValue("-Xdebug");
        task.createJvmarg().setValue("-Xrunjdwp:transport=dt_socket,address=" + forkedJVMDebugPort + ",server=y,suspend=y");
    }
    task.createArg().setValue("-f");
    task.createArg().setValue(BASEDIR + "/build.xml");
    task.createArg().setValue(target);
    task.setFailonerror(true);
    // Set output to go to a temp file
    File outputFile = Util.createTemporaryTextFile("cobertura-test");
    task.setOutput(outputFile);
    // Set the classpath to the same classpath as this JVM
    Path classpath = task.createClasspath();
    PathElement pathElement = classpath.createPathElement();
    pathElement.setPath(System.getProperty("java.class.path"));
    try {
        task.execute();
    } finally {
        if (outputFile.exists()) {
            // Put the contents of the output file in the exception
            System.out.println("\n\n\nOutput from Ant for " + testName + " test:\n----------------------------------------\n" + Util.getText(outputFile) + "----------------------------------------");
            outputFile.delete();
        }
    }
}
Example 66
Project: liquidware_beagleboard_android_sdk-master  File: SetupTask.java View source code
@Override
public void execute() throws BuildException {
    Project antProject = getProject();
    // get the SDK location
    String sdkLocation = antProject.getProperty(ProjectProperties.PROPERTY_SDK);
    // check if it's valid and exists
    if (sdkLocation == null || sdkLocation.length() == 0) {
        // LEGACY support: project created with 1.6 or before may be using a different
        // property to declare the location of the SDK. At this point, we cannot
        // yet check which target is running so we check both always.
        sdkLocation = antProject.getProperty(ProjectProperties.PROPERTY_SDK_LEGACY);
        if (sdkLocation == null || sdkLocation.length() == 0) {
            throw new BuildException("SDK Location is not set.");
        }
    }
    File sdk = new File(sdkLocation);
    if (sdk.isDirectory() == false) {
        throw new BuildException(String.format("SDK Location '%s' is not valid.", sdkLocation));
    }
    // get the target property value
    String targetHashString = antProject.getProperty(ProjectProperties.PROPERTY_TARGET);
    boolean isTestProject = false;
    if (antProject.getProperty("tested.project.dir") != null) {
        isTestProject = true;
    }
    if (targetHashString == null) {
        throw new BuildException("Android Target is not set.");
    }
    // load up the sdk targets.
    final ArrayList<String> messages = new ArrayList<String>();
    SdkManager manager = SdkManager.createManager(sdkLocation, new ISdkLog() {

        public void error(Throwable t, String errorFormat, Object... args) {
            if (errorFormat != null) {
                messages.add(String.format("Error: " + errorFormat, args));
            }
            if (t != null) {
                messages.add("Error: " + t.getMessage());
            }
        }

        public void printf(String msgFormat, Object... args) {
            messages.add(String.format(msgFormat, args));
        }

        public void warning(String warningFormat, Object... args) {
            messages.add(String.format("Warning: " + warningFormat, args));
        }
    });
    if (manager == null) {
        // since we failed to parse the SDK, lets display the parsing output.
        for (String msg : messages) {
            System.out.println(msg);
        }
        throw new BuildException("Failed to parse SDK content.");
    }
    // resolve it
    IAndroidTarget androidTarget = manager.getTargetFromHashString(targetHashString);
    if (androidTarget == null) {
        throw new BuildException(String.format("Unable to resolve target '%s'", targetHashString));
    }
    // display it
    System.out.println("Project Target: " + androidTarget.getName());
    if (androidTarget.isPlatform() == false) {
        System.out.println("Vendor: " + androidTarget.getVendor());
        System.out.println("Platform Version: " + androidTarget.getVersionName());
    }
    System.out.println("API level: " + androidTarget.getVersion().getApiString());
    // always check the manifest minSdkVersion.
    checkManifest(antProject, androidTarget.getVersion());
    // sets up the properties to find android.jar/framework.aidl/target tools
    String androidJar = androidTarget.getPath(IAndroidTarget.ANDROID_JAR);
    antProject.setProperty(PROPERTY_ANDROID_JAR, androidJar);
    String androidAidl = androidTarget.getPath(IAndroidTarget.ANDROID_AIDL);
    antProject.setProperty(PROPERTY_ANDROID_AIDL, androidAidl);
    antProject.setProperty(PROPERTY_AAPT, androidTarget.getPath(IAndroidTarget.AAPT));
    antProject.setProperty(PROPERTY_AIDL, androidTarget.getPath(IAndroidTarget.AIDL));
    antProject.setProperty(PROPERTY_DX, androidTarget.getPath(IAndroidTarget.DX));
    // sets up the boot classpath
    // create the Path object
    Path bootclasspath = new Path(antProject);
    // create a PathElement for the framework jar
    PathElement element = bootclasspath.createPathElement();
    element.setPath(androidJar);
    // create PathElement for each optional library.
    IOptionalLibrary[] libraries = androidTarget.getOptionalLibraries();
    if (libraries != null) {
        HashSet<String> visitedJars = new HashSet<String>();
        for (IOptionalLibrary library : libraries) {
            String jarPath = library.getJarPath();
            if (visitedJars.contains(jarPath) == false) {
                visitedJars.add(jarPath);
                element = bootclasspath.createPathElement();
                element.setPath(library.getJarPath());
            }
        }
    }
    // finally sets the path in the project with a reference
    antProject.addReference(REF_CLASSPATH, bootclasspath);
    // find the file to import, and import it.
    String templateFolder = androidTarget.getPath(IAndroidTarget.TEMPLATES);
    // older names. This sets those properties to make sure the rules will work.
    if (androidTarget.getVersion().getApiLevel() <= 4) {
        // 1.6 and earlier
        antProject.setProperty(PROPERTY_ANDROID_JAR_LEGACY, androidJar);
        antProject.setProperty(PROPERTY_ANDROID_AIDL_LEGACY, androidAidl);
        antProject.setProperty(ProjectProperties.PROPERTY_SDK_LEGACY, sdkLocation);
        String appPackage = antProject.getProperty(ProjectProperties.PROPERTY_APP_PACKAGE);
        if (appPackage != null && appPackage.length() > 0) {
            antProject.setProperty(ProjectProperties.PROPERTY_APP_PACKAGE_LEGACY, appPackage);
        }
    }
    // Now the import section. This is only executed if the task actually has to import a file.
    if (mDoImport) {
        // make sure the file exists.
        File templates = new File(templateFolder);
        if (templates.isDirectory() == false) {
            throw new BuildException(String.format("Template directory '%s' is missing.", templateFolder));
        }
        String importedRulesFileName = isTestProject ? ANDROID_TEST_RULES : ANDROID_RULES;
        // now check the rules file exists.
        File rules = new File(templateFolder, importedRulesFileName);
        if (rules.isFile() == false) {
            throw new BuildException(String.format("Build rules file '%s' is missing.", templateFolder));
        }
        // set the file location to import
        setFile(rules.getAbsolutePath());
        // and import
        super.execute();
    }
}
Example 67
Project: aspectwerkz-master  File: AspectWerkzCTask.java View source code
private List getDirectories(Path path) throws BuildException {
    List dirs = new ArrayList();
    if (path == null)
        return dirs;
    for (int i = 0; i < path.list().length; i++) {
        File dir = getProject().resolveFile(path.list()[i]);
        if (!dir.exists()) {
            throw new BuildException(" \"" + dir.getPath() + "\" does not exist!", getLocation());
        }
        //.getAbsolutePath());
        dirs.add(dir);
    }
    return dirs;
}
Example 68
Project: core-android-master  File: StringEncrypt.java View source code
/**
	 * Entry point, per ogni file del path (passato come argomento nel
	 * build.xml) viene creato un file encoded con le stringhe cifrate. Al
	 * termine viene generato un file M.java con tutti i metodi relativi alle
	 * stringhe.
	 */
public void execute() {
    File userdir = new File(System.getProperty("user.dir"));
    String dir = userdir.toURI().getPath();
    logInfo("execute: " + dir, true);
    for (Iterator itPaths = paths.iterator(); itPaths.hasNext(); ) {
        Path path = (Path) itPaths.next();
        String[] includedFiles = path.list();
        for (int i = 0; i < includedFiles.length; i++) {
            URI fileUri = (new File(includedFiles[i])).toURI();
            String filename = fileUri.getPath().replace(dir + "/", "");
            File destfile = new File(destDir + "/" + filename.replace(baseDir, ""));
            logInfo("  encode: " + filename + " -> " + destfile);
            mkdir(destfile.getParent());
            try {
                // viene creato un nuovo file con la codifica delle stringhe
                encodeFile(filename, destfile.getAbsolutePath());
            } catch (IOException ex) {
                ex.printStackTrace();
                logInfo(ex.toString());
            }
        }
    }
    // logInfo("Decoding class: " + mFile);
    // istanza che si occupa di generare il file M.java
    DecodingClass dc = new DecodingClass(destDir + "/com/android/m/M.java", mFile);
    for (EncodedTuple tuple : encodedTuples) {
        dc.append(tuple.method, tuple.ebytes, tuple.kbytes);
    }
    dc.close();
}
Example 69
Project: eclipselink.runtime-master  File: ProjectTask.java View source code
/**
     * Creates and configures an AntClassLoader instance from the
     * nested classpath element.
     */
private void createClassLoader() {
    Path commandlineClasspath = getCommandline().getClasspath();
    if (commandlineClasspath != null) {
        if (classLoader == null) {
            Path classpath = (Path) commandlineClasspath.clone();
            if (this.userClasspath.length() > 0) {
                Path path = new Path(getProject(), this.userClasspath);
                classpath.append(path);
            }
            classLoader = getProject().createClassLoader(classpath);
            classLoader.setParentFirst(false);
            classLoader.addJavaLibraries();
            log(this.stringRepository.getString("usingClasspath", classLoader.getClasspath()), Project.MSG_VERBOSE);
        }
    }
}
Example 70
Project: felix-master  File: IPojoTask.java View source code
/**
     * Execute the Ant Task.
     *
     * @see org.apache.tools.ant.Task#execute()
     */
public void execute() {
    if (m_input == null && m_directory == null) {
        throw new BuildException("Neither input bundle nor directory specified");
    }
    if (m_input != null && !m_input.exists()) {
        throw new BuildException("The input bundle " + m_input.getAbsolutePath() + " does not exist");
    }
    if (m_directory != null && !m_directory.exists()) {
        throw new BuildException("The input directory " + m_directory.getAbsolutePath() + " does not exist");
    }
    if (m_directory != null && !m_directory.isDirectory()) {
        throw new BuildException("The input directory " + m_directory.getAbsolutePath() + " is not a directory");
    }
    if (m_input != null) {
        log("Input bundle file : " + m_input.getAbsolutePath());
    } else {
        log("Input directory : " + m_directory.getAbsolutePath());
    }
    if (m_manifest != null) {
        if (m_input != null) {
            throw new BuildException("The manifest location cannot be used when manipulating an existing bundle");
        }
        if (!m_manifest.exists()) {
            throw new BuildException("The manifest file " + m_manifest.getAbsolutePath() + " does not exist");
        }
    }
    // Get metadata file
    if (m_metadata == null) {
        m_metadata = new File("./metadata.xml");
        if (!m_metadata.exists()) {
            // Verify if annotations are ignored
            if (m_ignoreAnnotations) {
                log("No metadata file found & annotations ignored : nothing to do");
                return;
            } else {
                log("No metadata file found - trying to use only annotations");
                m_metadata = null;
            }
        } else {
            log("Metadata file : " + m_metadata.getAbsolutePath());
        }
    } else {
        // Metadata file is specified, check existence
        if (!m_metadata.exists()) {
            throw new BuildException("No metadata file found - the file " + m_metadata.getAbsolutePath() + " does not exist");
        } else {
            if (m_metadata.isDirectory()) {
                log("Metadata directory : " + m_metadata.getAbsolutePath());
            } else {
                log("Metadata file : " + m_metadata.getAbsolutePath());
            }
        }
    }
    initializeSaxDriver();
    log("Start manipulation");
    if (m_input != null) {
        // Prepare output file
        if (m_output == null) {
            m_output = new File("./_out.jar");
        }
        if (m_output.exists()) {
            boolean r = m_output.delete();
            if (!r) {
                throw new BuildException("The file " + m_output.getAbsolutePath() + " cannot be deleted");
            }
        }
    }
    AntReporter reporter = new AntReporter(getProject());
    Pojoization pojo = new Pojoization(reporter);
    if (m_ignoreAnnotations) {
        pojo.disableAnnotationProcessing();
    }
    if (!m_ignoreLocalXSD) {
        pojo.setUseLocalXSD();
    }
    Path classpath = getClasspath();
    classpath.addJavaRuntime();
    // Adding the input jar or directory
    if (m_classpath == null) {
        m_classpath = createClasspath();
    }
    Path element = m_classpath.createPath();
    if (m_input != null) {
        element.setLocation(m_input.getAbsoluteFile());
    } else if (m_directory != null) {
        element.setLocation(m_directory.getAbsoluteFile());
    }
    m_classpath.add(element);
    ClassLoader loader = getProject().createClassLoader(getClasspath());
    if (m_input != null) {
        pojo.pojoization(m_input, m_output, m_metadata, loader);
    } else {
        pojo.directoryPojoization(m_directory, m_metadata, m_manifest, loader);
    }
    for (int i = 0; i < reporter.getWarnings().size(); i++) {
        log((String) reporter.getWarnings().get(i), Project.MSG_WARN);
    }
    if (reporter.getErrors().size() > 0) {
        throw new BuildException((String) reporter.getErrors().get(0));
    }
    if (m_input != null) {
        String out;
        if (m_output.getName().equals("_out.jar")) {
            if (m_input.delete()) {
                if (!m_output.renameTo(m_input)) {
                    log("Cannot rename the output jar to " + m_input.getAbsolutePath(), Project.MSG_WARN);
                }
            } else {
                log("Cannot delete the input file : " + m_input.getAbsolutePath(), Project.MSG_WARN);
            }
            out = m_input.getAbsolutePath();
        } else {
            out = m_output.getAbsolutePath();
        }
        log("Bundle manipulation - SUCCESS");
        log("Output file : " + out);
    } else {
        log("Manipulation - SUCCESS");
        log("Output files : " + m_directory.getAbsolutePath());
        if (m_manifest != null) {
            log("Manifest : " + m_manifest.getAbsolutePath());
        }
    }
}
Example 71
Project: liferay-portal-master  File: Java2WsddTask.java View source code
public static String[] generateWsdd(String className, String classPath, String serviceName) throws Exception {
    // Create temp directory
    java.nio.file.Path tempDirPath = Files.createTempDirectory(Paths.get(SystemProperties.get(SystemProperties.TMP_DIR)), null);
    File tempDir = tempDirPath.toFile();
    tempDir.mkdir();
    // axis-java2wsdl
    String wsdlFileName = tempDir + "/service.wsdl";
    int pos = className.lastIndexOf(".");
    String packagePath = className.substring(0, pos);
    String[] packagePaths = StringUtil.split(packagePath, '.');
    String namespace = "urn:";
    for (int i = packagePaths.length - 1; i >= 0; i--) {
        namespace += packagePaths[i];
        if (i > 0) {
            namespace += ".";
        }
    }
    String location = "http://localhost/services/" + serviceName;
    String mappingPackage = packagePath.substring(0, packagePath.lastIndexOf(".")) + ".ws";
    Project project = AntUtil.getProject();
    Java2WsdlAntTask java2Wsdl = new Java2WsdlAntTask();
    NamespaceMapping mapping = new NamespaceMapping();
    mapping.setNamespace(namespace);
    mapping.setPackage(mappingPackage);
    java2Wsdl.setProject(project);
    java2Wsdl.setClassName(className);
    if (Validator.isNotNull(classPath)) {
        java2Wsdl.setClasspath(new Path(project, classPath));
    }
    java2Wsdl.setOutput(new File(wsdlFileName));
    java2Wsdl.setLocation(location);
    java2Wsdl.setNamespace(namespace);
    java2Wsdl.addMapping(mapping);
    java2Wsdl.execute();
    // axis-wsdl2java
    Wsdl2javaAntTask wsdl2Java = new Wsdl2javaAntTask();
    wsdl2Java.setProject(project);
    wsdl2Java.setURL(wsdlFileName);
    wsdl2Java.setOutput(tempDir);
    wsdl2Java.setServerSide(true);
    wsdl2Java.setTestCase(false);
    wsdl2Java.setVerbose(false);
    wsdl2Java.execute();
    // Get content
    String packagePathWithSlashes = StringUtil.replace(packagePath, CharPool.PERIOD, CharPool.SLASH);
    File deployFile = new File(tempDir + "/" + packagePathWithSlashes + "/deploy.wsdd");
    String deployContent = new String(Files.readAllBytes(deployFile.toPath()));
    deployContent = StringUtil.replace(deployContent, packagePath + "." + serviceName + "SoapBindingImpl", className);
    deployContent = _format(deployContent);
    File undeployFile = new File(tempDir + "/" + packagePathWithSlashes + "/undeploy.wsdd");
    String undeployContent = new String(Files.readAllBytes(undeployFile.toPath()));
    undeployContent = _format(undeployContent);
    // Delete temp directory
    DeleteTask.deleteDirectory(tempDir);
    return new String[] { deployContent, undeployContent };
}
Example 72
Project: maven-jellydoc-plugin-master  File: JellydocMojo.java View source code
public void execute() throws MojoExecutionException, MojoFailureException {
    Project p = new Project();
    DefaultLogger logger = new DefaultLogger();
    logger.setErrorPrintStream(System.err);
    logger.setOutputPrintStream(System.out);
    logger.setMessageOutputLevel(getLog().isDebugEnabled() ? Project.MSG_DEBUG : Project.MSG_INFO);
    p.addBuildListener(logger);
    Javadoc javadoc = new Javadoc();
    javadoc.setTaskName("jellydoc");
    javadoc.setProject(p);
    for (Object dir : project.getCompileSourceRoots()) {
        FileSet fs = new FileSet();
        fs.setProject(p);
        fs.setDir(new File(dir.toString()));
        javadoc.addFileset(fs);
    }
    javadoc.setClasspath(makePath(p, (Collection<Artifact>) project.getArtifacts()));
    Javadoc.DocletInfo d = javadoc.createDoclet();
    d.setProject(p);
    d.setName(TagXMLDoclet.class.getName());
    setParam(d, "-d", targetDir().getAbsolutePath());
    Path docletPath = makePath(p, pluginArtifacts);
    try {
        Artifact self = factory.createArtifact("org.jvnet.maven-jellydoc-plugin", "maven-jellydoc-plugin", pluginVersion, null, "maven-plugin");
        resolver.resolve(self, project.getPluginArtifactRepositories(), localRepository);
        docletPath.createPathElement().setLocation(self.getFile());
    } catch (AbstractArtifactResolutionException e) {
        throw new MojoExecutionException("Failed to resolve plugin from within itself", e);
    }
    d.setPath(docletPath);
    // debug support
    //        javadoc.createArg().setLine("-J-Xrunjdwp:transport=dt_socket,server=y,address=8000");
    javadoc.execute();
    generateSchema();
}
Example 73
Project: openjpa-master  File: AbstractTask.java View source code
/**
     * Return the classloader to use.
     */
protected ClassLoader getClassLoader() {
    if (_cl != null)
        return _cl;
    if (classpath != null)
        _cl = new AntClassLoader(getProject(), classpath, useParent);
    else
        _cl = new AntClassLoader(getProject().getCoreLoader(), getProject(), new Path(getProject()), useParent);
    _cl.setIsolated(isolate);
    return _cl;
}
Example 74
Project: org.revisionfilter-master  File: AbstractFindBugsTask.java View source code
/**
	 * Create the FindBugs engine (the Java process that will run
	 * whatever FindBugs-related program this task is
	 * going to execute).
	 */
protected void createFindbugsEngine() {
    findbugsEngine = new Java();
    findbugsEngine.setProject(getProject());
    findbugsEngine.setTaskName(getTaskName());
    findbugsEngine.setFork(true);
    if (jvm.length() > 0)
        findbugsEngine.setJvm(jvm);
    findbugsEngine.setTimeout(timeout);
    if (debug) {
        jvmargs = jvmargs + " -Dfindbugs.debug=true";
    }
    findbugsEngine.createJvmarg().setLine(jvmargs);
    // Add JVM arguments for system properties
    for (SystemProperty systemProperty : systemPropertyList) {
        String jvmArg = "-D" + systemProperty.getName() + "=" + systemProperty.getValue();
        findbugsEngine.createJvmarg().setValue(jvmArg);
    }
    if (homeDir != null) {
        // Use findbugs.home to locate findbugs.jar and the standard
        // plugins.  This is the usual means of initialization.
        File findbugsLib = new File(homeDir, "lib");
        File findbugsLibFindBugs = new File(findbugsLib, "findbugs.jar");
        File findBugsFindBugs = new File(homeDir, "findbugs.jar");
        //log("executing using home dir [" + homeDir + "]");
        if (findbugsLibFindBugs.exists())
            findbugsEngine.setClasspath(new Path(getProject(), findbugsLibFindBugs.getPath()));
        else if (findBugsFindBugs.exists())
            findbugsEngine.setClasspath(new Path(getProject(), findBugsFindBugs.getPath()));
        else
            throw new IllegalArgumentException("Can't find findbugs.jar in " + homeDir);
        findbugsEngine.createJvmarg().setValue("-Dfindbugs.home=" + homeDir.getPath());
    } else {
        // Use an explicitly specified classpath and list of plugin Jars
        // to initialize.  This is useful for other tools which may have
        // FindBugs installed using a non-standard directory layout.
        findbugsEngine.setClasspath(classpath);
        addArg("-pluginList");
        addArg(pluginList.toString());
    }
    // Set the main class to be whatever the subclass's constructor
    // specified.
    findbugsEngine.setClassname(mainClass);
}
Example 75
Project: pitest-master  File: PitestTask.java View source code
private Path generateLaunchClasspath() {
    if (this.pitClasspath == null) {
        throw new BuildException("You must specify the classpath for pitest and its plugins.");
    }
    final Object reference = getProject().getReference(this.pitClasspath);
    if (reference != null) {
        this.pitClasspath = reference.toString();
    }
    return new Path(getProject(), this.pitClasspath);
}
Example 76
Project: PM-master  File: PMDTaskImpl.java View source code
private void setupClassLoader() {
    if (classpath == null) {
        classpath = new Path(project);
    }
    /*
         * 'basedir' is added to the path to make sure that relative paths such
         * as "<ruleset>resources/custom_ruleset.xml</ruleset>" still work when
         * ant is invoked from a different directory using "-f"
         */
    classpath.add(new Path(null, project.getBaseDir().toString()));
    project.log("Using the AntClassLoader: " + classpath, Project.MSG_VERBOSE);
    // must be true, otherwise you'll get ClassCastExceptions as classes
    // are loaded twice
    // and exist in multiple class loaders
    boolean parentFirst = true;
    configuration.setClassLoader(new AntClassLoader(Thread.currentThread().getContextClassLoader(), project, classpath, parentFirst));
    try {
        if (auxClasspath != null) {
            project.log("Using auxclasspath: " + auxClasspath, Project.MSG_VERBOSE);
            configuration.prependClasspath(auxClasspath.toString());
        }
    } catch (IOException ioe) {
        throw new BuildException(ioe.getMessage(), ioe);
    }
}
Example 77
Project: pmd-master  File: PMDTaskImpl.java View source code
private void setupClassLoader() {
    if (classpath == null) {
        classpath = new Path(project);
    }
    /*
         * 'basedir' is added to the path to make sure that relative paths such
         * as "<ruleset>resources/custom_ruleset.xml</ruleset>" still work when
         * ant is invoked from a different directory using "-f"
         */
    classpath.add(new Path(null, project.getBaseDir().toString()));
    project.log("Using the AntClassLoader: " + classpath, Project.MSG_VERBOSE);
    // must be true, otherwise you'll get ClassCastExceptions as classes
    // are loaded twice
    // and exist in multiple class loaders
    boolean parentFirst = true;
    configuration.setClassLoader(new AntClassLoader(Thread.currentThread().getContextClassLoader(), project, classpath, parentFirst));
    try {
        if (auxClasspath != null) {
            project.log("Using auxclasspath: " + auxClasspath, Project.MSG_VERBOSE);
            configuration.prependClasspath(auxClasspath.toString());
        }
    } catch (IOException ioe) {
        throw new BuildException(ioe.getMessage(), ioe);
    }
}
Example 78
Project: RestComm-master  File: PlayConfigurationLoadTask.java View source code
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);
}
Example 79
Project: restcommander-master  File: PlayConfigurationLoadTask.java View source code
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);
}
Example 80
Project: squale-master  File: CheckStyleProcess.java View source code
/**
     * Create a ajava ant task for launch checkstyle
     * 
     * @param pRuleFile The rule file
     * @param sourceDir The directory in which there is the sources to analyze
     * @param pResultFile The result file
     * @return a configured ANT task
     */
private Java createAntTask(File pRuleFile, File sourceDir, File pResultFile) {
    // We create a java ant task
    Java task = new Java();
    // We create the project
    Project antProject = new Project();
    antProject.addBuildListener(this);
    task.setProject(antProject);
    // We fork to avoid classpath problems
    task.setFork(true);
    // The class to call
    task.setClassname("com.puppycrawl.tools.checkstyle.Main");
    // Classpath creation
    Path path = createClassPath(antProject);
    task.setClasspath(path);
    // Jvm argument. We increase the memory allocate to the JVM
    Argument jvmArg = task.createJvmarg();
    jvmArg.setValue("-Xmx128M");
    jvmArg = task.createJvmarg();
    jvmArg.setValue("-Xss1M");
    // We create the task argument
    Argument arg = task.createArg();
    // The result format : xml
    arg = task.createArg();
    arg.setValue("-f");
    arg = task.createArg();
    arg.setValue("xml");
    // Location for the result file
    arg = task.createArg();
    arg.setValue("-o");
    arg = task.createArg();
    arg.setValue(pResultFile.getAbsolutePath());
    // Location of the result file
    arg = task.createArg();
    arg.setValue("-c");
    arg = task.createArg();
    arg.setValue(pRuleFile.getAbsolutePath());
    // Location of the directori in which there ise the file to analyze
    arg = task.createArg();
    arg.setValue("-r");
    arg = task.createArg();
    arg.setValue(sourceDir.getAbsolutePath());
    return task;
}
Example 81
Project: TBLips-master  File: WOPBXBuild.java View source code
@Override
public void execute() throws BuildException {
    Map dico = null;
    Enumeration<FileSet> e;
    /**
		 * Get Dictionary from pbproj
		 */
    try {
        dico = (Map) new Parser(new File(new Path(this.getProject(), getPbxproj()).toString())).propertyList();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    /**
		 * TODO: Handle Better Warnings
		 */
    if (dico == null)
        return;
    /**
		 * Objects contains all probject related objects
		 */
    Map objects = (Map) dico.get("objects");
    String rootObject = (String) dico.get("rootObject");
    PBXProjectCoder coder = new PBXProjectCoder(objects, rootObject);
    String sourcesFiles = this.setUp(coder, rootObject);
    coder = null;
    objects = null;
    dico = null;
    /**
		 * Compile sources
		 */
    Javac javac = new Javac();
    task.getSubtaskFactory().initChildTask(javac);
    javac.setClasspathRef(new Reference(this.getProject(), "classpath"));
    javac.setDestdir(new File(this.getProject().getBaseDir(), "build"));
    javac.setSrcdir(new Path(this.getProject(), "."));
    javac.setIncludes(sourcesFiles);
    javac.setOptimize(true);
    javac.execute();
    /**
		 * Add classes to task
		 */
    e = classes.elements();
    while (e.hasMoreElements()) {
        task.addClasses((WOFileSet) e.nextElement());
    }
    task.execute();
}
Example 82
Project: visualvm-master  File: LocJHIndexer.java View source code
protected void setJHLib(JHIndexer jhindexer) {
    String jhlib, dir, regexp;
    int idx, i;
    FileSet fs;
    File file;
    LinkedList<String> dirs, regexps;
    StringTokenizer st;
    Path path;
    // For each regular expression. //
    dirs = new LinkedList<String>();
    regexps = new LinkedList<String>();
    jhlib = getJhall();
    st = new StringTokenizer(jhlib, " 	\n,");
    while (st.hasMoreTokens()) {
        regexp = st.nextToken();
        // Break the regular expression up into directory and file //
        // components.						 //
        idx = regexp.lastIndexOf("/");
        dir = regexp.substring(0, idx);
        file = new File(dir);
        if (file.exists()) {
            dirs.add(dir);
            regexps.add(regexp.substring(idx + 1));
        }
    }
    if (dirs.size() > 0) {
        path = jhindexer.createClasspath();
        for (i = 0; i < dirs.size(); i++) {
            dir = dirs.get(i);
            regexp = regexps.get(i);
            fs = new FileSet();
            fs.setDir(new File(dir));
            fs.setIncludes(regexp);
            path.addFileset(fs);
        }
    } else {
        throw new BuildException("jhall not found.");
    }
}
Example 83
Project: wala-mirror-master  File: DynamicCallGraphTestBase.java View source code
protected void run(String mainClass, String exclusionsFile, String... args) throws IOException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, InterruptedException {
    Project p = new Project();
    p.setBaseDir(new File(System.getProperty("java.io.tmpdir")));
    p.init();
    p.fireBuildStarted();
    Java childJvm = new Java();
    childJvm.setTaskName("test_" + mainClass.replace('.', '_'));
    childJvm.setClasspath(new Path(p, getClasspathEntry("com.ibm.wala.shrike") + ":" + getClasspathEntry("com.ibm.wala.util") + ":" + instrumentedJarLocation));
    childJvm.setClassname(mainClass);
    String jvmArgs = "-noverify -Xmx500M -DdynamicCGFile=" + cgLocation + " -DdynamicCGHandleMissing=true";
    if (exclusionsFile != null) {
        File tmpFile = TemporaryFile.urlToFile("exclusions.txt", getClass().getClassLoader().getResource(exclusionsFile));
        jvmArgs += " -DdynamicCGFilter=" + tmpFile.getCanonicalPath();
    }
    childJvm.setJvmargs(jvmArgs);
    StringBuffer argsStr = new StringBuffer();
    for (String a : args) {
        argsStr.append(a).append(" ");
    }
    childJvm.setArgs(argsStr.toString());
    childJvm.setFailonerror(true);
    childJvm.setFork(true);
    childJvm.init();
    Process x = Runtime.getRuntime().exec(childJvm.getCommandLine().toString());
    x.waitFor();
    Assert.assertTrue("expected to create call graph", new File(cgLocation).exists());
}
Example 84
Project: was-maven-plugin-master  File: AntTaskUtils.java View source code
private static Project generateAntProject(WebSphereModel model, File antBuildFile, MavenProject project, MavenProjectHelper projectHelper, List<Artifact> pluginArtifact, Log logger) throws MojoExecutionException {
    try {
        Project antProject = new Project();
        ProjectHelper.configureProject(antProject, antBuildFile);
        antProject.init();
        setupLogger(antBuildFile, logger, antProject);
        antProject.setBaseDir(project.getBasedir());
        Path p = new Path(antProject);
        p.setPath(StringUtils.join(project.getCompileClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.compile.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(project.getRuntimeClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.runtime.classpath", p);
        p = new Path(antProject);
        p.setPath(StringUtils.join(project.getTestClasspathElements().iterator(), File.pathSeparator));
        antProject.addReference("maven.test.classpath", p);
        antProject.addReference("maven.plugin.classpath", getPathFromArtifacts(pluginArtifact, antProject));
        antProject.addReference(DEFAULT_MAVEN_PROJECT_REFID, project);
        antProject.addReference(DEFAULT_MAVEN_PROJECT_HELPER_REFID, projectHelper);
        initMavenTasks(antProject);
        copyProperties(project, antProject);
        copyProperties(model.getProperties(), antProject);
        return antProject;
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e);
    } catch (BuildException e) {
        throw new MojoExecutionException("An Ant BuildException has occurred: " + e.getMessage(), e);
    } catch (Throwable e) {
        throw new MojoExecutionException("Error executing ant tasks: " + e.getMessage(), e);
    }
}
Example 85
Project: Wol-master  File: WOPBXBuild.java View source code
@Override
public void execute() throws BuildException {
    Map dico = null;
    Enumeration<FileSet> e;
    /**
		 * Get Dictionary from pbproj
		 */
    try {
        dico = (Map) new Parser(new File(new Path(this.getProject(), getPbxproj()).toString())).propertyList();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    /**
		 * TODO: Handle Better Warnings
		 */
    if (dico == null)
        return;
    /**
		 * Objects contains all probject related objects
		 */
    Map objects = (Map) dico.get("objects");
    String rootObject = (String) dico.get("rootObject");
    PBXProjectCoder coder = new PBXProjectCoder(objects, rootObject);
    String sourcesFiles = this.setUp(coder, rootObject);
    coder = null;
    objects = null;
    dico = null;
    /**
		 * Compile sources
		 */
    Javac javac = new Javac();
    task.getSubtaskFactory().initChildTask(javac);
    javac.setClasspathRef(new Reference(this.getProject(), "classpath"));
    javac.setDestdir(new File(this.getProject().getBaseDir(), "build"));
    javac.setSrcdir(new Path(this.getProject(), "."));
    javac.setIncludes(sourcesFiles);
    javac.setOptimize(true);
    javac.execute();
    /**
		 * Add classes to task
		 */
    e = classes.elements();
    while (e.hasMoreElements()) {
        task.addClasses((WOFileSet) e.nextElement());
    }
    task.execute();
}
Example 86
Project: wolips-master  File: WOPBXBuild.java View source code
@Override
public void execute() throws BuildException {
    Map dico = null;
    Enumeration<FileSet> e;
    /**
		 * Get Dictionary from pbproj
		 */
    try {
        dico = (Map) new Parser(new File(new Path(this.getProject(), getPbxproj()).toString())).propertyList();
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
    /**
		 * TODO: Handle Better Warnings
		 */
    if (dico == null)
        return;
    /**
		 * Objects contains all probject related objects
		 */
    Map objects = (Map) dico.get("objects");
    String rootObject = (String) dico.get("rootObject");
    PBXProjectCoder coder = new PBXProjectCoder(objects, rootObject);
    String sourcesFiles = this.setUp(coder, rootObject);
    coder = null;
    objects = null;
    dico = null;
    /**
		 * Compile sources
		 */
    Javac javac = new Javac();
    task.getSubtaskFactory().initChildTask(javac);
    javac.setClasspathRef(new Reference(this.getProject(), "classpath"));
    javac.setDestdir(new File(this.getProject().getBaseDir(), "build"));
    javac.setSrcdir(new Path(this.getProject(), "."));
    javac.setIncludes(sourcesFiles);
    javac.setOptimize(true);
    javac.execute();
    /**
		 * Add classes to task
		 */
    e = classes.elements();
    while (e.hasMoreElements()) {
        task.addClasses((WOFileSet) e.nextElement());
    }
    task.execute();
}
Example 87
Project: process-master  File: AppBundlerTask.java View source code
private void copyClassPathRefEntries(File javaDirectory) throws IOException {
    if (classPathRef != null) {
        org.apache.tools.ant.types.Path classpath = (org.apache.tools.ant.types.Path) classPathRef.getReferencedObject(getProject());
        Iterator<?> iter = classpath.iterator();
        while (iter.hasNext()) {
            FileResource resource = (FileResource) iter.next();
            File source = resource.getFile();
            File destination = new File(javaDirectory, source.getName());
            copy(source, destination);
        }
    }
}
Example 88
Project: processing-master  File: AppBundlerTask.java View source code
private void copyClassPathRefEntries(File javaDirectory) throws IOException {
    if (classPathRef != null) {
        org.apache.tools.ant.types.Path classpath = (org.apache.tools.ant.types.Path) classPathRef.getReferencedObject(getProject());
        Iterator<?> iter = classpath.iterator();
        while (iter.hasNext()) {
            FileResource resource = (FileResource) iter.next();
            File source = resource.getFile();
            File destination = new File(javaDirectory, source.getName());
            copy(source, destination);
        }
    }
}
Example 89
Project: SetupBuilder-master  File: AppBundlerTask.java View source code
private void copyClassPathRefEntries(File javaDirectory) throws IOException {
    if (classPathRef != null) {
        org.apache.tools.ant.types.Path classpath = (org.apache.tools.ant.types.Path) classPathRef.getReferencedObject(getProject());
        Iterator<FileResource> iter = (Iterator<FileResource>) (Object) classpath.iterator();
        while (iter.hasNext()) {
            FileResource resource = iter.next();
            File source = resource.getFile();
            File destination = new File(javaDirectory, source.getName());
            copy(source, destination);
        }
    }
}
Example 90
Project: Wiring-master  File: AppBundlerTask.java View source code
private void copyClassPathRefEntries(File javaDirectory) throws IOException {
    if (classPathRef != null) {
        org.apache.tools.ant.types.Path classpath = (org.apache.tools.ant.types.Path) classPathRef.getReferencedObject(getProject());
        Iterator<?> iter = classpath.iterator();
        while (iter.hasNext()) {
            FileResource resource = (FileResource) iter.next();
            File source = resource.getFile();
            File destination = new File(javaDirectory, source.getName());
            copy(source, destination);
        }
    }
}
Example 91
Project: fawkez-old-master  File: ReportNormalizerAntTask.java View source code
/**
    * Create a Java command line for executing the ReportNormalizer.
    *
    * @param suite The suite to run
    * @return The Java command line.
    */
private CommandlineJava createCommandline() {
    final CommandlineJava cmd;
    try {
        cmd = (CommandlineJava) mCommandline.clone();
    } catch (CloneNotSupportedException unexpected) {
        throw new RuntimeException("Ups, CommandLineJava doesn't support the method clone()", unexpected);
    }
    cmd.setClassname(ReportNormalizer.class.getName());
    // WOW      cmd.createVmArgument().setValue("-Xmx1500m");
    cmd.createArgument().setValue("-out");
    cmd.createArgument().setFile(mOut);
    cmd.createArgument().setValue("-projectName");
    cmd.createArgument().setValue(mName);
    cmd.createArgument().setValue("-level");
    cmd.createArgument().setValue(mLevel.toString());
    cmd.createArgument().setValue("-loglevel");
    if (mDebug) {
        cmd.createArgument().setValue("ALL");
    } else {
        cmd.createArgument().setValue("INFO");
    }
    if (mFilter != null) {
        cmd.createArgument().setValue("-filter");
        cmd.createArgument().setFile(mFilter);
    }
    for (final Iterator iterator = mSourceDirectories.iterator(); iterator.hasNext(); ) {
        final SourceDirectory sourceDir = (SourceDirectory) iterator.next();
        cmd.createArgument().setValue("-srcDir");
        cmd.createArgument().setPath(new Path(getProject(), sourceDir.getDir()));
    }
    for (final Iterator iterator = mReportFiles.iterator(); iterator.hasNext(); ) {
        final Report reportFile = (Report) iterator.next();
        if (reportFile.testIfCondition()) {
            cmd.createArgument().setValue("-" + reportFile.getFormat());
            cmd.createArgument().setFile(reportFile.getFile());
        }
    }
    return cmd;
}
Example 92
Project: flex-falcon-master  File: FlexTask.java View source code
private Class<?> resolveClass(String className) {
    Class<?> result = null;
    try {
        result = Class.forName(className, true, Thread.currentThread().getContextClassLoader());
    } catch (ClassNotFoundException ignoredClassNotFoundException) {
        String flexHomeProperty = getProject().getProperty("FALCON_HOME");
        if (flexHomeProperty != null) {
            File flexHome = new File(flexHomeProperty);
            if (flexHome.exists()) {
                File jarFile = new File(flexHome + "/lib", toolJARFileName);
                if (jarFile.exists()) {
                    try {
                        URL url = jarFile.toURI().toURL();
                        URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url });
                        result = Class.forName(className, true, urlClassLoader);
                        originalContextClassLoader = Thread.currentThread().getContextClassLoader();
                        Thread.currentThread().setContextClassLoader(urlClassLoader);
                        if (fork)
                            super.setClasspath(new Path(getProject(), jarFile.getAbsolutePath()));
                    } catch (MalformedURLException malformedURLException) {
                        malformedURLException.printStackTrace();
                    } catch (ClassNotFoundException classNotFoundException) {
                        throw new BuildException("The class " + className + " was not found in jar file " + toolJARFileName, getLocation());
                    }
                } else {
                    throw new BuildException("File does not exist: " + toolJARFileName, getLocation());
                }
            } else {
                throw new BuildException("FALCON_HOME does not exist.", getLocation());
            }
        } else {
            throw new BuildException("The class, " + className + ", must be in the classpath or the FALCON_HOME property must be set.", getLocation());
        }
    }
    return result;
}
Example 93
Project: hive-master  File: CompileProcessor.java View source code
@VisibleForTesting
CommandProcessorResponse compile(SessionState ss) throws CompileProcessorException {
    Project proj = new Project();
    String ioTempDir = System.getProperty(IO_TMP_DIR);
    File ioTempFile = new File(ioTempDir);
    if (!ioTempFile.exists()) {
        throw new CompileProcessorException(ioTempDir + " does not exists");
    }
    if (!ioTempFile.isDirectory() || !ioTempFile.canWrite()) {
        throw new CompileProcessorException(ioTempDir + " is not a writable directory");
    }
    Groovyc g = new Groovyc();
    long runStamp = System.currentTimeMillis();
    String jarId = myId + "_" + runStamp;
    g.setProject(proj);
    Path sourcePath = new Path(proj);
    File destination = new File(ioTempFile, jarId + "out");
    g.setDestdir(destination);
    File input = new File(ioTempFile, jarId + "in");
    sourcePath.setLocation(input);
    g.setSrcdir(sourcePath);
    input.mkdir();
    File fileToWrite = new File(input, this.named);
    try {
        Files.write(this.code, fileToWrite, Charset.forName("UTF-8"));
    } catch (IOException e1) {
        throw new CompileProcessorException("writing file", e1);
    }
    destination.mkdir();
    try {
        g.execute();
    } catch (BuildException ex) {
        throw new CompileProcessorException("Problem compiling", ex);
    }
    File testArchive = new File(ioTempFile, jarId + ".jar");
    JarArchiveOutputStream out = null;
    try {
        out = new JarArchiveOutputStream(new FileOutputStream(testArchive));
        for (File f : destination.listFiles()) {
            JarArchiveEntry jentry = new JarArchiveEntry(f.getName());
            FileInputStream fis = new FileInputStream(f);
            out.putArchiveEntry(jentry);
            IOUtils.copy(fis, out);
            fis.close();
            out.closeArchiveEntry();
        }
        out.finish();
    } catch (IOException e) {
        throw new CompileProcessorException("Exception while writing jar", e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException WhatCanYouDo) {
            }
        }
    }
    if (ss != null) {
        ss.add_resource(ResourceType.JAR, testArchive.getAbsolutePath());
    }
    CommandProcessorResponse good = new CommandProcessorResponse(0, testArchive.getAbsolutePath(), null);
    return good;
}
Example 94
Project: maven-plugin-tools-master  File: AntMojoWrapper.java View source code
private void addClasspathReferences() throws MojoExecutionException {
    try {
        if (mavenProject != null && session != null && pathTranslator != null) {
            ExpressionEvaluator exprEvaluator = new PluginParameterExpressionEvaluator(session, mojoExecution, pathTranslator, logger, mavenProject, mavenProject.getProperties());
            PropertyHelper propertyHelper = PropertyHelper.getPropertyHelper(antProject);
            propertyHelper.setNext(new AntPropertyHelper(exprEvaluator, mavenProject.getArtifacts(), getLog()));
        } else {
            unconstructedParts.add("Maven parameter expression evaluator for Ant properties.");
        }
        @SuppressWarnings("unchecked") Map<String, Object> references = scriptInvoker.getReferences();
        if (mavenProject != null) {
            // Compile classpath
            Path p = new Path(antProject);
            p.setPath(StringUtils.join(mavenProject.getCompileClasspathElements().iterator(), File.pathSeparator));
            /* maven.dependency.classpath it's deprecated as it's equal to maven.compile.classpath */
            references.put("maven.dependency.classpath", p);
            antProject.addReference("maven.dependency.classpath", p);
            references.put("maven.compile.classpath", p);
            antProject.addReference("maven.compile.classpath", p);
            // Runtime classpath
            p = new Path(antProject);
            p.setPath(StringUtils.join(mavenProject.getRuntimeClasspathElements().iterator(), File.pathSeparator));
            references.put("maven.runtime.classpath", p);
            antProject.addReference("maven.runtime.classpath", p);
            // Test classpath
            p = new Path(antProject);
            p.setPath(StringUtils.join(mavenProject.getTestClasspathElements().iterator(), File.pathSeparator));
            references.put("maven.test.classpath", p);
            antProject.addReference("maven.test.classpath", p);
        } else {
            unconstructedParts.add("Maven standard project-based classpath references.");
        }
        if (mojoExecution != null) {
            // Plugin dependency classpath
            Path p = getPathFromArtifacts(mojoExecution.getMojoDescriptor().getPluginDescriptor().getArtifacts(), antProject);
            references.put("maven.plugin.classpath", p);
            antProject.addReference("maven.plugin.classpath", p);
        } else {
            unconstructedParts.add("Maven standard plugin-based classpath references.");
        }
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException("Error creating classpath references for Ant-based plugin scripts.", e);
    }
}
Example 95
Project: parallel-junit-master  File: ParallelJUnitTask.java View source code
@Override
public void init() throws BuildException {
    super.init();
    final Path remoteTestRunnerClasses = commandLine.createClasspath(getProject()).createPath();
    remoteTestRunnerClasses.setLocation(getClassSource(RemoteTestRunner.class));
    remoteTestRunnerClasses.setLocation(getClassSource(JUnitTest.class));
    remoteTestRunnerClasses.setLocation(getClassSource(AntMain.class));
    remoteTestRunnerClasses.setLocation(getClassSource(Task.class));
    final File antJunit4Lib = LoaderUtils.getResourceSource(getClass().getClassLoader(), "org/apache/tools/ant/taskdefs/optional/junit/JUnit4TestMethodAdapter.class");
    if (antJunit4Lib != null) {
        remoteTestRunnerClasses.setLocation(antJunit4Lib);
    }
}
Example 96
Project: tomcat60-master  File: AntCompiler.java View source code
// --------------------------------------------------------- Public Methods
/** 
     * Compile the servlet from .java file to .class file
     */
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {
    long t1 = 0;
    if (log.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }
    String javaEncoding = ctxt.getOptions().getJavaEncoding();
    String javaFileName = ctxt.getServletJavaFileName();
    String classpath = ctxt.getClassPath();
    String sep = System.getProperty("path.separator");
    StringBuffer errorReport = new StringBuffer();
    StringBuffer info = new StringBuffer();
    info.append("Compile: javaFileName=" + javaFileName + "\n");
    info.append("    classpath=" + classpath + "\n");
    // Start capturing the System.err output for this thread
    SystemLogHandler.setThread();
    // Initializing javac task
    getProject();
    Javac javac = (Javac) project.createTask("javac");
    // Initializing classpath
    Path path = new Path(project);
    path.setPath(System.getProperty("java.class.path"));
    info.append("    cp=" + System.getProperty("java.class.path") + "\n");
    StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
    while (tokenizer.hasMoreElements()) {
        String pathElement = tokenizer.nextToken();
        File repository = new File(pathElement);
        path.setLocation(repository);
        info.append("    cp=" + repository + "\n");
    }
    if (log.isDebugEnabled())
        log.debug("Using classpath: " + System.getProperty("java.class.path") + sep + classpath);
    // Initializing sourcepath
    Path srcPath = new Path(project);
    srcPath.setLocation(options.getScratchDir());
    info.append("    work dir=" + options.getScratchDir() + "\n");
    // Initialize and set java extensions
    String exts = System.getProperty("java.ext.dirs");
    if (exts != null) {
        Path extdirs = new Path(project);
        extdirs.setPath(exts);
        javac.setExtdirs(extdirs);
        info.append("    extension dir=" + exts + "\n");
    }
    // See Bugzilla 31257
    if (ctxt.getOptions().getFork()) {
        String endorsed = System.getProperty("java.endorsed.dirs");
        if (endorsed != null) {
            Javac.ImplementationSpecificArgument endorsedArg = javac.createCompilerArg();
            endorsedArg.setLine("-J-Djava.endorsed.dirs=" + quotePathList(endorsed));
            info.append("    endorsed dir=" + quotePathList(endorsed) + "\n");
        } else {
            info.append("    no endorsed dirs specified\n");
        }
    }
    // Configure the compiler object
    javac.setEncoding(javaEncoding);
    javac.setClasspath(path);
    javac.setDebug(ctxt.getOptions().getClassDebugInfo());
    javac.setSrcdir(srcPath);
    javac.setTempdir(options.getScratchDir());
    javac.setOptimize(!ctxt.getOptions().getClassDebugInfo());
    javac.setFork(ctxt.getOptions().getFork());
    info.append("    srcDir=" + srcPath + "\n");
    // Set the Java compiler to use
    if (options.getCompiler() != null) {
        javac.setCompiler(options.getCompiler());
        info.append("    compiler=" + options.getCompiler() + "\n");
    }
    if (options.getCompilerTargetVM() != null) {
        javac.setTarget(options.getCompilerTargetVM());
        info.append("   compilerTargetVM=" + options.getCompilerTargetVM() + "\n");
    }
    if (options.getCompilerSourceVM() != null) {
        javac.setSource(options.getCompilerSourceVM());
        info.append("   compilerSourceVM=" + options.getCompilerSourceVM() + "\n");
    }
    // Build includes path
    PatternSet.NameEntry includes = javac.createInclude();
    includes.setName(ctxt.getJavaPath());
    info.append("    include=" + ctxt.getJavaPath() + "\n");
    BuildException be = null;
    try {
        if (ctxt.getOptions().getFork()) {
            javac.execute();
        } else {
            synchronized (javacLock) {
                javac.execute();
            }
        }
    } catch (BuildException e) {
        be = e;
        log.error(Localizer.getMessage("jsp.error.javac"), e);
        log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
    }
    errorReport.append(logger.getReport());
    // Stop capturing the System.err output for this thread
    String errorCapture = SystemLogHandler.unsetThread();
    if (errorCapture != null) {
        errorReport.append(System.getProperty("line.separator"));
        errorReport.append(errorCapture);
    }
    if (!ctxt.keepGenerated()) {
        File javaFile = new File(javaFileName);
        javaFile.delete();
    }
    if (be != null) {
        String errorReportString = errorReport.toString();
        log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString));
        JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(errorReportString, javaFileName, pageNodes);
        if (javacErrors != null) {
            errDispatcher.javacError(javacErrors);
        } else {
            errDispatcher.javacError(errorReportString, be);
        }
    }
    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }
    logger = null;
    project = null;
    if (ctxt.isPrototypeMode()) {
        return;
    }
    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smap);
    }
}
Example 97
Project: visage-compiler-master  File: VisageRunAndCompareWrapper.java View source code
private void execute(String outputFileName, String errorFileName, String expectedFileName) throws IOException {
    CommandlineJava commandLine = new CommandlineJava();
    String mainClass = className.substring(0, className.length() - ".visage".length());
    if (xpackage.length() > 0) {
        mainClass = xpackage + "." + mainClass;
    }
    commandLine.setClassname(VISAGE_MAIN);
    Project project = new Project();
    Path p = commandLine.createClasspath(project);
    p.createPathElement().setPath(System.getProperty("java.class.path"));
    p.createPathElement().setPath(buildDir.getPath());
    // for possible .visageproperties files in the test source directory
    p.createPathElement().setPath(testFile.getParent());
    commandLine.createArgument().setValue(mainClass);
    if (param != null)
        commandLine.createArgument().setLine(param);
    // set locale to en_US (required to make test-output reproduceable)
    commandLine.createVmArgument().setValue("-Duser.language=en");
    commandLine.createVmArgument().setValue("-Duser.country=US");
    commandLine.createVmArgument().setValue("-Djava.io.tmpdir=" + System.getProperty("java.io.tmpdir"));
    PumpStreamHandler sh = new PumpStreamHandler(new FileOutputStream(outputFileName), new FileOutputStream(errorFileName));
    Execute exe = new Execute(sh);
    String[] strings = commandLine.getCommandline();
    exe.setCommandline(strings);
    try {
        exe.execute();
        File errorFileHandle = new File(errorFileName);
        if (errorFileHandle.length() > 0) {
            if (expectRunFailure)
                return;
            if (!ignoreStdError && !checkForMacOSJavaBug(errorFileHandle)) {
                TestHelper.dumpFile(new FileInputStream(outputFileName), "Test Output", testFile.toString());
                TestHelper.dumpFile(new FileInputStream(errorFileName), "Test Error", testFile.toString());
                System.out.println("--");
                fail("Output written to standard error");
            }
        }
        if (compare)
            compare(outputFileName, expectedFileName, false);
    } catch (IOException e) {
        if (!expectRunFailure)
            fail("Failure running test " + testFile + ": " + e.getMessage());
    }
}
Example 98
Project: bnd-master  File: BndTask.java View source code
@SuppressWarnings("cast")
private void executeBackwardCompatible() throws BuildException {
    try {
        if (files == null)
            throw new BuildException("No files set");
        if (eclipse) {
            File project = getProject().getBaseDir();
            EclipseClasspath cp = new EclipseClasspath(this, project.getParentFile(), project);
            classpath.addAll(cp.getClasspath());
            classpath.addAll(cp.getBootclasspath());
            sourcepath.addAll(cp.getSourcepath());
            // classpath.add(cp.getOutput());
            if (report())
                throw new BuildException("Errors during Eclipse Path inspection");
        }
        if (output == null)
            output = getProject().getBaseDir();
        for (Iterator<File> f = files.iterator(); f.hasNext(); ) {
            File file = f.next();
            Builder builder = new Builder();
            builder.setPedantic(isPedantic());
            if (file.exists()) {
                // Do nice property calculations
                // merging includes etc.
                builder.setProperties(file);
            }
            // properties, if the inherit flag is specified
            if (inherit) {
                Properties projectProperties = new UTF8Properties();
                @SuppressWarnings("unchecked") Hashtable<Object, Object> antProps = getProject().getProperties();
                projectProperties.putAll(antProps);
                projectProperties.putAll(builder.getProperties());
                builder.setProperties(projectProperties);
            }
            builder.setClasspath(toFiles(classpath, "classpath"));
            builder.setSourcepath(toFiles(sourcepath, "sourcepath"));
            Jar jars[] = builder.builds();
            // Report both task failures and bnd build failures.
            boolean taskFailed = report();
            boolean bndFailed = report(builder);
            // failed or the bnd build failed.
            if (!failok && (taskFailed || bndFailed)) {
                throw new BuildException("bnd failed", new org.apache.tools.ant.Location(file.getAbsolutePath()));
            }
            for (int i = 0; i < jars.length; i++) {
                Jar jar = jars[i];
                String bsn = jar.getName();
                File base = file.getParentFile();
                File output = this.output;
                String path = builder.getProperty("-output");
                if (output == null) {
                    if (path == null)
                        output = getFile(base, bsn + ".jar");
                    else {
                        output = getFile(base, path);
                    }
                } else if (output.isDirectory()) {
                    if (path == null)
                        output = getFile(this.output, bsn + ".jar");
                    else
                        output = getFile(this.output, path);
                } else if (output.isFile()) {
                    if (files.size() > 1)
                        messages.GotFileNeedDir_(output.getAbsoluteFile());
                }
                String msg = "";
                if (!output.exists() || output.lastModified() <= jar.lastModified()) {
                    jar.write(output);
                } else {
                    msg = "(not modified)";
                }
                logger.debug("{} ({}) {} {}", jar.getName(), output.getName(), jar.getResources().size(), msg);
                report();
                jar.close();
            }
            builder.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (!failok)
            throw new BuildException("Failed to build jar file: ", e);
    }
}
Example 99
Project: BoxMeBackend-master  File: OneJarTask.java View source code
public void addConfiguredClasspath(final Path classpath) {
    log("adding classpath: " + classpath, Project.MSG_VERBOSE);
    final Iterator pathIter = classpath.iterator();
    while (pathIter.hasNext()) {
        final Resource res = (Resource) pathIter.next();
        if (res instanceof FileResource) {
            final FileResource fres = (FileResource) res;
            log("res.name: " + fres.getName() + " res.exists: " + fres.isExists() + " res.class: " + fres.getClass().getName() + " res.file: " + fres.getFile(), Project.MSG_DEBUG);
            final File dir = fres.getFile().getParentFile();
            final String name = fres.getFile().getName();
            final ZipFileSet fileset = new ZipFileSet();
            fileset.setProject(getProject());
            fileset.setDir(dir);
            fileset.createInclude().setName(name);
            filesets.add(fileset);
        } else {
            throw new BuildException("Not a file resource: " + res);
        }
    }
}
Example 100
Project: checkstyle-master  File: CheckstyleAntTaskTest.java View source code
@Test
public final void testPathsOneFile() throws IOException {
    // given
    TestRootModuleChecker.reset();
    final CheckstyleAntTask antTask = getCheckstyleAntTask(CUSTOM_ROOT_CONFIG_FILE);
    final FileSet examinationFileSet = new FileSet();
    examinationFileSet.setFile(new File(getPath(FLAWLESS_INPUT)));
    final Path sourcePath = new Path(antTask.getProject());
    sourcePath.addFileset(examinationFileSet);
    antTask.addPath(sourcePath);
    // when
    antTask.execute();
    // then
    assertTrue(TestRootModuleChecker.isProcessed());
    final List<File> filesToCheck = TestRootModuleChecker.getFilesToCheck();
    assertThat(filesToCheck.size(), is(1));
    assertThat(filesToCheck.get(0).getAbsolutePath(), is(getPath(FLAWLESS_INPUT)));
}
Example 101
Project: ci.ant-master  File: CompileJSPs.java View source code
private void createAppXML(File serverDir) throws FileNotFoundException {
    if (srcdir != null) {
        // TODO write the loose application xml.
        File appsDir = new File(serverDir, "apps");
        appsDir.mkdirs();
        PrintStream ps = new PrintStream(new File(appsDir, "fake.war.xml"));
        ps.println("<archive>");
        ps.println("  <dir targetInArchive=\"/\" sourceOnDisk=\"" + srcdir.getAbsolutePath() + "\"/>");
        Path p = new Path(getProject(), classpath);
        if (classpathRef != null) {
            Path path = (Path) getProject().getReference(classpathRef);
            p.add(path);
        }
        String[] cp = p.toString().split(File.pathSeparator);
        for (String entry : cp) {
            File f = new File(entry);
            String basename = f.getName();
            if (f.isFile() && f.exists() && f.getName().endsWith(".jar")) {
                ps.println("  <file targetInArchive=\"/WEB-INF/lib/" + basename + "\" sourceOnDisk=\"" + f.getAbsolutePath() + "\"/>");
            } else if (f.isDirectory() && f.exists()) {
                // TODO: What if basename is NOT "classes"?
                ps.println("  <dir targetInArchive=\"/WEB-INF/classes\" sourceOnDisk=\"" + f.getAbsolutePath() + "\"/>");
            }
        }
        ps.println("</archive>");
        ps.close();
    }
}