org.apache.tools.ant.util.FileUtils Java Examples

The following examples show how to use org.apache.tools.ant.util.FileUtils. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JarExpander.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
/**
 * 解压缩jar包
 *
 */
public void expand()
    throws IOException
{
    File[] fs = jarsDir.listFiles(new JarFilter());
    if (fs == null)
    {
       return; 
    }
    
    for (File f : fs)
    {
        LOG.info("start to unzip jar {}", f.getName());
        unzipJar(f.getCanonicalPath());
        FileUtils.delete(f);
    }

    LOG.info("finished to unzip jar to dir");
}
 
Example #2
Source File: ResourcePackageTask.java    From development with Apache License 2.0 6 votes vote down vote up
private IFileSet createFileSet() throws IOException {
    final BaseContainer rootcontainer = new BaseContainer();
    final IContainer container = Files.autozip(rootcontainer);
    // We just use the Properties.load() method as a parser. As we
    // will allow duplicate keys we have to hook into the put() method.
    final Properties parser = new Properties() {
        private static final long serialVersionUID = 1L;

        @Override
        public synchronized Object put(Object key, Object value) {
            String outputpath = replaceProperties((String) key);
            String sourcepath = replaceProperties((String) value);
            addFiles(container, outputpath, sourcepath);
            return null;
        }
    };
    final InputStream in = new FileInputStream(packagefile);
    try {
        parser.load(in);
    } finally {
        FileUtils.close(in);
    }
    return rootcontainer;
}
 
Example #3
Source File: ModuleListParser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static Map<String,Entry> scanSuiteSources(Map<String,Object> properties, Project project) throws IOException {
    File basedir = new File((String) properties.get("basedir"));
    String suiteDir = (String) properties.get("suite.dir");
    if (suiteDir == null) {
        throw new IOException("No definition of suite.dir in " + basedir);
    }
    File suite = FileUtils.getFileUtils().resolveFile(basedir, suiteDir);
    if (!suite.isDirectory()) {
        throw new IOException("No such suite " + suite);
    }
    Map<String,Entry> entries = SUITE_SCAN_CACHE.get(suite);
    if (entries == null) {
        if (project != null) {
            project.log("Scanning for modules in suite " + suite);
        }
        entries = new HashMap<>();
        doScanSuite(entries, suite, properties, project);
        if (project != null) {
            project.log("Found modules: " + entries.keySet(), Project.MSG_VERBOSE);
        }
        SUITE_SCAN_CACHE.put(suite, entries);
    }
    return entries;
}
 
Example #4
Source File: ShorterPaths.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Copies source file to target location only if it is missing there.
 * @param file source file
 * @param copy target file
 * @return true if file was successfully copied, false if source is the same
 * as target
 * @throws IOException if target file exists and it is not the same as 
 * source file
 */
private boolean copyMissing(File file, File copy) throws IOException {
    if (FileUtils.getFileUtils().contentEquals(file, copy)) {
        return false;
    } else if (copy.isFile()) {
        // Could try to copy to a different name, but this is probably something that should be fixed anyway:
        throw new IOException(file + " is not the same as " + copy + "; will not overwrite");
    }
    log("Copying " + file + " to extralibs despite " + replacements);
    FileUtils.getFileUtils().copyFile(file, copy);
    return true;
}
 
Example #5
Source File: TagListTask.java    From ant-git-tasks with Apache License 2.0 5 votes vote down vote up
/**
 * Processes a list of references, check references names and output to a file if requested.
 *
 * @param refList The list of references to process
 */
