Example usage for org.apache.commons.vfs2 FileObject createFile

List of usage examples for org.apache.commons.vfs2 FileObject createFile

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject createFile.

Prototype

void createFile() throws FileSystemException;

Source Link

Document

Creates this file, if it does not exist.

Usage

From source file:org.apache.synapse.commons.vfs.VFSUtils.java

public synchronized static void markFailRecord(FileSystemManager fsManager, FileObject fo) {

    // generate a random fail value to ensure that there are no two parties
    // processing the same file
    Random random = new Random();
    byte[] failValue = (Long.toString((new Date()).getTime())).getBytes();

    try {//from w  ww  .  j av a2 s. c om
        String fullPath = fo.getName().getURI();
        int pos = fullPath.indexOf("?");
        if (pos != -1) {
            fullPath = fullPath.substring(0, pos);
        }
        FileObject failObject = fsManager.resolveFile(fullPath + ".fail");
        if (!failObject.exists()) {
            failObject.createFile();
        }

        // write a lock file before starting of the processing, to ensure that the
        // item is not processed by any other parties

        OutputStream stream = failObject.getContent().getOutputStream();
        try {
            stream.write(failValue);
            stream.flush();
            stream.close();
        } catch (IOException e) {
            failObject.delete();
            log.error("Couldn't create the fail file before processing the file " + maskURLPassword(fullPath),
                    e);
        } finally {
            failObject.close();
        }
    } catch (FileSystemException fse) {
        log.error("Cannot get the lock for the file : " + maskURLPassword(fo.getName().getURI())
                + " before processing");
    }
}

From source file:org.apache.synapse.transport.vfs.VFSTransportSender.java

private void writeFile(MessageContext msgCtx, VFSOutTransportInfo vfsOutInfo) throws AxisFault {

    FileSystemOptions fso = null;/*from w w w.  jav  a 2s. com*/
    try {
        fso = VFSUtils.attachFileSystemOptions(vfsOutInfo.getOutFileSystemOptionsMap(), fsManager);
    } catch (Exception e) {
        log.error("Error while attaching VFS file system properties. " + e.getMessage());
    }

    if (vfsOutInfo != null) {
        FileObject replyFile = null;
        try {

            boolean wasError = true;
            int retryCount = 0;
            int maxRetryCount = vfsOutInfo.getMaxRetryCount();
            long reconnectionTimeout = vfsOutInfo.getReconnectTimeout();
            boolean append = vfsOutInfo.isAppend();

            while (wasError) {

                try {
                    retryCount++;
                    replyFile = fsManager.resolveFile(vfsOutInfo.getOutFileURI(), fso);

                    if (replyFile == null) {
                        log.error("replyFile is null");
                        throw new FileSystemException("replyFile is null");
                    }
                    wasError = false;

                } catch (FileSystemException e) {
                    log.error("cannot resolve replyFile", e);
                    if (maxRetryCount <= retryCount) {
                        handleException("cannot resolve replyFile repeatedly: " + e.getMessage(), e);
                    }
                }

                if (wasError) {
                    try {
                        Thread.sleep(reconnectionTimeout);
                    } catch (InterruptedException e2) {
                        e2.printStackTrace();
                    }
                }
            }

            //If the reply folder does not exists create the folder structure
            if (vfsOutInfo.isForceCreateFolder()) {
                String strPath = vfsOutInfo.getOutFileURI();
                int iIndex = strPath.indexOf("?");
                if (iIndex > -1) {
                    strPath = strPath.substring(0, iIndex);
                }
                //Need to add a slash otherwise vfs consider this as a file
                if (!strPath.endsWith("/") || !strPath.endsWith("\\")) {
                    strPath += "/";
                }
                FileObject replyFolder = fsManager.resolveFile(strPath, fso);
                if (!replyFolder.exists()) {
                    replyFile.createFolder();
                }
            }

            if (replyFile.exists()) {
                if (replyFile.getType() == FileType.FOLDER) {
                    // we need to write a file containing the message to this folder
                    FileObject responseFile = fsManager.resolveFile(replyFile,
                            VFSUtils.getFileName(msgCtx, vfsOutInfo));

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(responseFile, vfsOutInfo, fso);
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, responseFile, fso);
                    } else {
                        if (!responseFile.exists()) {
                            responseFile.createFile();
                        }
                        populateResponseFile(responseFile, msgCtx, append, false, fso);
                    }

                } else if (replyFile.getType() == FileType.FILE) {

                    // if file locking is not disabled acquire the lock
                    // before uploading the file
                    if (vfsOutInfo.isFileLockingEnabled()) {
                        acquireLockForSending(replyFile, vfsOutInfo, fso);
                        populateResponseFile(replyFile, msgCtx, append, true, fso);
                        VFSUtils.releaseLock(fsManager, replyFile, fso);
                    } else {
                        populateResponseFile(replyFile, msgCtx, append, false, fso);
                    }

                } else {
                    handleException("Unsupported reply file type : " + replyFile.getType() + " for file : "
                            + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()));
                }
            } else {
                // if file locking is not disabled acquire the lock before uploading the file
                if (vfsOutInfo.isFileLockingEnabled()) {
                    acquireLockForSending(replyFile, vfsOutInfo, fso);
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, true, fso);
                    VFSUtils.releaseLock(fsManager, replyFile, fso);
                } else {
                    replyFile.createFile();
                    populateResponseFile(replyFile, msgCtx, append, false, fso);
                }
            }
        } catch (FileSystemException e) {
            handleException(
                    "Error resolving reply file : " + VFSUtils.maskURLPassword(vfsOutInfo.getOutFileURI()), e);
        } finally {
            if (replyFile != null) {
                try {/*
                     if (fsManager != null && replyFile.getParent() != null && replyFile.getParent().getFileSystem() != null) {
                     fsManager.closeFileSystem(replyFile.getParent().getFileSystem());
                     }*/
                    replyFile.close();
                } catch (FileSystemException ignore) {
                }
            }
        }
    } else {
        handleException("Unable to determine out transport information to send message");
    }
}

