Java Code Examples for org.apache.commons.vfs2.FileObject

The following are top voted examples for showing how to use org.apache.commons.vfs2.FileObject. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: esb-connector-file   File: FileMove.java   Source Code and License 7 votes vote down vote up
/**
 * @param remoteFile     Location of the file
 * @param destination    New file location
 * @param filePattern    Pattern of the file
 * @param manager        Standard file system manager
 * @param messageContext The message context that is generated for processing the file
 * @throws IOException
 */
private void moveFileWithPattern(FileObject remoteFile, String destination, String filePattern,
                                 StandardFileSystemManager manager, MessageContext messageContext) throws IOException {
    FilePattenMatcher patternMatcher = new FilePattenMatcher(filePattern);
    try {
        if (patternMatcher.validate(remoteFile.getName().getBaseName())) {
            FileObject file = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
            if (!file.exists()) {
                file.createFolder();
            }
            file = manager.resolveFile(destination + File.separator + remoteFile.getName().getBaseName(),
                    FileConnectorUtils.init(messageContext));
            remoteFile.moveTo(file);
        }
    } catch (IOException e) {
        log.error("Error occurred while moving a file. " + e.getMessage(), e);
    }
}
 
Example 2
Project: yajsw   File: FilePropertiesConfiguration.java   Source Code and License 6 votes vote down vote up
public void load() throws Exception
{
	Reader reader = null;
	try
	{
	FileObject f = VFSUtils.resolveFile(".", _fileName);
	InputStream in = f.getContent().getInputStream();
	reader = new InputStreamReader(in);
	this.read(reader);
	}
	catch(Exception ex)
	{
		ex.printStackTrace();
	}
	finally
	{
		if (reader != null)
			reader.close();
	}
}
 
Example 3
Project: yajsw   File: YajswConfigurationImpl.java   Source Code and License 6 votes vote down vote up
private boolean fileExists(String file)
{
	try
	{
		// this hack is no longer required, changed VFS to init without
		// providers.xm.
		// String current =
		// System.getProperty("javax.xml.parsers.DocumentBuilderFactory");
		// System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
		// "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
		DefaultFileSystemManager fsManager = (DefaultFileSystemManager) VFS
				.getManager();
		// if (current != null)
		// System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
		// current);
		// else
		// System.clearProperty("javax.xml.parsers.DocumentBuilderFactory");
		FileObject f = VFSUtils.resolveFile(".", file);
		return f.exists();
	}
	catch (FileSystemException e)
	{
		e.printStackTrace();
		return false;
	}
}
 
Example 4
Project: yajsw   File: YajswConfigurationImpl.java   Source Code and License 6 votes vote down vote up
public boolean isLocalFile()
{
	if (_fileConfiguration == null)
		return true;
	try
	{
		String name = _fileConfiguration.getURL();
		if (name.endsWith(".jnlp"))
			return false;

		FileObject f = VFSUtils.resolveFile(".", name);
		// if we set cache to CacheStrategy.ON_CALL FileObjects are
		// decorated to call refresh.
		// getContent().getFile() returns the decorated file
		return VFSUtils.isLocal(f);
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
		return true;
	}

}
 
Example 5
Project: yajsw   File: JarBuilder.java   Source Code and License 6 votes vote down vote up
private void buildJar(String newJar) throws IOException
{
	ZipOutputStream out = new ZipOutputStream(new FileOutputStream(newJar ));
	FileSystemManager fsManager = VFS.getManager();
	for (String jar : _jar2class.keySet())
	{
		FileObject jarFile;
		if (jar.endsWith(".jar"))
			jarFile = fsManager.resolveFile( "jar:"+jar );
		else
			jarFile = fsManager.resolveFile( jar );
			
			for (String file : _jar2class.get(jar))
			{
				file = file.replaceAll("\\.", "/");
				file += ".class";
				FileObject f = fsManager.resolveFile(jarFile, file);
				if (f.exists())
					addFile(f, file, out);
				else
					System.out.println("file not found "+f);
			}	
			
	}
	out.close();
}
 
Example 6
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 6 votes vote down vote up
@Override
public void remove(String noteId) throws IOException {
  FileObject rootDir = fsManager.resolveFile(getPath("/"));
  FileObject noteDir = rootDir.resolveFile(noteId, NameScope.CHILD);

  if (!noteDir.exists()) {
    // nothing to do
    return;
  }

  if (!isDirectory(noteDir)) {
    // it is not look like zeppelin note savings
    throw new IOException("Can not remove " + noteDir.getName().toString());
  }

  noteDir.delete(Selectors.SELECT_SELF_AND_CHILDREN);
}
 
Example 7
Project: mycore   File: MCRStore.java   Source Code and License 6 votes vote down vote up
/**
 * Recursively searches for the highest ID, which is the greatest slot file
 * name currently used in the store.
 * 
 * @param dir
 *            the directory to search
 * @param depth
 *            the subdirectory depth level of the dir
 * @return the highest slot file name / ID currently stored
 */
