Example usage for org.apache.commons.vfs FileObject close

List of usage examples for org.apache.commons.vfs FileObject close

Introduction

In this page you can find the example usage for org.apache.commons.vfs FileObject close.

Prototype

public void close() throws FileSystemException;

Source Link

Document

Closes this file, and its content.

Usage

From source file:com.panet.imeta.job.entries.createfile.JobEntryCreateFile.java

private void addFilenameToResult(String targetFilename, LogWriter log, Result result, Job parentJob)
        throws KettleException {
    FileObject targetFile = null;
    try {/*from  ww  w .  j  a  v  a2s  . c  o  m*/
        targetFile = KettleVFS.getFileObject(targetFilename);

        // Add to the result files...
        ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL, targetFile, parentJob.getJobname(),
                toString());
        resultFile.setComment(""); //$NON-NLS-1$
        result.getResultFiles().put(resultFile.getFile().toString(), resultFile);

        if (log.isDetailed())
            log.logDetailed(toString(),
                    Messages.getString("JobEntryCreateFile.FileAddedToResult", targetFilename)); //$NON-NLS-1$
    } catch (Exception e) {
        throw new KettleException(e);
    } finally {
        try {
            targetFile.close();
            targetFile = null;
        } catch (Exception e) {
        }
    }
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testRandomReadOnlyAccessInputStreamOpenReadAutocloseRead() throws Exception {
    final FileObject fo = openFileObject(TEST_FILENAME);
    final RandomAccessContent rac = openRandomAccessContent(fo, RandomAccessMode.READ);
    final BufferedReader reader = getBufferedReader(rac.getInputStream());
    try {/*from  w w  w . j a va  2s . c  om*/
        for (int i = 0; i < TEST_FILE_A_CHARS_NUMBER; i++) {
            assertTrue('a' == reader.read());
        }
        Thread.sleep(SLEEP_TIME);
        for (int i = 0; i < TEST_FILE_B_CHARS_NUMBER; i++) {
            assertTrue('b' == reader.read());
        }
    } finally {
        rac.close();
    }
    fo.close();
}

From source file:functionalTests.vfsprovider.TestProActiveProviderAutoclosing.java

@Test
public void testRandomReadOnlyAccessInputStreamOpenSeekAutocloseReadGetPos() throws Exception {
    final FileObject fo = openFileObject(TEST_FILENAME);
    final RandomAccessContent rac = openRandomAccessContent(fo, RandomAccessMode.READ);
    InputStream is = rac.getInputStream();
    try {//from  w w w.  j  a v a 2 s .  co  m
        rac.seek(TEST_FILE_A_CHARS_NUMBER);
        // reget input stream
        is = rac.getInputStream();
        Thread.sleep(SLEEP_TIME);
        for (int i = 0; i < TEST_FILE_B_CHARS_NUMBER; i++) {
            assertTrue('b' == is.read());
        }
        assertEquals(TEST_FILE_A_CHARS_NUMBER + TEST_FILE_B_CHARS_NUMBER, rac.getFilePointer());
    } finally {
        rac.close();
    }
    fo.close();
}

From source file:com.panet.imeta.trans.steps.gpbulkloader.GPBulkLoader.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (GPBulkLoaderMeta) smi;//www . j  a v a2s .  c o m
    data = (GPBulkLoaderData) sdi;

    super.dispose(smi, sdi);

    if (!preview && meta.isEraseFiles()) {
        // Erase the created cfg/dat files if requested. We don't erase
        // the rest of the files because it would be "stupid" to erase them
        // right after creation. If you don't want them, don't fill them in.
        FileObject fileObject = null;

        String method = meta.getLoadMethod();
        if ( // GPBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(method) ||
        GPBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            if (meta.getControlFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()));
                    fileObject.delete();
                    fileObject.close();
                } catch (IOException ex) {
                    logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (GPBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            // In concurrent mode the data is written to the control file.
            if (meta.getDataFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()));
                    fileObject.delete();
                    fileObject.close();
                } catch (IOException ex) {
                    logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (GPBulkLoaderMeta.METHOD_MANUAL.equals(method)) {
            logBasic("Deletion of files is not compatible with \'manual load method\'");
        }
    }
}

From source file:com.panet.imeta.trans.steps.orabulkloader.OraBulkLoader.java

