public static VFSContainer getOrCreateContainer(VFSContainer parent, String name) { VFSItem item = parent.resolve(name); if (item instanceof VFSContainer) { return (VFSContainer) item; } else if (item != null) { return null; // problem } else { return parent.createChildContainer(name); } }
/** * Resolves a directory path in the base container or creates this directory. The method creates * any missing directories. * * @param baseContainer The base directory. User must have write permissions on this container * @param relContainerPath The path relative to the base container. Must start with a '/'. To * separate sub directories use '/' * @return The resolved or created container or NULL if a problem happened */ public static VFSContainer resolveOrCreateContainerFromPath( VFSContainer baseContainer, String relContainerPath) { VFSContainer resultContainer = baseContainer; if (!VFSConstants.YES.equals(baseContainer.canWrite())) { log.error( "Could not create relPath::" + relContainerPath + ", base container::" + getRealPath(baseContainer) + " not writable", null); resultContainer = null; } else if (StringHelper.containsNonWhitespace(relContainerPath)) { // Try to resolve given rel path from current container VFSItem resolvedPath = baseContainer.resolve(relContainerPath.trim()); if (resolvedPath == null) { // Does not yet exist - create subdir String[] pathSegments = relContainerPath.split("/"); for (int i = 0; i < pathSegments.length; i++) { String segment = pathSegments[i].trim(); if (StringHelper.containsNonWhitespace(segment)) { resolvedPath = resultContainer.resolve(segment); if (resolvedPath == null) { resultContainer = resultContainer.createChildContainer(segment); if (resultContainer == null) { log.error( "Could not create container with name::" + segment + " in relPath::" + relContainerPath + " in base container::" + getRealPath(baseContainer), null); break; } } else { if (resolvedPath instanceof VFSContainer) { resultContainer = (VFSContainer) resolvedPath; } else { resultContainer = null; log.error( "Could not create container with name::" + segment + " in relPath::" + relContainerPath + ", a file with this name exists (but not a directory) in base container::" + getRealPath(baseContainer), null); break; } } } } } else { // Parent dir already exists, make sure this is really a container and not a file! if (resolvedPath instanceof VFSContainer) { resultContainer = (VFSContainer) resolvedPath; } else { resultContainer = null; log.error( "Could not create relPath::" + relContainerPath + ", a file with this name exists (but not a directory) in base container::" + getRealPath(baseContainer), null); } } } return resultContainer; }