List of usage examples for org.apache.commons.vfs FileObject createFolder
public void createFolder() throws FileSystemException;
From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java
private boolean CreateDestinationFolder(FileObject filefolder) { LogWriter log = LogWriter.getInstance(); FileObject folder = null; try {//w w w . j a v a 2s.c o m if (destination_is_a_file) folder = filefolder.getParent(); else folder = filefolder; if (!folder.exists()) { if (create_destination_folder) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FolderNotExist", folder.getName().toString())); folder.createFolder(); if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.FolderWasCreated", folder.getName().toString())); } else { log.logError(toString(), Messages.getString("JobMoveFiles.Log.FolderNotExist", folder.getName().toString())); return false; } } return true; } catch (Exception e) { log.logError(toString(), Messages.getString("JobMoveFiles.Log.CanNotCreateParentFolder", folder.getName().toString())); } finally { if (folder != null) { try { folder.close(); } catch (Exception ex) { } ; } } return false; }
From source file:com.panet.imeta.job.entries.movefiles.JobEntryMoveFiles.java
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) throws KettleException { LogWriter log = LogWriter.getInstance(); Result result = previousResult; List<RowMetaAndData> rows = result.getRows(); RowMetaAndData resultRow = null;/* w ww . j av a 2 s . c om*/ result.setEntryNr(1); result.setResult(false); NrErrors = 0; NrSuccess = 0; successConditionBroken = false; successConditionBrokenExit = false; limitFiles = Const.toInt(environmentSubstitute(getNrErrorsLessThan()), 10); if (simulate) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.SimulationOn")); } if (include_subfolders) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.IncludeSubFoldersOn")); } String MoveToFolder = environmentSubstitute(destinationFolder); // Get source and destination files, also wildcard String vsourcefilefolder[] = source_filefolder; String vdestinationfilefolder[] = destination_filefolder; String vwildcard[] = wildcard; if (iffileexists.equals("move_file")) { if (Const.isEmpty(MoveToFolder)) { log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error.MoveToFolderMissing")); return result; } FileObject folder = null; try { folder = KettleVFS.getFileObject(MoveToFolder); if (!folder.exists()) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.Error.FolderMissing", MoveToFolder)); if (create_move_to_folder) { folder.createFolder(); } else { log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error.FolderMissing", MoveToFolder)); return result; } } if (!folder.getType().equals(FileType.FOLDER)) { log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error.NotFolder", MoveToFolder)); return result; } } catch (Exception e) { log.logError(toString(), Messages.getString("JobMoveFiles.Log.Error.GettingMoveToFolder", MoveToFolder, e.getMessage())); return result; } finally { if (folder != null) { try { folder.close(); } catch (IOException ex) { } ; } } } if (arg_from_previous) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.ArgFromPrevious.Found", (rows != null ? rows.size() : 0) + "")); } if (arg_from_previous && rows != null) { for (int iteration = 0; iteration < rows.size() && !parentJob.isStopped(); iteration++) { // Success condition broken? if (successConditionBroken) { if (!successConditionBrokenExit) { log.logError(toString(), Messages.getString("JobMoveFiles.Error.SuccessConditionbroken", "" + NrErrors)); successConditionBrokenExit = true; } result.setNrErrors(NrErrors); displayResults(log); return result; } resultRow = rows.get(iteration); // Get source and destination file names, also wildcard String vsourcefilefolder_previous = resultRow.getString(0, null); String vdestinationfilefolder_previous = resultRow.getString(1, null); String vwildcard_previous = resultRow.getString(2, null); if (!Const.isEmpty(vsourcefilefolder_previous) && !Const.isEmpty(vdestinationfilefolder_previous)) { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.ProcessingRow", vsourcefilefolder_previous, vdestinationfilefolder_previous, vwildcard_previous)); if (!ProcessFileFolder(vsourcefilefolder_previous, vdestinationfilefolder_previous, vwildcard_previous, parentJob, result, MoveToFolder, log)) { // The move process fail // Update Errors updateErrors(); } } else { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.IgnoringRow", vsourcefilefolder[iteration], vdestinationfilefolder[iteration], vwildcard[iteration])); } } } else if (vsourcefilefolder != null && vdestinationfilefolder != null) { for (int i = 0; i < vsourcefilefolder.length && !parentJob.isStopped(); i++) { // Success condition broken? if (successConditionBroken) { if (!successConditionBrokenExit) { log.logError(toString(), Messages.getString("JobMoveFiles.Error.SuccessConditionbroken", "" + NrErrors)); successConditionBrokenExit = true; } result.setEntryNr(NrErrors); displayResults(log); return result; } if (!Const.isEmpty(vsourcefilefolder[i]) && !Const.isEmpty(vdestinationfilefolder[i])) { // ok we can process this file/folder if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.ProcessingRow", vsourcefilefolder[i], vdestinationfilefolder[i], vwildcard[i])); if (!ProcessFileFolder(vsourcefilefolder[i], vdestinationfilefolder[i], vwildcard[i], parentJob, result, MoveToFolder, log)) { // Update Errors updateErrors(); } } else { if (log.isDetailed()) log.logDetailed(toString(), Messages.getString("JobMoveFiles.Log.IgnoringRow", vsourcefilefolder[i], vdestinationfilefolder[i], vwildcard[i])); } } } // Success Condition result.setNrErrors(NrErrors); result.setNrLinesWritten(NrSuccess); if (getSuccessStatus()) result.setResult(true); displayResults(log); return result; }
From source file:com.newatlanta.appengine.vfs.provider.GaeFileSystemManager.java
/** * Resolves a URI, relative to a base file with the specified FileSystem * configuration options.// w w w. j a v a 2s. c om */ @Override public FileObject resolveFile(FileObject baseFile, String uri, FileSystemOptions opts) throws FileSystemException { // let the specified provider handle it if (!isCombinedLocal || isSchemeSpecified(uri)) { return super.resolveFile(baseFile, uri, opts); } FileObject localFile; FileObject gaeFile; if (baseFile != null) { // if uri starts with "/", determine if it includes the base path; // if it doesn't, then remove the leading "/" to create a relative // path; this is required to properly resolve "file://" uri = checkRelativity(baseFile, uri); FileObject fileObject = super.resolveFile(baseFile, uri, opts); if (fileObject.exists() && (fileObject.getType().hasContent())) { return fileObject; // return existing file } // fileObject doesn't exist or is a folder, check other file system if (fileObject.getName().getScheme().equals("gae")) { gaeFile = fileObject; FileName baseName = baseFile.getName(); if (baseName instanceof GaeFileName) { String localUri = "file://" + ((GaeFileName) baseName).getRootPath() + baseName.getPath() + "/" + uri; localFile = super.resolveFile(null, localUri, opts); } else { localFile = super.resolveFile(baseFile, "file://" + uri, opts); } if (localFile.exists() && (localFile.getType().hasContent())) { return localFile; // return existing local files } } else { localFile = fileObject; gaeFile = super.resolveFile(baseFile, "gae://" + uri, opts); } } else { // neither scheme nor baseFile specified, check local first localFile = super.resolveFile(null, uri, opts); if (localFile.exists() && (localFile.getType().hasContent())) { return localFile; // return existing local files } // localFile doesn't exist or is a folder, check GAE file system gaeFile = super.resolveFile(null, "gae://" + uri, opts); } ((GaeFileObject) gaeFile).setCombinedLocal(true); // when we get here we either have a non-existing file, or a folder; // return the GAE file/folder if it exists if (gaeFile.exists()) { return gaeFile; } // never return local folders if (localFile.exists()) { gaeFile.createFolder(); // create GAE "shadow" for existing local folder return gaeFile; } return gaeFile; // neither local nor GAE file/folder exists }
From source file:org.bibalex.gallery.storage.BAGStorage.java
public static URL cacheFileLocally(String cacheLocalPath, String fileUrlStr) throws BAGException { try {/*from w ww.j a v a 2 s .c om*/ // String extension = ""; // // int lastDotIx = fileUrlStr.lastIndexOf('.'); // if (lastDotIx > fileUrlStr.lastIndexOf('/')) { // extension = fileUrlStr.substring(lastDotIx); // } // String cacheFileName = "cached" + fileUrlStr.hashCode() + extension; int lastSlashIx = fileUrlStr.lastIndexOf('/'); String cacheFileName = fileUrlStr.substring(lastSlashIx + 1); String cacheFilePath = URLPathStrUtils.appendParts(cacheLocalPath, cacheFileName); FileSystemManager fsMgr = VFS.getManager(); final FileObject cacheFileFO = fsMgr.resolveFile(cacheFilePath); final FileObject cacheDirFO = fsMgr.resolveFile(cacheLocalPath); if (!cacheFileFO.exists()) { synchronized (BAGStorage.class) { if (!cacheDirFO.exists()) { cacheDirFO.createFolder(); } cacheFileFO.createFile(); OutputStream cacheFileOut = cacheFileFO.getContent().getOutputStream(); try { readRemoteFile(fileUrlStr, cacheFileOut); } finally { cacheFileOut.close(); } } } return cacheFileFO.getURL(); } catch (FileSystemException e) { throw new BAGException(e); } catch (IOException e) { throw new BAGException(e); } }
From source file:org.codehaus.cargo.container.spi.configuration.StandaloneConfigurationTest.java
/** * Test the creation of a config directory when the target directory exists and is empty. * @throws Exception If anything goes wrong. *///w w w. j a v a 2 s. c o m public void testCreateConfigDirWhenDirectoryExistButIsEmpty() throws Exception { String configDir = "ram:///cargo/testCreateConfigDirWhenDirectoryExistButIsEmpty"; FileObject configDirObject = VFS.getManager().resolveFile(configDir); FileObject timestampFileObject = configDirObject.resolveFile(".cargo"); configDirObject.createFolder(); TestableAbstractStandaloneConfiguration configuration = new TestableAbstractStandaloneConfiguration( configDir); configuration.setFileHandler(new VFSFileHandler()); configuration.setupConfigurationDir(); assertTrue("Cargo timestamp should have existed", timestampFileObject.exists()); }
From source file:org.codehaus.cargo.util.VFSFileHandler.java
/** * Create a directory. {@inheritDoc}//from w w w .j ava 2 s . c o m * @param parent Parent directory name. * @param path Directory name. * @return Created directory name. */ @Override public String createDirectory(String parent, String path) { String directoryname; if (path != null) { directoryname = path; } else { directoryname = ""; } if (parent != null) { if (!parent.endsWith("/") && !directoryname.startsWith("/")) { directoryname = "/" + directoryname; } directoryname = parent + directoryname; } try { FileObject fileObject = getFileSystemManager().resolveFile(directoryname); fileObject.createFolder(); return fileObject.toString(); } catch (FileSystemException e) { throw new CargoException("Failed to create folder [" + directoryname + "]", e); } }
From source file:org.codehaus.mojo.unix.core.FsFileCollector.java
public FsFileCollector(FileObject fsRoot) throws FileSystemException { this.fsRoot = fsRoot; FileSystemManager fileSystemManager = fsRoot.getFileSystem().getFileSystemManager(); FileObject root = fileSystemManager.createVirtualFileSystem(fsRoot); root.createFolder(); this.root = root; }
From source file:org.codehaus.mojo.unix.maven.deb.DebUnixPackage.java
public void packageToFile(File packageFile, ScriptUtil.Strategy strategy) throws Exception { FileObject fsRoot = fileCollector.getFsRoot(); FileObject debian = fsRoot.resolveFile("DEBIAN"); FileObject controlFilePath = debian.resolveFile("control"); debian.createFolder(); LineStreamUtil.toFile(controlFile.toList(), asFile(controlFilePath)); fileCollector.collect();/*from w w w . j av a2 s .co m*/ ScriptUtil.Result result = scriptUtil .createExecution(controlFile.packageName, "deb", getScripts(), asFile(debian), strategy).execute(); UnixUtil.chmodIf(result.preInstall, "0755"); UnixUtil.chmodIf(result.postInstall, "0755"); UnixUtil.chmodIf(result.preRemove, "0755"); UnixUtil.chmodIf(result.postRemove, "0755"); new Dpkg().setDebug(debug).setPackageRoot(asFile(fsRoot)).setDebFile(packageFile) .setUseFakeroot(useFakeroot).execute(); }
From source file:org.codehaus.mojo.unix.maven.MojoHelper.java
public static Execution create(Map platforms, String platformType, Map formats, String formatType, SnapshotTransformation snapshotTransformation, MavenProjectWrapper project, boolean debug, boolean attachedMode, F<UnixPackage, UnixPackage> validateMojoSettingsAndApplyFormatSpecificSettingsToPackage, PackagingMojoParameters mojoParameters, final Log log) throws MojoFailureException, MojoExecutionException { MavenCommonLoggingLogFactory.setMavenLogger(log); PackagingFormat format = (PackagingFormat) formats.get(formatType); if (format == null) { throw new MojoFailureException("INTERNAL ERROR: could not find format: '" + formatType + "'."); }//from w w w . j a v a2s . co m UnixPlatform platform = (UnixPlatform) platforms.get(platformType); if (platform == null) { throw new MojoFailureException("INTERNAL ERROR: could not find platform: '" + platformType + "'."); } // TODO: This is using a private Maven API that might change. Perhaps use some reflection magic here. String timestamp = snapshotTransformation.getDeploymentTimestamp(); FileObject buildDirectory; try { FileSystemManager fileSystemManager = VFS.getManager(); buildDirectory = fileSystemManager.resolveFile(project.buildDirectory.getAbsolutePath()); } catch (FileSystemException e) { throw new MojoExecutionException("Error while initializing Commons VFS", e); } PackageVersion version = PackageVersion.packageVersion(project.version, timestamp, project.artifact.isSnapshot(), mojoParameters.revision); List<P3<UnixPackage, Package, List<AssemblyOperation>>> packages = nil(); for (Package pakke : validatePackages(mojoParameters.packages, attachedMode)) { try { String name = "unix/root-" + formatType + pakke.classifier.map(dashString).orSome(""); FileObject packageRoot = buildDirectory.resolveFile(name); packageRoot.createFolder(); PackageParameters parameters = calculatePackageParameters(project, version, platform, mojoParameters, pakke); UnixPackage unixPackage = format.start().parameters(parameters).setVersion(version). // TODO: This should go away workingDirectory(packageRoot).debug(debug).basedir(project.basedir); // ----------------------------------------------------------------------- // Let the implementation add its metadata // ----------------------------------------------------------------------- unixPackage = validateMojoSettingsAndApplyFormatSpecificSettingsToPackage.f(unixPackage); // TODO: here the logic should be different if many packages are to be created. // Example: name should be taken from mojoParameters if there is only a single package, if not // it should come from the Pakke object. This should also be validated, at least for // name List<AssemblyOperation> assemblyOperations = createAssemblyOperations(project, parameters, unixPackage, project.basedir, buildDirectory, mojoParameters.assembly, pakke.assembly); // ----------------------------------------------------------------------- // Dump the execution // ----------------------------------------------------------------------- if (debug) { log.info("======================================================================="); log.info("Package parameters: " + parameters.id); log.info("Default file attributes: "); log.info(" File : " + parameters.defaultFileAttributes); log.info(" Directory : " + parameters.defaultDirectoryAttributes); log.info("Assembly operations: "); for (AssemblyOperation operation : assemblyOperations) { operation.streamTo(new AbstractLineStreamWriter() { protected void onLine(String line) { log.info(line); } }); } } packages = packages.cons(p(unixPackage, pakke, assemblyOperations)); } catch (UnknownArtifactException e) { Map map = new TreeMap<String, Artifact>(e.artifactMap); // TODO: Do not log here, throw a CouldNotFindArtifactException with the map as an argument log.warn("Could not find artifact:" + e.artifact); log.warn("Available artifacts:"); for (Object o : map.keySet()) { log.warn(o.toString()); } throw new MojoFailureException( "Unable to find artifact: '" + e.artifact + "'. See log for available artifacts."); } catch (MissingSettingException e) { String msg = "Missing required setting '" + e.getSetting() + "'"; if (!pakke.classifier.isNone()) { msg += ", for '" + pakke.classifier.some() + "'"; } msg += ", format '" + formatType + "'."; throw new MojoFailureException(msg); } catch (IOException e) { throw new MojoExecutionException( "Error creating package '" + pakke.classifier + "', format '" + formatType + "'.", e); } } return new Execution(packages, project, formatType, attachedMode); }
From source file:org.codehaus.mojo.unix.sysvpkg.prototype.PrototypeFileTest.java
public void testBasic() throws Exception { FileSystemManager fsManager = VFS.getManager(); FileObject root = fsManager.resolveFile(getTestPath("target/prototype-test/assembly")); root.createFolder(); PrototypeFile prototypeFile = new PrototypeFile(defaultEntry); FileObject bashProfileObject = fsManager.resolveFile(getTestPath("src/test/non-existing/bash_profile")); FileObject extractJarObject = fsManager.resolveFile(getTestPath("src/test/non-existing/extract.jar")); UnixFsObject.RegularFile extractJar = regularFile(extractJarPath, dateTime, 0, some(fileAttributes)); UnixFsObject.RegularFile bashProfile = regularFile(bashProfilePath, dateTime, 0, some(fileAttributes)); UnixFsObject.RegularFile smfManifestXml = regularFile(smfManifestXmlPath, dateTime, 0, some(fileAttributes.addTag("class:smf"))); prototypeFile.addFile(bashProfileObject, bashProfile); prototypeFile.addFile(extractJarObject, extractJar); prototypeFile.addFile(extractJarObject, smfManifestXml); prototypeFile.addDirectory(directory(BASE, dateTime, dirAttributes)); prototypeFile.addDirectory(directory(specialPath, dateTime, dirAttributes)); prototypeFile.apply(filter(extractJarPath, fileAttributes.user("funnyuser"))); prototypeFile.apply(filter(specialPath, dirAttributes.group("funnygroup"))); LineFile stream = new LineFile(); prototypeFile.streamTo(stream);//from w ww. ja va2 s . c o m assertEquals( new LineFile() .add("f none /extract.jar=" + extractJarObject.getName().getPath() + " 0644 funnyuser nogroup") .add("d none /opt ? default default").add("d none /opt/jetty ? default default") .add("f none /opt/jetty/.bash_profile=" + bashProfileObject.getName().getPath() + " 0644 nouser nogroup") .add("d none /smf ? default default") .add("f smf /smf/manifest.xml=" + extractJarObject.getName().getPath() + " 0644 nouser nogroup") .add("d none /special 0755 nouser funnygroup").toString(), stream.toString()); }