protected void processReferencesAndOutput(List<Ref> refList) {
        List<String> refNames = new ArrayList<String>(refList.size());

        for (Ref ref : refList) {
                refNames.add(GitTaskUtils.sanitizeRefName(ref.getName()));
        }

        if (!namesToCheck.isEmpty()) {
                if (!refNames.containsAll(namesToCheck)) {
                        List<String> namesCopy = new ArrayList<String>(namesToCheck);
                        namesCopy.removeAll(refNames);

                        throw new GitBuildException(String.format(MISSING_REFS_TEMPLATE, namesCopy.toString()));
                }
        }

        if (!GitTaskUtils.isNullOrBlankString(outputFilename)) {
                FileUtils fileUtils = FileUtils.getFileUtils();

                Echo echo = new Echo();
                echo.setProject(getProject());
                echo.setFile(fileUtils.resolveFile(getProject().getBaseDir(), outputFilename));

                for (int i = 0; i < refNames.size(); i++) {
                        String refName = refNames.get(i);
                        echo.addText(String.format(REF_NAME_TEMPLATE, refName));
                }

                echo.perform();
        }
}
 
Example #6
Source File: Groovy.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void createNewArgs(String txt) throws IOException {
    final String[] args = cmdline.getCommandline();
    // Temporary file - delete on exit, create (assured unique name).
    final File tempFile = FileUtils.getFileUtils().createTempFile(PREFIX, SUFFIX, null, true, true);
    final String[] commandline = new String[args.length + 1];
    ResourceGroovyMethods.write(tempFile, txt);
    commandline[0] = tempFile.getCanonicalPath();
    System.arraycopy(args, 0, commandline, 1, args.length);
    super.clearArgs();
    for (String arg : commandline) {
        final Commandline.Argument argument = super.createArg();
        argument.setValue(arg);
    }
}
 
Example #7
Source File: AndroidUpdateTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void copy(String source, String dest) throws IOException {
    if (source==null) {
        return;
    }
    String ext = source.substring(source.indexOf(".")); // NOI18N
    final String prjPath = getProject().getBaseDir().getPath();
    FileUtils.getFileUtils().copyFile(
            prjPath + "/" + getProperty("site.root") + "/" + source, 
            prjPath + "/" + getProject().getProperty("cordova.platforms") + "/android/res/" + dest + ext);
}
 
Example #8
Source File: IOSUpdateTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void copy(String source, String dest) throws IOException {
    if (source==null) {
        return;
    }
    String name = getProject().getProperty("xcode.project.name");
    final int i = source.indexOf("."); // NOI18N
    String ext = i<0?"":source.substring(i);
    final String prjPath = getProject().getBaseDir().getPath();
    FileUtils.getFileUtils().copyFile(
            prjPath + "/" + getProperty("site.root") + "/" + source, 
            prjPath + "/" + getProject().getProperty("cordova.platforms") + "/ios/" + name + "/Resources/" + dest + ext);
}
 
Example #9
Source File: MakeJNLP.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String safeRelativePath(File from, File to) {
    try {
        return FileUtils.getRelativePath(from, to);
    } catch (Exception ex) {
        return to.getAbsolutePath();
    }
}
 
Example #10
Source File: JNLPUpdateManifestBranding.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String safeRelativePath(File from, File to) {
    try {
        return FileUtils.getRelativePath(from, to);
    } catch (Exception ex) {
        return to.getAbsolutePath();
    }
}
 
Example #11
Source File: JNLPUpdateManifestStartup.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String safeRelativePath(File from, File to) {
    try {
        return FileUtils.getRelativePath(from, to);
    } catch (Exception ex) {
        return to.getAbsolutePath();
    }
}
 
Example #12
Source File: SignJarsTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String safeRelativePath(File from, File to) {
    try {
        return FileUtils.getRelativePath(from, to);
    } catch (Exception ex) {
        return to.getAbsolutePath();
    }
}
 
Example #13
Source File: FileExistPredicatorTest.java    From griffin with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void deleteFile() {
    File file = new File(rootPath + fileName);
    if (file.exists()) {
        FileUtils.delete(file);
    }
}
 
Example #14
Source File: S3UploadClient.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void upload(String source, String target) throws Exception {
  String bucket = this.s3OutputConfig.getBucketConfig().getBucket();
  File fileToUpload = new File(source);
  logger.info("Starting S3 upload {} -> bucket: {}, key: {}", source, bucket, target);
  s3Client.putObject(bucket, target, new File(source));
  s3Client.setObjectAcl(bucket, target, acl);
  FileUtils.delete(fileToUpload);
}
 