private String findMaxID(final FileObject dir, final int depth) throws FileSystemException {
    final FileObject[] children = dir.getChildren();

    if (children.length == 0) {
        return null;
    }

    Arrays.sort(children, new MCRFileObjectComparator());

    if (depth == slotLength.length) {
        return children[children.length - 1].getName().getBaseName();
    }

    for (int i = children.length - 1; i >= 0; i--) {
        final FileObject child = children[i];
        if (!child.getType().hasChildren()) {
            continue;
        }
        final String found = findMaxID(child, depth + 1);
        if (found != null) {
            return found;
        }
    }
    return null;
}
 
Example 8
Project: mycore   File: MCRNode.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the FileObject that is the father of all logical children of this
 * FileObject. This may not be the current node itself, in case the node is
 * a container file, because then intermediate FileObject instances are
 * created by Apache VFS.
 * 
 * @return the father of this node's children in VFS
 */
private FileObject getFather() throws IOException {
    if (isDirectory()) {
        return fo;
    } else if (getSize() == 0) {
        return null;
    } else if (VFS.getManager().canCreateFileSystem(fo)) {
        FileObject father = fo;
        while (VFS.getManager().canCreateFileSystem(father)) {
            father = VFS.getManager().createFileSystem(father);
        }
        return father;
    } else {
        return null;
    }
}
 
Example 9
Project: mycore   File: MCRNode.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the children of this node. Directories and container files like
 * zip or tar may have child nodes.
 * 
 * @return a List of child nodes, which may be empty, in undefined order
 */
public List<MCRNode> getChildren() throws IOException {
    List<MCRNode> children = new ArrayList<>();
    FileObject father = getFather();
    if (father != null) {
        FileObject[] childFos = father.getChildren();
        for (FileObject childFo : childFos) {
            String name = childFo.getName().getBaseName();
            MCRNode child = getChild(name);
            if (child != null) {
                children.add(child);
            }
        }
    }
    return children;
}
 
Example 10
Project: mycore   File: MCRCStoreVFS.java   Source Code and License 6 votes vote down vote up
@Override
protected String doStoreContent(MCRFile file, MCRContentInputStream source) throws Exception {
    StringBuilder storageId = new StringBuilder();

    String[] slots = buildSlotPath();
    // Recursively create directory name
    for (String slot : slots) {
        storageId.append(slot).append("/");
    }

    String fileId = buildNextID(file);
    storageId.append(fileId);

    FileObject targetObject = fsManager.resolveFile(getBase(), storageId.toString());
    FileContent targetContent = targetObject.getContent();
    try (OutputStream out = targetContent.getOutputStream()) {
        IOUtils.copy(source, out);
    } finally {
        targetContent.close();
    }
    return storageId.toString();
}
 
Example 11
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 6 votes vote down vote up
@Override
public synchronized void save(Note note) throws IOException {
  GsonBuilder gsonBuilder = new GsonBuilder();
  gsonBuilder.setPrettyPrinting();
  Gson gson = gsonBuilder.create();
  String json = gson.toJson(note);

  FileObject rootDir = getRootDir();

  FileObject noteDir = rootDir.resolveFile(note.id(), NameScope.CHILD);

  if (!noteDir.exists()) {
    noteDir.createFolder();
  }
  if (!isDirectory(noteDir)) {
    throw new IOException(noteDir.getName().toString() + " is not a directory");
  }

  FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
  // false means not appending. creates file if not exists
  OutputStream out = noteJson.getContent().getOutputStream(false);
  out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
  out.close();
  noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}
 
Example 12
Project: common-vfs2-nfs   File: Main.java   Source Code and License 6 votes vote down vote up
public static void main(String[] args) {
	try {
		FileSystemManager fileSystemManager = VFS.getManager();
		
		FileObject fileObject;
		String path = "";
        fileObject = fileSystemManager.resolveFile("nfs://10.0.202.122//opt/glog/a.txt");
        if (fileObject == null) {
            throw new IOException("File cannot be resolved: " + path);
        }
        if (!fileObject.exists()) {
            throw new IOException("File does not exist: " + path);
        }
        System.out.println(fileObject.getName().getPath());
        BufferedReader stream = new BufferedReader(new InputStreamReader(fileObject.getContent().getInputStream(), "utf-8"));
       	String line = null;
       	while((line = stream.readLine()) != null) {
       		System.out.println(line);
       	}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 13
Project: motu   File: GsiFtpFileObject.java   Source Code and License 6 votes vote down vote up
/**
 * Renames the file.
 * 
 * @param newfile the newfile
 * 
 * @throws Exception the exception
 */
@Override
protected void doRename(FileObject newfile) throws Exception {
    boolean ok = true;
    final GridFTPClient ftpClient = ftpFs.getClient();
    try {
        String oldName = getName().getPath();
        String newName = newfile.getName().getPath();
        ftpClient.rename(oldName, newName);
    } catch (IOException ioe) {
        ok = false;
    } catch (ServerException e) {
        ok = false;
    } finally {
        ftpFs.putClient(ftpClient);
    }

    if (!ok) {
        throw new FileSystemException("vfs.provider.gsiftp/rename-file.error", new Object[] { getName().toString(), newfile });
    }
    this.fileInfo = null;
    children = EMPTY_FTP_FILE_MAP;
}
 
Example 14
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the uri as input stream.
 * 
 * @param uri the uri
 * 
 * @return the uri as input stream
 * 
 * @throws MotuException the motu exception
 */
public InputStream getUriAsInputStream(String uri) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("getUriAsInputStream(String) - entering");
    }

    InputStream in = null;
    try {

        FileObject fileObject = resolveFile(uri);
        if (fileObject != null) {
            in = fileObject.getContent().getInputStream();
        }
    } catch (IOException e) {
        LOG.error("getUriAsInputStream(String)", e);

        throw new MotuException(ErrorType.NETCDF_LOADING, String.format("'%s' uri file has not be found", uri), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("getUriAsInputStream(String) - exiting");
    }
    return in;
}
 
Example 15
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Delete directory.
 * 
 * @param path the path
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean deleteDirectory(String path) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteDirectory(String) - entering");
    }

    StringBuffer stringBuffer = new StringBuffer();
    stringBuffer.append(path);

    if (!(path.endsWith("/") || path.endsWith("\\"))) {
        stringBuffer.append("/");
    }
    FileObject pathToDelete = resolveFile(stringBuffer.toString());
    boolean returnboolean = deleteDirectory(pathToDelete);
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteDirectory(String) - exiting");
    }
    return returnboolean;

}
 