From source file:org.datacleaner.actions.DownloadFilesActionListener.java

@Override
protected FileObject[] doInBackground() throws Exception {
    for (int i = 0; i < _urls.length; i++) {
        final String url = _urls[i];
        final FileObject file = _files[i];

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {/*  ww w .j  a v  a2  s .c  o  m*/
            byte[] buffer = new byte[1024];

            final HttpGet method = new HttpGet(url);

            if (!_cancelled) {
                final HttpResponse response = _httpClient.execute(method);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new InvalidHttpResponseException(url, response);
                }

                final HttpEntity responseEntity = response.getEntity();
                final long expectedSize = responseEntity.getContentLength();
                if (expectedSize > 0) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize);
                        }
                    });
                }

                inputStream = responseEntity.getContent();

                if (!file.exists()) {
                    file.createFile();
                }
                outputStream = file.getContent().getOutputStream();

                long bytes = 0;
                for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream
                        .read(buffer)) {
                    if (_cancelled) {
                        break;
                    }
                    outputStream.write(buffer, 0, numBytes);
                    bytes += numBytes;

                    final long totalBytes = bytes;
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes);
                        }
                    });
                }

                if (!_cancelled) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setFinished(file.getName().getBaseName());
                        }
                    });
                }
            }
        } catch (IOException e) {
            logger.debug("IOException occurred while downloading files", e);
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not close input stream: " + e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not flush & close output stream: " + e.getMessage(), e);
                }
            }

            _httpClient.close();
        }

        if (_cancelled) {
            logger.info("Deleting non-finished download-file '{}'", file);
            file.delete();
        }
    }

    return _files;
}

From source file:org.efaps.db.store.VFSStoreResource.java

/**
 * The method writes the context (from the input stream) to a temporary file
 * (same file URL, but with extension {@link #EXTENSION_TEMP}).
 *
 * @param _in   input stream defined the content of the file
 * @param _size length of the content (or negative meaning that the length
 *              is not known; then the content gets the length of readable
 *              bytes from the input stream)
 * @param _fileName name of the file//from ww w.  j  a va 2 s . c o m
 * @return size of the created temporary file object
 * @throws EFapsException on error
 */