public void dispose(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (OraBulkLoaderMeta) smi;// w  w  w . ja  va2s .  c o  m
    data = (OraBulkLoaderData) sdi;

    super.dispose(smi, sdi);

    // close output stream (may terminate running sqlldr)       
    if (output != null) {
        // Close the output
        try {
            output.close();
        } catch (IOException e) {
            logError("Error while closing output", e);
        }

        output = null;
    }
    // running sqlldr process must be terminated       
    if (sqlldrProcess != null) {
        try {
            int exitVal = sqlldrProcess.waitFor();
            sqlldrProcess = null;
            logBasic(Messages.getString("OraBulkLoader.Log.ExitValueSqlldr", "" + exitVal)); //$NON-NLS-1$
        } catch (InterruptedException e) {
            /* process should be destroyed */
            e.printStackTrace();
            if (sqlldrProcess != null) {
                sqlldrProcess.destroy();
            }
        }
    }

    if (!preview && meta.isEraseFiles()) {
        // Erase the created cfg/dat files if requested. We don't erase
        // the rest of the files because it would be "stupid" to erase them
        // right after creation. If you don't want them, don't fill them in.
        FileObject fileObject = null;

        String method = meta.getLoadMethod();
        if ( // OraBulkLoaderMeta.METHOD_AUTO_CONCURRENT.equals(method) || 
        OraBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            if (meta.getControlFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getControlFile()));
                    fileObject.delete();
                    fileObject.close();
                } catch (IOException ex) {
                    logError("Error deleting control file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (OraBulkLoaderMeta.METHOD_AUTO_END.equals(method)) {
            // In concurrent mode the data is written to the control file.
            if (meta.getDataFile() != null) {
                try {
                    fileObject = KettleVFS.getFileObject(environmentSubstitute(meta.getDataFile()));
                    fileObject.delete();
                    fileObject.close();
                } catch (IOException ex) {
                    logError("Error deleting data file \'" + KettleVFS.getFilename(fileObject) + "\': "
                            + ex.getMessage());
                }
            }
        }

        if (OraBulkLoaderMeta.METHOD_MANUAL.equals(method)) {
            logBasic("Deletion of files is not compatible with \'manual load method\'");
        }
    }
}

From source file:mondrian.spi.impl.ApacheVfsVirtualFileHandler.java

public InputStream readVirtualFile(String url) throws FileSystemException {
    // Treat catalogUrl as an Apache VFS (Virtual File System) URL.
    // VFS handles all of the usual protocols (http:, file:)
    // and then some.
    FileSystemManager fsManager = VFS.getManager();
    if (fsManager == null) {
        throw Util.newError("Cannot get virtual file system manager");
    }/*from   w  w w .j  a v a2s .c  o  m*/

    // Workaround VFS bug.
    if (url.startsWith("file://localhost")) {
        url = url.substring("file://localhost".length());
    }
    if (url.startsWith("file:")) {
        url = url.substring("file:".length());
    }

    //work around for VFS bug not closing http sockets
    // (Mondrian-585)
    if (url.startsWith("http")) {
        try {
            return new URL(url).openStream();
        } catch (IOException e) {
            throw Util.newError("Could not read URL: " + url);
        }
    }

    File userDir = new File("").getAbsoluteFile();
    FileObject file = fsManager.resolveFile(userDir, url);
    FileContent fileContent = null;
    try {
        // Because of VFS caching, make sure we refresh to get the latest
        // file content. This refresh may possibly solve the following
        // workaround for defect MONDRIAN-508, but cannot be tested, so we
        // will leave the work around for now.
        file.refresh();

        // Workaround to defect MONDRIAN-508. For HttpFileObjects, verifies
        // the URL of the file retrieved matches the URL passed in.  A VFS
        // cache bug can cause it to treat URLs with different parameters
        // as the same file (e.g. http://blah.com?param=A,
        // http://blah.com?param=B)
        if (file instanceof HttpFileObject && !file.getName().getURI().equals(url)) {
            fsManager.getFilesCache().removeFile(file.getFileSystem(), file.getName());

            file = fsManager.resolveFile(userDir, url);
        }

        if (!file.isReadable()) {
            throw Util.newError("Virtual file is not readable: " + url);
        }

        fileContent = file.getContent();
    } finally {
        file.close();
    }

    if (fileContent == null) {
        throw Util.newError("Cannot get virtual file content: " + url);
    }

    return fileContent.getInputStream();
}

From source file:com.thinkberg.moxo.dav.PutHandler.java