Example #15
Source File: OneLinerFormatter.java    From pxf with Apache License 2.0 5 votes vote down vote up
@Override
public void endTestSuite(JUnitTest suite) throws BuildException {
	StringBuffer sb = new StringBuffer("Tests run: ");
	sb.append(suite.runCount());
	sb.append(", Failures: ");
	sb.append(suite.failureCount());
	sb.append(", Errors: ");
	sb.append(suite.errorCount());
	sb.append(", Time elapsed: ");
	sb.append(numberFormat.format(suite.getRunTime() / 1000.0));
	sb.append(" sec");
	sb.append(" (" + numberFormat.format(suite.getRunTime() / 1000.0 / 60));
	sb.append(" min)");
	sb.append(StringUtils.LINE_SEP);
	sb.append(StringUtils.LINE_SEP);

	if (output != null) {
		try {
			output.write(sb.toString());
			resultWriter.close();
			output.write(results.toString());
			output.flush();
		} finally {
			if (out != System.out && out != System.err) {
				FileUtils.close(out);
			}
		}
	}
}
 
Example #16
Source File: ResolveList.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private void seekHarderExecute() {
    StringBuilder value = new StringBuilder();
    Path full = new Path(getProject());
    String prefix = "";
    for (String property: properties) {
        String[] props;
        if (mapper != null) {
            props = mapper.getImplementation().mapFileName(property);
        } else {
            props = new String[] { property };
        }
        final FileUtils fileUtils = FileUtils.getFileUtils();

        String clusterDir = getProject().getProperty(property + ".dir");
        if (clusterDir == null) {
            throw new BuildException(property + ".dir is not defined");
        }
        File cluster = fileUtils.resolveFile(dir, clusterDir);

        for (String p : props) {
            String pval = getProject().getProperty(p);
            if (pval == null) {
                if (ignoreMissing) {
                    continue;
                } else {
                    throw new BuildException("Missing definition for " + p);
                }
                
            }
            String[] pValues = pval.split(",");

            for (String oneValue : pValues) {
                if (modules != null && !modules.contains(oneValue)) {
                    continue;
                }
                File oneFile = fileUtils.resolveFile(dir, oneValue);
                if (!nbProjectExists(oneFile)) {
                    File sndFile = fileUtils.resolveFile(cluster, oneValue);
                    if (!nbProjectExists(sndFile)) {
                        throw new BuildException("Cannot resolve " + oneValue + ". Neither one exist:\n  " + oneFile + "\n  " + sndFile);
                    }
                    oneValue = clusterDir + "/" + oneValue;
                    oneFile = sndFile;
                }

                if (oneValue != null && oneValue.length() > 0) {
                    value.append(prefix).append(oneValue);
                    full.createPathElement().setLocation(oneFile);
                    prefix = ",";
                }
            }
        }
    }

    getProject().setNewProperty(name, value.toString());
    getProject().setNewProperty(path, full.toString());
}
 