Example 16
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Delete all descendents of this file that match a selector.
 * 
 * @param file the file
 * @param selector the selector
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean delete(FileObject file, FileSelector selector) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("delete(FileObject, FileSelector) - entering");
    }

    int deleted = 0;
    try {
        if (file.exists()) {
            deleted = file.delete(selector);
        }
    } catch (FileSystemException e) {
        LOG.error("delete(FileObject, FileSelector)", e);

        // throw new MotuException(String.format("Unable to copy file '%s' to '%s'",
        // foSrc.getURL().toString(), foDest.getURL().toString()), e);
        throw new MotuException(ErrorType.NETCDF_LOADING, String.format("Unable to delete '%s'", file.getName().toString()), e);
    }
    boolean returnboolean = (deleted > 0);
    if (LOG.isDebugEnabled()) {
        LOG.debug("delete(FileObject, FileSelector) - exiting");
    }
    return returnboolean;
}
 
Example 17
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Copy file.
 * 
 * @param from the from
 * @param to the to
 * 
 * @throws MotuException the motu exception
 */
public void copyFile(String from, String to) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String) - entering");
    }

    // FileObject originBase = fsManager.resolveFile(uri, opts);
    // fsManager.setBaseFile(originBase);

    FileObject src = resolveFile(from);
    FileObject dest = resolveFile(to);
    copyFile(src, dest);

    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String) - exiting");
    }
}
 
Example 18
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Copy file.
 * 
 * @param from the from
 * @param to the to
 * @param userFrom the user from
 * @param pwdFrom the pwd from
 * @param userTo the user to
 * @param pwdTo the pwd to
 * 
 * @throws MotuException the motu exception
 */
public void copyFile(String from, String to, String userFrom, String pwdFrom, String userTo, String pwdTo) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String, String, String, String, String) - entering");
    }

    opts = null;
    if (!StringUtils.isNullOrEmpty(userFrom)) {
        opts = setUserInfo(userFrom, pwdFrom);
    }
    FileObject src = resolveFile(from, opts);

    opts = null;
    if (!StringUtils.isNullOrEmpty(userTo)) {
        opts = setUserInfo(userTo, pwdTo);
    }

    FileObject dest = resolveFile(to, opts);

    copyFile(src, dest);

    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String, String, String, String, String) - exiting");
    }
}
 
Example 19
Project: motu   File: VFSManager.java   Source Code and License 6 votes vote down vote up
/**
 * Refresh ftp cache.
 * 
 * @param fileObject the file object
 * @throws FileSystemException
 */
public void refreshFtpCache(FileObject fileObject) throws FileSystemException {

    if (fileObject == null) {
        return;
    }

    if (!(fileObject.getFileSystem() instanceof FtpFileSystem)) {
        return;
    }
    if (fileObject.exists()) {
        return;
    }
    FileObject fileObjectParent = fileObject.getParent();
    if (fileObjectParent == null) {
        return;
    }

    fileObjectParent.getType(); // force to attach : needed for force refresh
    fileObjectParent.refresh();

}
 
Example 20
Project: motu   File: FileCatalogLoader.java   Source Code and License 6 votes vote down vote up
/**
 * Gets the uri as input stream.
 * 
 * @param uri the uri
 * 
 * @return the uri as input stream
 * 
 * @throws MotuException the motu exception
 */
public static InputStream getUriAsInputStream(String uri) throws MotuException {
    InputStream in = null;
    try {

        in = ConfigLoader.getInstance().getAsStream(uri);
        if (in == null) {
            FileObject fileObject = resolveFile(uri);
            if (fileObject != null) {
                in = fileObject.getContent().getInputStream();
            }
        }
    } catch (IOException e) {
        throw new MotuException(ErrorType.LOADING_CATALOG, String.format("'%s' uri file has not be found", uri), e);
    }
    return in;
}
 