@Override
public long write(final InputStream _in, final long _size, final String _fileName) throws EFapsException {
    try {
        long size = _size;
        final FileObject tmpFile = this.manager.resolveFile(this.manager.getBaseFile(),
                this.storeFileName + VFSStoreResource.EXTENSION_TEMP);
        if (!tmpFile.exists()) {
            tmpFile.createFile();
        }
        final FileContent content = tmpFile.getContent();
        OutputStream out = content.getOutputStream(false);
        if (getCompress().equals(Compress.GZIP)) {
            out = new GZIPOutputStream(out);
        } else if (getCompress().equals(Compress.ZIP)) {
            out = new ZipOutputStream(out);
        }

        // if size is unkown!
        if (_size < 0) {
            int length = 1;
            size = 0;
            while (length > 0) {
                length = _in.read(this.buffer);
                if (length > 0) {
                    out.write(this.buffer, 0, length);
                    size += length;
                }
            }
        } else {
            Long length = _size;
            while (length > 0) {
                final int readLength = length.intValue() < this.buffer.length ? length.intValue()
                        : this.buffer.length;
                _in.read(this.buffer, 0, readLength);
                out.write(this.buffer, 0, readLength);
                length -= readLength;
            }
        }
        if (getCompress().equals(Compress.GZIP) || getCompress().equals(Compress.ZIP)) {
            out.close();
        }
        tmpFile.close();
        setFileInfo(_fileName, size);
        return size;
    } catch (final IOException e) {
        VFSStoreResource.LOG.error("write of content failed", e);
        throw new EFapsException(VFSStoreResource.class, "write.IOException", e);
    }

}

From source file:org.eobjects.datacleaner.actions.DownloadFilesActionListener.java

@Override
protected FileObject[] doInBackground() throws Exception {
    for (int i = 0; i < _urls.length; i++) {
        final String url = _urls[i];
        final FileObject file = _files[i];

        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {//  www. j a v  a 2 s . c o  m
            byte[] buffer = new byte[1024];

            final HttpGet method = new HttpGet(url);

            if (!_cancelled) {
                final HttpResponse response = _httpClient.execute(method);

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new InvalidHttpResponseException(url, response);
                }

                final HttpEntity responseEntity = response.getEntity();
                final long expectedSize = responseEntity.getContentLength();
                if (expectedSize > 0) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setExpectedSize(file.getName().getBaseName(), expectedSize);
                        }
                    });
                }

                inputStream = responseEntity.getContent();

                if (!file.exists()) {
                    file.createFile();
                }
                outputStream = file.getContent().getOutputStream();

                long bytes = 0;
                for (int numBytes = inputStream.read(buffer); numBytes != -1; numBytes = inputStream
                        .read(buffer)) {
                    if (_cancelled) {
                        break;
                    }
                    outputStream.write(buffer, 0, numBytes);
                    bytes += numBytes;

                    final long totalBytes = bytes;
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setProgress(file.getName().getBaseName(), totalBytes);
                        }
                    });
                }

                if (!_cancelled) {
                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _downloadProgressWindow.setFinished(file.getName().getBaseName());
                        }
                    });
                }
            }
        } catch (IOException e) {
            logger.debug("IOException occurred while downloading files", e);
            throw e;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not close input stream: " + e.getMessage(), e);
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    logger.warn("Could not flush & close output stream: " + e.getMessage(), e);
                }
            }
        }

        if (_cancelled) {
            logger.info("Deleting non-finished download-file '{}'", file);
            file.delete();
        }
    }

    return _files;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public String createFile(String parentPath, String title, String type,
        SharedUserPortletParameters userParameters) {
    try {/*from   ww  w. j a v a  2  s  .com*/
        FileObject parent = cd(parentPath, userParameters);
        FileObject child = parent.resolveFile(title);
        if (!child.exists()) {
            if ("folder".equals(type)) {
                child.createFolder();
                log.info("folder " + title + " created");
            } else {
                child.createFile();
                log.info("file " + title + " created");
            }
            return child.getName().getPath();
        } else {
            log.info("file " + title + " already exists !");
        }
    } catch (FileSystemException e) {
        log.info("can't create file because of FileSystemException : " + e.getMessage(), e);
    }
    return null;
}

From source file:org.esupportail.portlet.filemanager.services.vfs.VfsAccessImpl.java

@Override
public boolean putFile(String dir, String filename, InputStream inputStream,
        SharedUserPortletParameters userParameters, UploadActionType uploadOption) {

    boolean success = false;
    FileObject newFile = null;

    try {/*from w  w w . j a  v  a 2  s . c o m*/
        FileObject folder = cd(dir, userParameters);
        newFile = folder.resolveFile(filename);
        if (newFile.exists()) {
            switch (uploadOption) {
            case ERROR:
                throw new EsupStockFileExistException();
            case OVERRIDE:
                newFile.delete();
                break;
            case RENAME_NEW:
                newFile = folder.resolveFile(this.getUniqueFilename(filename, "-new-"));
                break;
            case RENAME_OLD:
                newFile.moveTo(folder.resolveFile(this.getUniqueFilename(filename, "-old-")));
                break;
            }
        }
        newFile.createFile();

        OutputStream outstr = newFile.getContent().getOutputStream();

        FileCopyUtils.copy(inputStream, outstr);

        success = true;
    } catch (FileSystemException e) {
        log.info("can't upload file : " + e.getMessage(), e);
    } catch (IOException e) {
        log.warn("can't upload file : " + e.getMessage(), e);
    }

    if (!success && newFile != null) {
        // problem when uploading the file -> the file uploaded is corrupted
        // best is to delete it
        try {
            newFile.delete();
            log.debug("delete corrupted file after bad upload ok ...");
        } catch (Exception e) {
            log.debug("can't delete corrupted file after bad upload " + e.getMessage());
        }
    }

    return success;
}

