/** * Return an InputStream for reading the contents of this Resource. * @return an InputStream object. * @throws IOException if the tar file cannot be opened, * or the entry cannot be read. */ @Override public InputStream getInputStream() throws IOException { if (isReference()) { return getCheckedRef().getInputStream(); } Resource archive = getArchive(); final TarInputStream i = new TarInputStream(archive.getInputStream()); TarEntry te; while ((te = i.getNextEntry()) != null) { if (te.getName().equals(getName())) { return i; } } FileUtils.close(i); throw new BuildException("no entry " + getName() + " in " + getArchive()); }
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; }
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; }
private void writeFiles(IFileSet set) throws BuildException { final Set<String> filenames = new HashSet<String>(); for (final IFile f : set.getFiles()) { if (filenames.add(f.getLocalPath())) { try { OutputStream out = null; try { out = new FileOutputStream(new File(outputdir, f.getLocalPath())); f.writeTo(out); } finally { if (out != null) FileUtils.close(out); } } catch (IOException e) { throw new BuildException(e); } } } }
/** * Writes the given set of files into the output directory. * * @param set * @param outputdir */ public static void writeFiles(final IFileSet set, final File outputdir) throws IOException { final Set<String> filenames = new HashSet<String>(); for (final IFile f : set.getFiles()) { assertNoAbsolutePath(f); assertNoDuplicates(filenames, f); final File file = new File(outputdir, f.getLocalPath()); OutputStream out = null; try { out = new FileOutputStream(file); f.writeTo(out); } finally { if (out != null) FileUtils.close(out); } } }
/** * 解压缩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"); }
/** * Writes the script lines to a temp file. */ protected void writeScript() throws BuildException { FileOutputStream os = null; try { FileUtils fileUtils = FileUtils.newFileUtils(); // NB: use File.io.createTempFile whenever jdk 1.2 is allowed tmpFile = fileUtils.createTempFile("script", tmpSuffix, null); os = new java.io.FileOutputStream(tmpFile); String string = script.toString(); os.write(string.getBytes(), 0, string.length()); os.close(); } catch (Exception e) { throw new BuildException(e); } finally { try { os.close(); } catch (Throwable t) { } } }
private boolean run() { if (logFile.exists()) { if (! readLogFile()) { return false; } try { FileUtils.getFileUtils().copyFile(logFile.getAbsolutePath(), logFile.getAbsolutePath()+".bak"); } catch (IOException ex) { System.err.println("Error creating backup of log-file."); System.err.println("Cowardly refusing to overwrite old file."); return false; } } tests.addAll(newResults.data.keySet()); return writeLogFile(); }
protected void addFiles(File base, String[] files, Commandline cmdl) { FileUtils utils = FileUtils.getFileUtils(); if (spec == null) { for (int i = 0; i < files.length; i++) { cmdl.createArgument().setValue(utils.resolveFile(base, files[i]).getAbsolutePath()); } } else { for (int i = 0; i < files.length; i++) { cmdl.createArgument().setValue("-" + spec.getFullName() + equalString() + utils.resolveFile(base, files[i]).getAbsolutePath()); } } }
protected void addFiles(File base, String[] files, Commandline cmdl) { FileUtils utils = FileUtils.getFileUtils(); for (int i = 0; i < files.length; ++i) { File f = utils.resolveFile(base, files[i]); String absolutePath = f.getAbsolutePath(); if( f.isFile() && !absolutePath.endsWith(".swc") && !absolutePath.endsWith(".ane") ) continue; if (spec != null) { cmdl.createArgument().setValue("-" + spec.getFullName() + equalString() + absolutePath); } else { cmdl.createArgument().setValue(absolutePath); } } }
private ArgumentProcessor getProcessorByService(InputStream is) throws IOException { InputStreamReader isr = null; try { try { isr = new InputStreamReader(is, "UTF-8"); } catch (UnsupportedEncodingException e) { isr = new InputStreamReader(is); } BufferedReader rd = new BufferedReader(isr); String processorClassName = rd.readLine(); if (processorClassName != null && !"".equals(processorClassName)) { return getProcessor(processorClassName); } } finally { FileUtils.close(isr); } return null; }
public static @Nullable String relativizePaths( @NotNull String aAbsolutePath, @NotNull String bAbsolutePath ) { String relPath; try { relPath = FileUtils.getRelativePath(new File(aAbsolutePath), new File(bAbsolutePath)); // If the first character is not a '.' we add a ./ to indicate that // the file is in the same directory and not a node module if (relPath.charAt(0) != '.') { relPath = "./".concat(relPath); } } catch (Exception e) { return null; } return relPath; }
/** * Return an InputStream for reading the contents of this Resource. * @return an InputStream object. * @throws IOException if the zip file cannot be opened, * or the entry cannot be read. */ public InputStream getInputStream() throws IOException { if (isReference()) { return ((Resource) getCheckedRef()).getInputStream(); } final ZipFile z = new ZipFile(getZipfile(), getEncoding()); ZipEntry ze = z.getEntry(getName()); if (ze == null) { z.close(); throw new BuildException("no entry " + getName() + " in " + getArchive()); } return new FilterInputStream(z.getInputStream(ze)) { public void close() throws IOException { FileUtils.close(in); z.close(); } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } }; }
@Test public void testBuildfile() throws IOException { buildRule.configureProject(DIR + "/cdataoutput.xml"); if (buildRule.getProject().getProperty("cdata.inner") == null) { // avoid endless loop buildRule.executeTarget("run-junit"); File f = buildRule.getProject().resolveFile(REPORT); FileReader reader = null; try { reader = new FileReader(f); String content = FileUtils.readFully(reader); assertTrue(content.indexOf("</RESPONSE>]]>" + "</ERROR>") > 0); } finally { if (reader != null) { reader.close(); } f.delete(); } } }
/** * Computes a 'hashvalue' for a file content. * It reads the content of a file, convert that to String and use the * String.hashCode() method. * @param file The file for which the value should be computed * @return the hashvalue or <i>null</i> if the file couldn't be read */ // Because the content is only read the file will not be damaged. I tested // with JPG, ZIP and PDF as binary files. public String getValue(File file) { Reader r = null; try { if (!file.canRead()) { return null; } r = new FileReader(file); int hash = FileUtils.readFully(r).hashCode(); return Integer.toString(hash); } catch (Exception e) { return null; } finally { FileUtils.close(r); } }
/** * The heart of the matter. This is where the selector gets to decide * on the inclusion of a file in a particular fileset. * * @param basedir the base directory the scan is being done from * @param filename is the name of the file to check * @param file is a java.io.File object the selector can use * @return whether the file should be selected or not */ @Override public boolean isSelected(final File basedir, final String filename, final File file) { // throw BuildException on error validate(); // Determine file whose existence is to be checked final String[] destfiles = map.mapFileName(filename); // If filename does not match the To attribute of the mapper // then filter it out of the files we are considering if (destfiles == null) { return false; } // Sanity check if (destfiles.length != 1 || destfiles[0] == null) { throw new BuildException("Invalid destination file results for " + targetdir + " with filename " + filename); } final String destname = destfiles[0]; final File destfile = FileUtils.getFileUtils().resolveFile(targetdir, destname); return destfile.exists() == destmustexist; }
private static void registerTestCase(final String testCase) { if (crashFile != null) { try { FileWriter out = null; try { out = new FileWriter(crashFile); out.write(testCase + "\n"); out.flush(); } finally { FileUtils.close(out); } } catch (final IOException e) { // ignored. } } }
private void writeJavaClass() { try { File sourceFile = new File(getLocationName() + ".java"); verbose("Write collector class to '" + sourceFile.getAbsolutePath() + "'"); if (sourceFile.exists() && !sourceFile.delete()) { throw new IOException("could not delete " + sourceFile); } writer = new BufferedWriter(new FileWriter(sourceFile)); createClassHeader(); createSuiteMethod(); createClassFooter(); } catch (IOException e) { log(StringUtils.getStackTrace(e)); } finally { FileUtils.close(writer); } }
/** execute in a forked VM */ private int run(String[] command) throws BuildException { PumpStreamHandler psh = new PumpStreamHandler(new LogOutputStream(this, Project.MSG_INFO), new TeeOutputStream( new LogOutputStream(this, Project.MSG_WARN), bos) ); Execute exe = new Execute(psh, null); exe.setAntRun(getProject()); if (workingdir != null) { exe.setWorkingDirectory(workingdir); } exe.setCommandline(command); try { return exe.execute(); } catch (IOException e) { throw new BuildException(e, getLocation()); } finally { FileUtils.close(bos); } }
/** * get the URL of the schema * @return a URL to the schema * @throws BuildException if not */ public String getSchemaLocationURL() { boolean hasFile = file != null; boolean hasURL = isSet(url); //error if both are empty, or both are set if (!hasFile && !hasURL) { throw new BuildException(ERROR_NO_LOCATION + namespace); } if (hasFile && hasURL) { throw new BuildException(ERROR_TWO_LOCATIONS + namespace); } String schema = url; if (hasFile) { if (!file.exists()) { throw new BuildException(ERROR_NO_FILE + file); } try { schema = FileUtils.getFileUtils().getFileURL(file).toString(); } catch (MalformedURLException e) { //this is almost implausible, but required handling throw new BuildException(ERROR_NO_URL_REPRESENTATION + file, e); } } return schema; }
/** * test for bugzilla 48932 */ @Test public void testPrintStreamDoesNotGetClosed() throws IOException { Message ms = new Message(); Project p = new Project(); ms.setProject(p); ms.addText("hi, this is an email"); FileOutputStream fis = null; try { fis = new FileOutputStream(f); ms.print(new PrintStream(fis)); fis.write(120); } finally { FileUtils.close(fis); } }
private void getFile(final ChannelSftp channel, final ChannelSftp.LsEntry le, File localFile) throws IOException, SftpException { final String remoteFile = le.getFilename(); if (!localFile.exists()) { final String path = localFile.getAbsolutePath(); final int i = path.lastIndexOf(File.pathSeparator); if (i != -1) { if (path.length() > File.pathSeparator.length()) { new File(path.substring(0, i)).mkdirs(); } } } if (localFile.isDirectory()) { localFile = new File(localFile, remoteFile); } final long startTime = System.currentTimeMillis(); final long totalLength = le.getAttrs().getSize(); SftpProgressMonitor monitor = null; final boolean trackProgress = getVerbose() && totalLength > HUNDRED_KILOBYTES; if (trackProgress) { monitor = getProgressMonitor(); } try { log("Receiving: " + remoteFile + " : " + le.getAttrs().getSize()); channel.get(remoteFile, localFile.getAbsolutePath(), monitor); } finally { final long endTime = System.currentTimeMillis(); logStats(startTime, endTime, (int) totalLength); } if (getPreserveLastModified()) { FileUtils.getFileUtils().setFileLastModified(localFile, ((long) le.getAttrs() .getMTime()) * 1000); } }
/** * set the text using a file * @param file the file to use * @throws BuildException if the file does not exist, or cannot be * read */ public void setFile(File file) throws BuildException { // non-existing files are not allowed if (!file.exists()) { throw new BuildException("File %s does not exist.", file); } BufferedReader reader = null; try { if (this.encoding == null) { reader = new BufferedReader(new FileReader(file)); } else { reader = new BufferedReader( new InputStreamReader(Files.newInputStream(file.toPath()), this.encoding)); } value = FileUtils.safeReadFully(reader); } catch (IOException ex) { throw new BuildException(ex); } finally { FileUtils.close(reader); } }
/** * Check if a given resource can be loaded. */ private boolean checkResource(String resource) { InputStream is = null; try { if (loader != null) { is = loader.getResourceAsStream(resource); } else { ClassLoader cL = this.getClass().getClassLoader(); if (cL != null) { is = cL.getResourceAsStream(resource); } else { is = ClassLoader.getSystemResourceAsStream(resource); } } return is != null; } finally { FileUtils.close(is); } }
/** * access the stream to which the stdout from cvs should go * if this stream has already been set, it will be returned * if the stream has not yet been set, if the attribute output * has been set, the output stream will go to the output file * otherwise the output will go to ant's logging system * @return output stream to which cvs' stdout should go to */ protected OutputStream getOutputStream() { if (this.outputStream == null) { if (output != null) { try { setOutputStream(new PrintStream( new BufferedOutputStream( FileUtils.newOutputStream(Paths.get(output.getPath()), append)))); } catch (IOException e) { throw new BuildException(e, getLocation()); } } else { setOutputStream(new LogOutputStream(this, Project.MSG_INFO)); } } return this.outputStream; }
/** * access the stream to which the stderr from cvs should go * if this stream has already been set, it will be returned * if the stream has not yet been set, if the attribute error * has been set, the output stream will go to the file denoted by the error attribute * otherwise the stderr output will go to ant's logging system * @return output stream to which cvs' stderr should go to */ protected OutputStream getErrorStream() { if (this.errorStream == null) { if (error != null) { try { setErrorStream(new PrintStream( new BufferedOutputStream( FileUtils.newOutputStream(Paths.get(error.getPath()), append)))); } catch (IOException e) { throw new BuildException(e, getLocation()); } } else { setErrorStream(new LogOutputStream(this, Project.MSG_WARN)); } } return this.errorStream; }
/** * helper method to execute our command on VMS. * @param cmd Commandline * @param firstFileName int * @return boolean */ private boolean execOnVMS(Commandline cmd, int firstFileName) { File vmsFile = null; try { vmsFile = JavaEnvUtils.createVmsJavaOptionFile(cmd.getArguments()); String[] commandLine = {cmd.getExecutable(), "-V", vmsFile.getPath()}; return 0 == executeExternalCompile(commandLine, firstFileName, true); } catch (IOException e) { throw new BuildException( "Failed to create a temporary file for \"-V\" switch"); } finally { FileUtils.delete(vmsFile); } }
/** * @see Expand#expandFile(FileUtils, File, File) * {@inheritDoc} */ @Override protected void expandFile(FileUtils fileUtils, File srcF, File dir) { if (!srcF.exists()) { throw new BuildException("Unable to untar " + srcF + " as the file does not exist", getLocation()); } try (InputStream fis = Files.newInputStream(srcF.toPath())) { expandStream(srcF.getPath(), fis, dir); } catch (IOException ioe) { throw new BuildException("Error while expanding " + srcF.getPath() + "\n" + ioe.toString(), ioe, getLocation()); } }
/** * @since Ant 1.7 */ private void expandStream(String name, InputStream stream, File dir) throws IOException { try (TarInputStream tis = new TarInputStream( compression.decompress(name, new BufferedInputStream(stream)), getEncoding())) { log("Expanding: " + name + " into " + dir, Project.MSG_INFO); boolean empty = true; FileNameMapper mapper = getMapper(); TarEntry te; while ((te = tis.getNextEntry()) != null) { empty = false; extractFile(FileUtils.getFileUtils(), null, dir, tis, te.getName(), te.getModTime(), te.isDirectory(), mapper); } if (empty && getFailOnEmptyArchive()) { throw new BuildException("archive '%s' is empty", name); } log("expand complete", Project.MSG_VERBOSE); } }
private void collectFileListFromModulePath() { final FileUtils fu = FileUtils.getFileUtils(); for (String pathElement : moduleSourcepath.list()) { boolean valid = false; for (Map.Entry<String, Collection<File>> modules : resolveModuleSourcePathElement( getProject().getBaseDir(), pathElement).entrySet()) { final String moduleName = modules.getKey(); for (File srcDir : modules.getValue()) { if (srcDir.exists()) { valid = true; final DirectoryScanner ds = getDirectoryScanner(srcDir); final String[] files = ds.getIncludedFiles(); scanDir(srcDir, fu.resolveFile(destDir, moduleName), files); } } } if (!valid) { throw new BuildException("modulesourcepath \"" + pathElement + "\" does not exist!", getLocation()); } } }
/** * Finds modules in the expanded modulesourcepath entry. * @param root the project root * @param pathToModule the path to modules folder * @param pathInModule the path in module to source folder * @param collector the map to put modules into * @since 1.9.7 */ private static void findModules( final File root, final String pathToModule, final String pathInModule, final Map<String,Collection<File>> collector) { final FileUtils fu = FileUtils.getFileUtils(); final File f = fu.resolveFile(root, pathToModule); if (!f.isDirectory()) { return; } for (File module : f.listFiles(File::isDirectory)) { final String moduleName = module.getName(); final File moduleSourceRoot = pathInModule == null ? module : new File(module, pathInModule); Collection<File> moduleRoots = collector.get(moduleName); if (moduleRoots == null) { moduleRoots = new ArrayList<>(); collector.put(moduleName, moduleRoots); } moduleRoots.add(moduleSourceRoot); } }
/** * Returns properties from a specified properties file. * * @param resource The resource to load properties from. */ private Properties getProperties(Resource resource) { InputStream in = null; Properties props = new Properties(); try { in = resource.getInputStream(); props.load(in); } catch (IOException ioe) { if (getProject() != null) { getProject().log("getProperties failed, " + ioe.getMessage(), Project.MSG_ERR); } else { ioe.printStackTrace(); //NOSONAR } } finally { FileUtils.close(in); } return props; }
/** * Load default task or type definitions - just the names, * no class loading. * Caches results between calls to reduce overhead. * @param type true for typedefs, false for taskdefs * @return a mapping from definition names to class names * @throws BuildException if there was some problem loading * or parsing the definitions list */ private static synchronized Properties getDefaultDefinitions(boolean type) throws BuildException { int idx = type ? 1 : 0; if (defaultDefinitions[idx] == null) { String resource = type ? MagicNames.TYPEDEFS_PROPERTIES_RESOURCE : MagicNames.TASKDEF_PROPERTIES_RESOURCE; String errorString = type ? ERROR_NO_TYPE_LIST_LOAD : ERROR_NO_TASK_LIST_LOAD; InputStream in = null; try { in = ComponentHelper.class.getResourceAsStream(resource); if (in == null) { throw new BuildException(errorString); } Properties p = new Properties(); p.load(in); defaultDefinitions[idx] = p; } catch (IOException e) { throw new BuildException(errorString, e); } finally { FileUtils.close(in); } } return defaultDefinitions[idx]; }
@Test public void testFindClass() throws Exception { String testCaseURL = getClass() .getClassLoader().getResource("junit/framework/TestCase.class") .toExternalForm(); int pling = testCaseURL.indexOf('!'); String jarName = testCaseURL.substring(4, pling); File f = new File(FileUtils.getFileUtils().fromURI(jarName)); Path p = new Path(null); p.createPathElement().setLocation(f); AntClassLoader al = null; for (int i = 0; i < 1000; i++) { try { // not using factory method so the test can run on Ant // 1.7.1 as well al = new AntClassLoader(null, null, p, false); al.findClass("junit.framework.TestCase"); } finally { if (al != null) { al.cleanup(); } } } }
private static String safeRelativePath(File from, File to) { try { return FileUtils.getRelativePath(from, to); } catch (Exception ex) { return to.getAbsolutePath(); } }
/** 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; }