public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    FileObject object = getResourceManager().getFileObject(request.getPathInfo());

    try {// www.  j av a2 s.c o  m
        LockManager.getInstance().checkCondition(object, getIf(request));
    } catch (LockException e) {
        if (e.getLocks() != null) {
            response.sendError(SC_LOCKED);
        } else {
            response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        }
        return;
    }

    // it is forbidden to write data on a folder
    if (object.exists() && FileType.FOLDER.equals(object.getType())) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    FileObject parent = object.getParent();
    if (!parent.exists()) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    if (!FileType.FOLDER.equals(parent.getType())) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }

    InputStream is = request.getInputStream();
    OutputStream os = object.getContent().getOutputStream();
    log("PUT sends " + request.getHeader("Content-length") + " bytes");
    log("PUT copied " + Util.copyStream(is, os) + " bytes");
    os.flush();
    object.close();

    response.setStatus(HttpServletResponse.SC_CREATED);
}

From source file:com.panet.imeta.trans.steps.sqlfileoutput.SQLFileOutput.java

public boolean init(StepMetaInterface smi, StepDataInterface sdi) {
    meta = (SQLFileOutputMeta) smi;/*from   w ww.  j  a  v  a  2  s  .  c  om*/
    data = (SQLFileOutputData) sdi;

    if (super.init(smi, sdi)) {
        try {
            if (meta.getDatabaseMeta() == null) {
                throw new KettleStepException("The connection is not defined (empty)");
            }

            data.db = new Database(meta.getDatabaseMeta());
            data.db.shareVariablesWith(this);

            logBasic("Connected to database [" + meta.getDatabaseMeta() + "]");

            if (meta.isCreateParentFolder()) {
                // Check for parent folder
                FileObject parentfolder = null;
                try {
                    // Get parent folder
                    String filename = environmentSubstitute(meta.getFileName());
                    parentfolder = KettleVFS.getFileObject(filename).getParent();
                    if (!parentfolder.exists()) {
                        log.logBasic("Folder parent",
                                "Folder parent " + parentfolder.getName() + " does not exist !");
                        parentfolder.createFolder();
                        log.logBasic("Folder parent", "Folder parent was created.");
                    }
                } catch (Exception e) {
                    logError("Couldn't created parent folder " + parentfolder.getName());
                    setErrors(1L);
                    stopAll();
                } finally {
                    if (parentfolder != null) {
                        try {
                            parentfolder.close();
                        } catch (Exception ex) {
                        }
                        ;
                    }
                }
            }

            if (!meta.isDoNotOpenNewFileInit()) {
                if (!openNewFile()) {
                    logError("Couldn't open file [" + buildFilename() + "]");
                    setErrors(1L);
                    stopAll();
                }
            }

            tableName = environmentSubstitute(meta.getTablename());
            schemaName = environmentSubstitute(meta.getSchemaName());

            if (Const.isEmpty(tableName)) {
                throw new KettleStepException("The tablename is not defined (empty)");
            }

            schemaTable = data.db.getDatabaseMeta().getQuotedSchemaTableCombination(schemaName, tableName);

        } catch (Exception e) {
            logError("An error occurred intialising this step: " + e.getMessage());
            stopAll();
            setErrors(1);
        }

        return true;
    }
    return false;
}

From source file:com.learningobjects.community.abgm.logic.ControllerJob.java

private void download(String sourceUrl, File destinationFile) throws IOException {
    logger.log(Level.INFO, "Downloading or copying file from " + sourceUrl + " to " + destinationFile);
    FileObject sourceFileObject = null;
    OutputStream outputStream = null;
    try {/*from ww w .  j  a v a  2s .c om*/
        // special case sftp so that new hosts work out of the box. other options could go here too
        SftpFileSystemConfigBuilder sftpFileSystemConfigBuilder = SftpFileSystemConfigBuilder.getInstance();
        FileSystemOptions fileSystemOptions = new FileSystemOptions();
        sftpFileSystemConfigBuilder.setStrictHostKeyChecking(fileSystemOptions, "no");
        // actually try to get the file
        FileSystemManager fsManager = VFS.getManager();
        sourceFileObject = fsManager.resolveFile(sourceUrl, fileSystemOptions);
        FileContent sourceFileContent = sourceFileObject.getContent();
        InputStream inputStream = sourceFileContent.getInputStream();
        outputStream = new FileOutputStream(destinationFile);
        // do the copy - this is probably a dupe of commons io, and many others
        byte[] buffer = new byte[8192];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    } finally {
        if (outputStream != null) {
            outputStream.close();
        }
        if (sourceFileObject != null) {
            sourceFileObject.close(); // this will close the fileContent object, too
        }
    }
}