Example #17
Source File: JPDAReload.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws BuildException {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("JPDAReload.execute(), filesets = "+filesets);
    }
    if (filesets.size() == 0) {
        throw new BuildException ("A nested fileset with class to refresh in VM must be specified.");
    }
    
    // check debugger state
    DebuggerEngine debuggerEngine = DebuggerManager.getDebuggerManager ().
        getCurrentEngine ();
    if (debuggerEngine == null) {
        throw new BuildException ("No debugging sessions was found.");
    }
    JPDADebugger debugger = debuggerEngine.lookupFirst(null, JPDADebugger.class);
    if (debugger == null) {
        throw new BuildException("Current debugger is not JPDA one.");
    }
    if (!debugger.canFixClasses ()) {
        throw new BuildException("The debugger does not support Fix action.");
    }
    if (debugger.getState () == JPDADebugger.STATE_DISCONNECTED) {
        throw new BuildException ("The debugger is not running");
    }
    
    System.out.println ("Classes to be reloaded:");
    
    FileUtils fileUtils = FileUtils.getFileUtils();
    Map map = new HashMap ();
    EditorContext editorContext = DebuggerManager.getDebuggerManager().lookupFirst(null, EditorContext.class);

    Iterator it = filesets.iterator ();
    while (it.hasNext ()) {
        FileSet fs = (FileSet) it.next ();
        DirectoryScanner ds = fs.getDirectoryScanner (getProject ());
        String fileNames[] = ds.getIncludedFiles ();
        File baseDir = fs.getDir (getProject ());
        int i, k = fileNames.length;
        for (i = 0; i < k; i++) {
            File f = fileUtils.resolveFile (baseDir, fileNames [i]);
            if (f != null) {
                FileObject fo = FileUtil.toFileObject(f);
                if (fo != null) {
                    try {
                        String url = classToSourceURL (fo);
                        if (url != null)
                            editorContext.updateTimeStamp (debugger, url);
                        InputStream is = fo.getInputStream ();
                        long fileSize = fo.getSize ();
                        byte[] bytecode = new byte [(int) fileSize];
                        is.read (bytecode);
                        // remove ".class" from and use dots for for separator
                        String className = fileNames [i].substring (
                                0, 
                                fileNames [i].length () - 6
                            ).replace (File.separatorChar, '.');
                        map.put (
                            className, 
                            bytecode
                        );
                        System.out.println (" " + className);
                    } catch (IOException ex) {
                        ex.printStackTrace ();
                    }
                }
            }
        }
    }
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("Reloaded classes: "+map.keySet());
    }
    if (map.size () == 0) {
        System.out.println (" No class to reload");
        return;
    }
    String error = null;
    try {
        debugger.fixClasses (map);
    } catch (UnsupportedOperationException uoex) {
        error = "The virtual machine does not support this operation: "+uoex.getLocalizedMessage();
    } catch (NoClassDefFoundError ncdfex) {
        error = "The bytes don't correspond to the class type (the names don't match): "+ncdfex.getLocalizedMessage();
    } catch (VerifyError ver) {
        error = "A \"verifier\" detects that a class, though well formed, contains an internal inconsistency or security problem: "+ver.getLocalizedMessage();
    } catch (UnsupportedClassVersionError ucver) {
        error = "The major and minor version numbers in bytes are not supported by the VM. "+ucver.getLocalizedMessage();
    } catch (ClassFormatError cfer) {
        error = "The bytes do not represent a valid class. "+cfer.getLocalizedMessage();
    } catch (ClassCircularityError ccer) {
        error = "A circularity has been detected while initializing a class: "+ccer.getLocalizedMessage();
    } catch (VMOutOfMemoryException oomex) {
        error = "Out of memory in the target VM has occurred during class reload.";
    }
    if (error != null) {
        getProject().log(error, Project.MSG_ERR);
        throw new BuildException(error);
    }
}
 
Example #18
Source File: SourceContextPluginIntegrationTest.java    From app-gradle-plugin with Apache License 2.0 4 votes vote down vote up
/** Create a test project with git source context. */
public void setUpTestProject() throws IOException {
  Path buildFile = testProjectDir.getRoot().toPath().resolve("build.gradle");

  Files.createDirectory(testProjectDir.getRoot().toPath().resolve("src"));
  InputStream buildFileContent =
      getClass()
          .getClassLoader()
          .getResourceAsStream("projects/sourcecontext-project/build.gradle");
  Files.copy(buildFileContent, buildFile);

  Path gitContext = testProjectDir.getRoot().toPath().resolve("gitContext.zip");
  InputStream gitContextContent =
      getClass()
          .getClassLoader()
          .getResourceAsStream("projects/sourcecontext-project/gitContext.zip");
  Files.copy(gitContextContent, gitContext);

  try (ZipFile zipFile = new ZipFile(gitContext.toFile())) {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
      ZipEntry entry = entries.nextElement();
      File entryDestination = new File(testProjectDir.getRoot(), entry.getName());
      if (entry.isDirectory()) {
        entryDestination.mkdirs();
      } else {
        entryDestination.getParentFile().mkdirs();
        InputStream in = zipFile.getInputStream(entry);
        OutputStream out = new FileOutputStream(entryDestination);
        IOUtils.copy(in, out);
        IOUtils.closeQuietly(in);
        out.close();
      }
    }
  }

  FileUtils.delete(gitContext.toFile());

  Path webInf = testProjectDir.getRoot().toPath().resolve("src/main/webapp/WEB-INF");
  Files.createDirectories(webInf);
  File appengineWebXml = Files.createFile(webInf.resolve("appengine-web.xml")).toFile();
  Files.write(appengineWebXml.toPath(), "<appengine-web-app/>".getBytes(Charsets.UTF_8));
}
 