From source file:org.geoserver.backuprestore.utils.BackupUtils.java

/**
 * Compress {@code sourceFolder} to the archive file {@code archiveFile}; both shall previously exist.
 * /* ww w .java  2s . c  om*/
 * @param sourceFolder
 * @param archiveFile
 * @throws IOException
 */
public static void compressTo(Resource sourceFolder, Resource archiveFile) throws IOException {
    // See https://commons.apache.org/proper/commons-vfs/filesystems.html
    // for the supported filesystems

    FileSystemManager manager = VFS.getManager();

    FileObject sourceDir = manager
            .createVirtualFileSystem(manager.resolveFile(sourceFolder.dir().getAbsolutePath()));

    try {
        if ("zip".equalsIgnoreCase(FileUtils.getExtension(archiveFile.path()))) {
            // apache VFS does not support ZIP as writable FileSystem

            OutputStream fos = archiveFile.out();

            // Create access to zip.
            ZipOutputStream zos = new ZipOutputStream(fos);

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            fos.close();
        } else {
            // Create access to archive.
            FileObject zipFile = manager.resolveFile(resolveArchiveURI(archiveFile));
            zipFile.createFile();
            ZipOutputStream zos = new ZipOutputStream(zipFile.getContent().getOutputStream());

            // add entry/-ies.
            for (FileObject sourceFile : sourceDir.getChildren()) {
                writeEntry(zos, sourceFile, null);
            }

            // Close streams
            zos.flush();
            zos.close();
            zipFile.close();
            manager.closeFileSystem(zipFile.getFileSystem());
        }
    } finally {
        manager.closeFileSystem(sourceDir.getFileSystem());
    }
}

From source file:org.mycore.datamodel.ifs2.MCRFileStoreTest.java

@Test
public void repairMetadata() throws Exception {
    MCRFileCollection col = getStore().create();
    Document xml1 = (Document) col.getMetadata().clone();
    col.repairMetadata();/* w w w  . j a v  a 2s. co m*/
    Document xml2 = (Document) col.getMetadata().clone();
    assertTrue(equals(xml1, xml2));

    MCRDirectory dir = col.createDir("foo");
    xml1 = (Document) col.getMetadata().clone();
    assertFalse(equals(xml1, xml2));
    dir.delete();
    xml1 = (Document) col.getMetadata().clone();
    assertTrue(equals(xml1, xml2));

    MCRDirectory dir2 = col.createDir("dir");
    MCRFile file1 = col.createFile("test1.txt");
    file1.setContent(new MCRStringContent("Test 1"));
    MCRFile readme = dir2.createFile("readme.txt");
    readme.setContent(new MCRStringContent("Hallo Welt!"));
    MCRFile file3 = col.createFile("test2.txt");
    file3.setContent(new MCRStringContent("Test 2"));
    file3.setLabel("de", "Die Testdatei");
    xml2 = (Document) col.getMetadata().clone();

    col.repairMetadata();
    xml1 = (Document) col.getMetadata().clone();
    assertTrue(equals(xml1, xml2));

    file3.clearLabels();
    xml2 = (Document) col.getMetadata().clone();

    col.fo.getChild("mcrdata.xml").delete();
    col = getStore().retrieve(col.getID());
    xml1 = (Document) col.getMetadata().clone();
    assertTrue(equals(xml1, xml2));

    col.fo.getChild("test1.txt").delete();
    FileObject tmp = col.fo.resolveFile("test3.txt");
    tmp.createFile();
    new MCRStringContent("Hallo Welt!").sendTo(tmp);
    col.repairMetadata();
    String xml3 = new MCRJDOMContent(col.getMetadata()).asString();
    assertFalse(xml3.contains("name=\"test1.txt\""));
    assertTrue(xml3.contains("name=\"test3.txt\""));
}

From source file:org.mycore.datamodel.ifs2.MCRMetadataStore.java

/**
 * Stores a newly created document under the given ID.
 * /* w w  w .  jav a  2 s.c  om*/
 * @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;
}