From source file:com.panet.imeta.job.entries.xmlwellformed.JobEntryXMLWellFormed.java

private boolean ProcessFileFolder(String sourcefilefoldername, String wildcard, Job parentJob, Result result) {
    LogWriter log = LogWriter.getInstance();
    boolean entrystatus = false;
    FileObject sourcefilefolder = null;
    FileObject CurrentFile = null;

    // Get real source file and wilcard
    String realSourceFilefoldername = environmentSubstitute(sourcefilefoldername);
    if (Const.isEmpty(realSourceFilefoldername)) {
        log.logError(toString(),/*from   ww  w.j av  a2 s .  c om*/
                Messages.getString("JobXMLWellFormed.log.FileFolderEmpty", sourcefilefoldername));
        // Update Errors
        updateErrors();

        return entrystatus;
    }
    String realWildcard = environmentSubstitute(wildcard);

    try {
        sourcefilefolder = KettleVFS.getFileObject(realSourceFilefoldername);

        if (sourcefilefolder.exists()) {
            if (log.isDetailed())
                log.logDetailed(toString(),
                        Messages.getString("JobXMLWellFormed.Log.FileExists", sourcefilefolder.toString()));
            if (sourcefilefolder.getType() == FileType.FILE) {
                entrystatus = checkOneFile(sourcefilefolder, log, result, parentJob);

            } else if (sourcefilefolder.getType() == FileType.FOLDER) {
                FileObject[] fileObjects = sourcefilefolder.findFiles(new AllFileSelector() {
                    public boolean traverseDescendents(FileSelectInfo info) {
                        return true;
                    }

                    public boolean includeFile(FileSelectInfo info) {

                        FileObject fileObject = info.getFile();
                        try {
                            if (fileObject == null)
                                return false;
                            if (fileObject.getType() != FileType.FILE)
                                return false;
                        } catch (Exception ex) {
                            // Upon error don't process the file.
                            return false;
                        }

                        finally {
                            if (fileObject != null) {
                                try {
                                    fileObject.close();
                                } catch (IOException ex) {
                                }
                                ;
                            }

                        }
                        return true;
                    }
                });

                if (fileObjects != null) {
                    for (int j = 0; j < fileObjects.length && !parentJob.isStopped(); j++) {
                        if (successConditionBroken) {
                            if (!successConditionBrokenExit) {
                                log.logError(toString(), Messages.getString(
                                        "JobXMLWellFormed.Error.SuccessConditionbroken", "" + NrAllErrors));
                                successConditionBrokenExit = true;
                            }
                            return false;
                        }
                        // Fetch files in list one after one ...
                        CurrentFile = fileObjects[j];

                        if (!CurrentFile.getParent().toString().equals(sourcefilefolder.toString())) {
                            // Not in the Base Folder..Only if include sub folders  
                            if (include_subfolders) {
                                if (GetFileWildcard(CurrentFile.toString(), realWildcard)) {
                                    checkOneFile(CurrentFile, log, result, parentJob);
                                }
                            }

                        } else {
                            // In the base folder
                            if (GetFileWildcard(CurrentFile.toString(), realWildcard)) {
                                checkOneFile(CurrentFile, log, result, parentJob);
                            }
                        }
                    }
                }
            } else {
                log.logError(toString(), Messages.getString("JobXMLWellFormed.Error.UnknowFileFormat",
                        sourcefilefolder.toString()));
                // Update Errors
                updateErrors();
            }
        } else {
            log.logError(toString(),
                    Messages.getString("JobXMLWellFormed.Error.SourceFileNotExists", realSourceFilefoldername));
            // Update Errors
            updateErrors();
        }
    } // end try

    catch (IOException e) {
        log.logError(toString(), Messages.getString("JobXMLWellFormed.Error.Exception.Processing",
                realSourceFilefoldername.toString(), e.getMessage()));
        // Update Errors
        updateErrors();
    } finally {
        if (sourcefilefolder != null) {
            try {
                sourcefilefolder.close();
            } catch (IOException ex) {
            }
            ;

        }
        if (CurrentFile != null) {
            try {
                CurrentFile.close();
            } catch (IOException ex) {
            }
            ;
        }
    }
    return entrystatus;
}