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();
        }
    };
}