Example 21
Project: spring-boot-jar-resources   File: JarUtils.java   Source Code and License 6 votes vote down vote up
@SneakyThrows
private static File copyToDir(FileObject jarredFile, File destination, boolean retryIfImaginary) {
    switch (jarredFile.getType()) {
        case FILE:
            return copyFileToDir(jarredFile, destination);
        case FOLDER:
            return copyDirToDir(jarredFile, destination);
        case IMAGINARY:
            if (retryIfImaginary) {
                log.debug("Imaginary file found, retrying extraction");
                VFS.getManager().getFilesCache().removeFile(jarredFile.getFileSystem(), jarredFile.getName());
                FileObject newJarredFile = VFS.getManager().resolveFile(jarredFile.getName().getURI());
                return copyToDir(newJarredFile, destination, false);
            } else {
                log.debug("Imaginary file found after retry, abandoning retry");
            }

        default:
            throw new IllegalStateException("File Type not supported: " + jarredFile.getType());
    }
}
 
Example 22
Project: jbake-rtl-jalaali   File: BakeWatcher.java   Source Code and License 5 votes vote down vote up
/**
 * Starts watching the file system for changes to trigger a bake.
 *
 * @param res Commandline options
 * @param config Configuration settings
 */
public void start(final LaunchOptions res, CompositeConfiguration config) {
    try {
        FileSystemManager fsMan = VFS.getManager();
        FileObject listenPath = fsMan.resolveFile(res.getSource(), config.getString( ConfigUtil.Keys.CONTENT_FOLDER));

        System.out.println("Watching for changes in [" + res.getSource() + "]");
        DefaultFileMonitor monitor = new DefaultFileMonitor(new CustomFSChangeListener(res, config));
        monitor.setRecursive(true);
        monitor.addFile(listenPath);
        monitor.start();
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: waggle-dance   File: YamlFederatedMetaStoreStorage.java   Source Code and License 5 votes vote down vote up
public Federations unmarshall(String federationConfigLocation) {
  try (FileObject source = fsManager.resolveFile(federationConfigLocation)) {
    Federations federations = (Federations) yaml.load(source.getContent().getInputStream());
    if (federations == null) {
      return null;
    }
    validate(federations);
    return federations;
  } catch (IOException e) {
    throw new RuntimeException("Unable to initialize federations from '" + federationConfigLocation + "'", e);
  }
}
 
Example 24
Project: waggle-dance   File: YamlFederatedMetaStoreStorage.java   Source Code and License 5 votes vote down vote up
public void marshall(String federationConfigLocation, Federations federations) {
  try (FileObject target = fsManager.resolveFile(federationConfigLocation);
      Writer writer = new OutputStreamWriter(target.getContent().getOutputStream(), Charsets.UTF_8)) {
    yaml.dump(federations, writer);
  } catch (IOException e) {
    throw new RuntimeException("Unable to write federations to '" + federationConfigLocation + "'", e);
  }
}
 
Example 25
Project: yajsw   File: Cache.java   Source Code and License 5 votes vote down vote up
private void loadFiles(String key, YajswConfigurationImpl config,
		FileObject basef, FileObject cachef, boolean cacheLocal,
		DefaultFileSystemManager fsManager)
{
	try
	{
		String value = config.getString(key);
		List files = VFSUtils.resolveFiles(basef, value, fsManager);
		int count = 0;
		for (Iterator it = files.iterator(); it.hasNext();)
		{
			FileObject source = (FileObject) it.next();
			FileObject destination = loadFile(value, source, basef, cachef,
					cacheLocal, fsManager);
			if (destination != null)
			{
				config.getFileConfiguration().setProperty(
						key + "$" + count++,
						destination.getURL().getFile().substring(2));
				// System.out.println("set configuration "+key+" "+destination.getURL().getFile());
			}
		}
	}
	catch (Exception ex)
	{
		ex.printStackTrace();
	}
}
 
Example 26
Project: yajsw   File: Cache.java   Source Code and License 5 votes vote down vote up
private boolean fileChanged(FileObject source, FileObject destination)
{
	try
	{
		return !destination.exists()
				|| source.getContent().getLastModifiedTime() == 0
				|| source.getContent().getLastModifiedTime() != destination
						.getContent().getLastModifiedTime();
	}
	catch (FileSystemException e)
	{
		e.printStackTrace();
		return true;
	}
}
 
Example 27
Project: yajsw   File: JnlpSupport.java   Source Code and License 5 votes vote down vote up
public JnlpSupport(String file) throws ParserConfigurationException,
		SAXException, IOException
{
	FileObject fo = VFSUtils.resolveFile(".", file);
	if (fo == null || !fo.exists())
		throw new FileNotFoundException(file);
	InputStream in = fo.getContent().getInputStream();
	_doc = parseJnlp(in);
	in.close();
}
 
Example 28
Project: yajsw   File: FilePropertiesConfiguration.java   Source Code and License 5 votes vote down vote up
@Override
public URL locate(FileSystem fileSystem, FileLocator locator) {
	try {
		FileObject file = VFSUtils.resolveFile(_fileName);
		String base = VFSUtils.isLocal(file) ? new File(_fileName).getParent() : file.getParent().getURL().toString();
		return VFSUtils.resolveFile(base, locator.getFileName()).getURL();
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return null;
}
 
Example 29
Project: yajsw   File: VFSUtils.java   Source Code and License 5 votes vote down vote up
public static FileObject resolveFile(String base, String file)
		throws FileSystemException
{
	init();
	FileObject basef = null;
	if (base != null)
		basef = fsManager.resolveFile(new File("."), base);
	return resolveFile(basef, file);
}
 
Example 30
Project: yajsw   File: VFSUtils.java   Source Code and License 5 votes vote down vote up
public static long getLastModifiedTime(FileObject file)
{
	try
	{
		return file.getContent().getLastModifiedTime();
	}
	catch (FileSystemException e)
	{
		e.printStackTrace();
		return 0;
	}
}
 
Example 31
Project: yajsw   File: VFSUtils.java   Source Code and License 5 votes vote down vote up
public static FileObject resolveFile(FileObject basef, String file)
		throws FileSystemException
{
	init();
	if (basef != null)
		return fsManager.resolveFile(basef, file, opts);
	else
		return fsManager.resolveFile(file, opts);
}
 
Example 32
Project: yajsw   File: VFSUtils.java   Source Code and License 5 votes vote down vote up
public static boolean isLocal(FileObject f)
{
	if (f instanceof OnCallRefreshFileObject)
		try
		{
			return f.getContent().getFile() instanceof LocalFile;
		}
		catch (FileSystemException e)
		{
			e.printStackTrace();
		}
	return f instanceof LocalFile;
}
 
Example 33
Project: yajsw   File: JarBuilder.java   Source Code and License 5 votes vote down vote up
private void addFile(FileObject f, String name, ZipOutputStream out) throws IOException
{
	InputStream in = f.getContent().getInputStream();
	out.putNextEntry(new ZipEntry(name));
	
	byte[] buf = new byte[1024];
	int len;
       while ((len = in.read(buf)) > 0) {
           out.write(buf, 0, len);
       }
       // Complete the entry
       out.closeEntry();
       in.close();		
}
 
Example 34
Project: mycore   File: MCRMetadataStore.java   Source Code and License 5 votes vote down vote up
/**
 * Stores a newly created document under the given ID.
 * 
 * @param xml
 *            the XML document to be stored
 * @param id
 *            the ID under which the document should be stored
 * @return the stored metadata object
 */
public MCRStoredMetadata create(MCRContent xml, int id) throws IOException, JDOMException {
    if (id <= 0) {
        throw new MCRException("ID of metadata object must be a positive integer");
    }
    FileObject fo = getSlot(id);
    if (fo.exists()) {
        String msg = "Metadata object with ID " + id + " already exists in store";
        throw new MCRException(msg);
    }
    fo.createFile();
    MCRStoredMetadata meta = buildMetadataObject(fo, id);
    meta.create(xml);
    return meta;
}
 
Example 35
Project: mycore   File: MCRMetadataStore.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the metadata stored under the given ID, or null
 * 
 * @param id
 *            the ID of the XML document
 * @return the metadata stored under that ID, or null when there is no such
 *         metadata object
 */
public MCRStoredMetadata retrieve(int id) throws IOException {
    FileObject fo = getSlot(id);
    if (!fo.exists()) {
        return null;
    } else {
        return buildMetadataObject(fo, id);
    }
}
 
Example 36
Project: mycore   File: MCRFileCollection.java   Source Code and License 5 votes vote down vote up
private void readAdditionalData() throws IOException {
    FileObject src = VFS.getManager().resolveFile(fo, dataFile);
    if (!src.exists()) {
        LOGGER.warn("Metadata file is missing, repairing metadata...");
        data = new Element("collection");
        new Document(data);
        repairMetadata();
    }
    try {
        data = new MCRVFSContent(src).asXML().getRootElement();
    } catch (JDOMException | SAXException e) {
        throw new IOException(e);
    }
}
 
Example 37
Project: mycore   File: MCRStore.java   Source Code and License 5 votes vote down vote up
/**
 * Deletes the data stored in the given file object from the store
 * 
 * @param fo
 *            the file object to be deleted
 */
void delete(FileObject fo) throws IOException {
    FileObject parent = fo.getParent();
    fo.delete(Selectors.SELECT_ALL);

    while (!parent.equals(baseDirectory)) {
        final FileObject[] children = parent.getChildren();
        if (children.length > 0) {
            break;
        }
        fo = parent;
        parent = fo.getParent();
        fo.delete();
    }
}
 
Example 38
Project: mycore   File: MCRDirectory.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the MCRFile or MCRDirectory that is represented by the given
 * FileObject, which is a direct child of the directory FileObject this
 * MCRDirectory is stored in.
 * 
 * @return an MCRFile or MCRDirectory child
 */
@Override
protected MCRStoredNode buildChildNode(FileObject fo) throws IOException {
    if (fo == null) {
        return null;
    }

    Element childData = getChildData(fo.getName().getBaseName());
    if (fo.getType().equals(FileType.FILE)) {
        return new MCRFile(this, fo, childData);
    } else {
        return new MCRDirectory(this, fo, childData);
    }
}
 
Example 39
Project: mycore   File: MCRFileStore.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the file collection stored under the given ID, or null when no
 * collection is stored for the given ID.
 * 
 * @param id
 *            the file collection's ID
 * @return the file collection with the given ID, or null
 */
public MCRFileCollection retrieve(int id) throws IOException {
    FileObject fo = getSlot(id);
    if (!fo.exists()) {
        return null;
    } else {
        return new MCRFileCollection(this, id);
    }
}
 
Example 40
Project: mycore   File: MCRVersionedMetadata.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new metadata object both in the local store and in the SVN
 * repository
 *
 * @param store
 *            the store this object is stored in
 * @param fo
 *            the file storing the data in the local filesystem
 * @param id
 *            the id of the metadata object
 */
MCRVersionedMetadata(MCRMetadataStore store, FileObject fo, int id, String docType, boolean deleted) {
    super(store, fo, id, docType);
    super.deleted = deleted;
    revision = () -> {
        try {
            // 1. current revision, 2. deleted revision, empty()
            return Optional.ofNullable(Optional.ofNullable(getStore().getRepository().info(getFilePath(), -1))
                .map(SVNDirEntry::getRevision).orElseGet(this::getLastRevision));
        } catch (SVNException e) {
            LOGGER.error("Could not get last revision of {}_{}", getStore().getID(), id, e);
            return Optional.empty();
        }
    };
}
 
Example 41
Project: mycore   File: MCRStoredNode.java   Source Code and License 5 votes vote down vote up
/**
 * Renames this node.
 * 
 * @param name
 *            the new file name
 */
public void renameTo(String name) throws IOException {
    FileObject fNew = VFS.getManager().resolveFile(fo.getParent(), name);
    fo.moveTo(fNew);
    fo = fNew;
    fo.getContent().setLastModifiedTime(System.currentTimeMillis());
    data.setAttribute(NAME_ATT, name);
    getRoot().saveAdditionalData();
}
 
Example 42
Project: mycore   File: MCRNode.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the number of child nodes of this node.
 * 
 * @return the number of child nodes of this node.
 */
public int getNumChildren() throws IOException {
    FileObject father = getFather();
    if (father == null) {
        return 0;
    } else {
        return father.getChildren().length;
    }
}
 
Example 43
Project: mycore   File: MCRCStoreVFS.java   Source Code and License 5 votes vote down vote up
@Override
protected void doDeleteContent(String storageId) throws Exception {
    FileObject targetObject = fsManager.resolveFile(getBase(), storageId);
    LOGGER.debug("Delete fired on: {}", targetObject);
    LOGGER.debug("targetObject.class = {}", targetObject.getClass().getName());
    if (targetObject.delete()) {
        LOGGER.debug("Delete of {} was successful.", targetObject);
    } else {
        LOGGER.warn("Delete of {} was NOT successful (w/o errors given).", targetObject);
    }
}
 
Example 44
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 5 votes vote down vote up
protected FileObject getRootDir() throws IOException {
  FileObject rootDir = fsManager.resolveFile(getPath("/"));

  if (!rootDir.exists()) {
    throw new IOException("Root path does not exists");
  }

  if (!isDirectory(rootDir)) {
    throw new IOException("Root path is not a directory");
  }

  return rootDir;
}
 
Example 45
Project: mycore   File: MCRCStoreVFS.java   Source Code and License 5 votes vote down vote up
@Override
public void init(String storeId) {
    super.init(storeId);

    uri = MCRConfiguration.instance().getString(storeConfigPrefix + "URI");
    String check = MCRConfiguration.instance().getString(storeConfigPrefix + "StrictHostKeyChecking", "no");

    try {
        fsManager = VFS.getManager();

        opts = new FileSystemOptions();
        SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, check);

        FileObject baseDir = getBase();

        // Create a folder, if it does not exist or throw an
        // exception, if baseDir is not a folder
        baseDir.createFolder();

        if (!baseDir.isWriteable()) {
            String msg = "Content store base directory is not writeable: " + uri;
            throw new MCRConfigurationException(msg);
        }
    } catch (FileSystemException ex) {
        throw new MCRException(ex.getCode(), ex);
    }
}
 
Example 46
Project: mycore   File: MCRCStoreVFS.java   Source Code and License 5 votes vote down vote up
@Override
protected boolean exists(MCRFile file) {
    try {
        FileObject targetObject = fsManager.resolveFile(getBase(), file.getStorageID());
        return targetObject.exists();
    } catch (FileSystemException e) {
        LOGGER.error(e);
        return false;
    }
}
 
Example 47
Project: esb-connector-file   File: FileMove.java   Source Code and License 5 votes vote down vote up
/**
 * Move the files
 *
 * @param source      Location of the file
 * @param destination Destination of the file
 * @return return a resultStatus
 */
private boolean moveFile(String source, String destination, MessageContext messageContext,
                         boolean includeParentDirectory, String filePattern) {
    boolean resultStatus = false;
    StandardFileSystemManager manager = null;
    try {
        manager = FileConnectorUtils.getManager();
        // Create remote object
        FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
        if (remoteFile.exists()) {
            if (remoteFile.getType() == FileType.FILE) {
                fileMove(destination, remoteFile, messageContext, manager);
            } else {
                folderMove(source, destination, filePattern, includeParentDirectory, messageContext, manager);
            }
            resultStatus = true;
            if (log.isDebugEnabled()) {
                log.debug("File move completed from " + source + " to " + destination);
            }
        } else {
            log.error("The file/folder location does not exist.");
            resultStatus = false;
        }
    } catch (IOException e) {
        handleException("Unable to move a file/folder.", e, messageContext);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
    return resultStatus;
}
 
Example 48
Project: esb-connector-file   File: FileMove.java   Source Code and License 5 votes vote down vote up
/**
 * Move the folder
 *
 * @param destination            New location of the folder
 * @param source                 Location of the folder
 * @param messageContext         The message context that is processed by a handler in the handle method
 * @param includeParentDirectory Boolean type
 * @param manager                Standard file system manager
 */
private void folderMove(String source, String destination, String filePattern, boolean includeParentDirectory,
                        MessageContext messageContext, StandardFileSystemManager manager) throws IOException {
    FileObject remoteFile = manager.resolveFile(source, FileConnectorUtils.init(messageContext));
    FileObject file = manager.resolveFile(destination, FileConnectorUtils.init(messageContext));
    if (StringUtils.isNotEmpty(filePattern)) {
        FileObject[] children = remoteFile.getChildren();
        for (FileObject child : children) {
            if (child.getType() == FileType.FILE) {
                moveFileWithPattern(child, destination, filePattern, manager, messageContext);
            } else if (child.getType() == FileType.FOLDER) {
                String newSource = source + File.separator + child.getName().getBaseName();
                folderMove(newSource, destination, filePattern, includeParentDirectory, messageContext, manager);
            }
        }
    } else if (includeParentDirectory) {
        file = manager.resolveFile(destination + File.separator + remoteFile.getName().getBaseName(),
                FileConnectorUtils.init(messageContext));
        file.createFolder();
        remoteFile.moveTo(file);
    } else {
        if (!file.exists()) {
            file.createFolder();
        }
        remoteFile.moveTo(file);
        remoteFile.createFolder();
    }
}
 
Example 49
Project: geeCommerce-Java-Shop-Software-and-PIM   File: DefaultVfsHelper.java   Source Code and License 5 votes vote down vote up
@Override
public void close(FileObject fileObject) {
    try {
        fileObject.close();
    } catch (FileSystemException e) {
        e.printStackTrace();
    }
}
 
Example 50
Project: motu   File: VFSManager.java   Source Code and License 5 votes vote down vote up
/**
 * Resolve file.
 * 
 * @param uri the uri
 * 
 * @return the file object
 * 
 * @throws MotuException the motu exception
 */
public FileObject resolveFile(final String uri) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(String) - entering");
    }

    FileObject returnFileObject = resolveFile(uri, this.opts);
    if (LOG.isDebugEnabled()) {
        LOG.debug("resolveFile(String) - exiting");
    }
    return returnFileObject;
}
 
Example 51
Project: motu   File: VFSManager.java   Source Code and License 5 votes vote down vote up
/**
 * Delete a file.
 * 
 * @param file the file to delete
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean deleteFile(String file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(String) - entering");
    }

    FileObject fileToDelete = resolveFile(file);
    boolean returnboolean = deleteFile(fileToDelete);
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(String) - exiting");
    }
    return returnboolean;
}
 
Example 52
Project: motu   File: VFSManager.java   Source Code and License 5 votes vote down vote up
/**
 * Delete directory ´┐Żnd all descendents of the file.
 * 
 * @param file the file
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean deleteDirectory(FileObject file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteDirectory(FileObject) - entering");
    }

    boolean returnboolean = delete(file, Selectors.SELECT_ALL);
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteDirectory(FileObject) - exiting");
    }
    return returnboolean;
}
 
Example 53
Project: motu   File: VFSManager.java   Source Code and License 5 votes vote down vote up
/**
 * Delete the file repsented by the file parameter.
 * 
 * @param file the file
 * 
 * @return true, if successful
 * @throws MotuException
 */
public boolean deleteFile(FileObject file) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(FileObject) - entering");
    }

    boolean deleted = false;
    try {

        if (file.exists()) {
            if (file.getType() != FileType.FILE) {
                throw new MotuException(
                        ErrorType.NETCDF_LOADING,
                        String.format("Delete file '%s' is rejected: it is a folder. ", file.getName().toString()));
            }

            deleted = file.delete();
        }
    } catch (FileSystemException e) {
        LOG.error("deleteFile(FileObject)", e);

        // throw new MotuException(String.format("Unable to copy file '%s' to '%s'",
        // foSrc.getURL().toString(), foDest.getURL().toString()), e);
        throw new MotuException(ErrorType.NETCDF_LOADING, String.format("Unable to delete '%s'", file.getName().toString()), e);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("deleteFile(FileObject) - exiting");
    }
    return deleted;
}
 