Example #19
Source File: MakeHTMLTask.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void execute() {
  final Project proj = getProject();
  this.projectName = proj.getName();

  if (template == null) {
    throw new BuildException("template must be set");
  }
  if (title == null) {
    title = "";
  }
  if (description == null) {
    description = "";
  }

  if (filesets.isEmpty() && fromFile == null && toFile == null) {
    throw new BuildException("Need to specify tofile and fromfile or give a fileset");
  }

  if (filesets.isEmpty()) {
    // log("Project base is: " + getProject().getBaseDir());
    // log("Attempting to transform: " + fromFile);
    if (!FileUtils.isAbsolutePath(fromFile)) {
      fromFile = getProject().getBaseDir() + File.separator + fromFile;
    }
    transform(fromFile, toFile.toString());
  } else {
    if (fromFile != null) {
      throw new BuildException("Can not specify fromfile when using filesets");
    }
    if (toFile != null) {
      throw new BuildException("Can not specify tofile when using filesets");
    }

    for (final Object element : filesets) {
      final FileSet fs = (FileSet) element;
      final DirectoryScanner ds = fs.getDirectoryScanner(getProject());
      final String[] files = ds.getIncludedFiles();

      for (final String file : files) {
        transform(new File(fs.getDir(getProject()),
                           file).getAbsolutePath(), file);
      }
    }
  }
}
 
Example #20
Source File: JspC.java    From Tomcat8-Source-Read with MIT License 3 votes vote down vote up
/**
* Resolves the relative or absolute pathname correctly
* in both Ant and command-line situations.  If Ant launched
* us, we should use the basedir of the current project
* to resolve relative paths.
*
* See Bugzilla 35571.
*
* @param s The file
* @return The file resolved
*/
protected File resolveFile(final String s) {
    if(getProject() == null) {
        // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
        return FileUtils.getFileUtils().resolveFile(null, s);
    } else {
        return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s);
    }
}
 
Example #21
Source File: JspC.java    From Tomcat7.0.67 with Apache License 2.0 3 votes vote down vote up
/**
* Resolves the relative or absolute pathname correctly
* in both Ant and command-line situations.  If Ant launched
* us, we should use the basedir of the current project
* to resolve relative paths.
*
* See Bugzilla 35571.
*
* @param s The file
* @return The file resolved
*/
protected File resolveFile(final String s) {
    if(getProject() == null) {
        // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
        return FileUtils.getFileUtils().resolveFile(null, s);
    } else {
        return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s);
    }
}
 
Example #22
Source File: JspC.java    From tomcatsrc with Apache License 2.0 3 votes vote down vote up
/**
* Resolves the relative or absolute pathname correctly
* in both Ant and command-line situations.  If Ant launched
* us, we should use the basedir of the current project
* to resolve relative paths.
*
* See Bugzilla 35571.
*
* @param s The file
* @return The file resolved
*/
protected File resolveFile(final String s) {
    if(getProject() == null) {
        // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3
        return FileUtils.getFileUtils().resolveFile(null, s);
    } else {
        return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s);
    }
}