Example 54
Project: motu   File: VFSManager.java   Source Code and License 5 votes vote down vote up
/**
 * Copy file.
 * 
 * @param from the from
 * @param to the to
 * @param optsFrom the opts from
 * @param optsTo the opts to
 * 
 * @throws MotuException the motu exception
 */
public void copyFile(String from, String to, FileSystemOptions optsFrom, FileSystemOptions optsTo) throws MotuException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String, FileSystemOptions, FileSystemOptions) - entering");
    }

    FileObject src = resolveFile(from, optsFrom);
    FileObject dest = resolveFile(to, optsTo);
    copyFile(src, dest);

    if (LOG.isDebugEnabled()) {
        LOG.debug("copyFile(String, String, FileSystemOptions, FileSystemOptions) - exiting");
    }
}
 
Example 55
Project: spring-boot-jar-resources   File: JarUtils.java   Source Code and License 5 votes vote down vote up
@SneakyThrows
private static File getFromJar(Resource resource, String extractPath) {
    Preconditions.checkArgument(extractPath != null, "Extract Path cannot be null");
    FileObject file = VFS.getManager().resolveFile(maybeFixUri(resource));
    File extractDir;
    extractDir = new File(extractPath);
    if (!extractDir.exists() || !extractDir.isDirectory()) {
        FileUtils.forceMkdir(extractDir);
        log.debug("TEMP EXTRACT DIR CREATED {}", extractDir.getAbsolutePath());
    }
    return copyToDir(file, extractDir);
}
 
Example 56
Project: spring-boot-jar-resources   File: JarUtils.java   Source Code and License 5 votes vote down vote up
@SneakyThrows
private static File copyDirToDir(FileObject jarredDir, File destination) {
    File tempDir = new File(destination, jarredDir.getName().getBaseName());
    createDir(tempDir);
    Arrays.stream(jarredDir.getChildren())
            .forEach(fileObject -> copyToDir(fileObject, tempDir));
    return tempDir;
}
 
Example 57
Project: spring-boot-jar-resources   File: JarUtils.java   Source Code and License 5 votes vote down vote up
@SneakyThrows
private static File copyFileToDir(FileObject jarredFile, File destination) {
    File tempFile = new File(destination, jarredFile.getName().getBaseName());
    createFile(tempFile);
    log.info("TEMP FILE CREATED {}", tempFile.getAbsolutePath());
    FileUtils.copyInputStreamToFile(jarredFile.getContent().getInputStream(), tempFile);
    return tempFile;
}
 
Example 58
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 5 votes vote down vote up
private boolean isDirectory(FileObject fo) throws IOException {
  if (fo == null) return false;
  if (fo.getType() == FileType.FOLDER) {
    return true;
  } else {
    return false;
  }
}
 
Example 59
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 5 votes vote down vote up
@Override
public List<NoteInfo> list() throws IOException {
  FileObject rootDir = getRootDir();

  FileObject[] children = rootDir.getChildren();

  List<NoteInfo> infos = new LinkedList<NoteInfo>();
  for (FileObject f : children) {
    String fileName = f.getName().getBaseName();
    if (f.isHidden()
        || fileName.startsWith(".")
        || fileName.startsWith("#")
        || fileName.startsWith("~")) {
      // skip hidden, temporary files
      continue;
    }

    if (!isDirectory(f)) {
      // currently single note is saved like, [NOTE_ID]/note.json.
      // so it must be a directory
      continue;
    }

    NoteInfo info = null;

    try {
      info = getNoteInfo(f);
      if (info != null) {
        infos.add(info);
      }
    } catch (IOException e) {
      logger.error("Can't read note " + f.getName().toString(), e);
    }
  }

  return infos;
}
 
Example 60
Project: incubator-zeppelin-druid   File: VFSNotebookRepo.java   Source Code and License 5 votes vote down vote up
private Note getNote(FileObject noteDir) throws IOException {
    if (!isDirectory(noteDir)) {
      throw new IOException(noteDir.getName().toString() + " is not a directory");
    }

    FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
    if (!noteJson.exists()) {
      throw new IOException(noteJson.getName().toString() + " not found");
    }

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();

    FileContent content = noteJson.getContent();
    InputStream ins = content.getInputStream();
    String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
    ins.close();

    Note note = gson.fromJson(json, Note.class);
//    note.setReplLoader(replLoader);
//    note.jobListenerFactory = jobListenerFactory;

    for (Paragraph p : note.getParagraphs()) {
      if (p.getStatus() == Status.PENDING || p.getStatus() == Status.RUNNING) {
        p.setStatus(Status.ABORT);
      }
    }

    return note;
  }