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

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

Introduction

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

Prototype

public void createFile() throws FileSystemException;

Source Link

Document

Creates this file, if it does not exist.

Usage

From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java

@Test
public void testUserAuthentication() throws Exception {
    StaticUserAuthenticator auth = new StaticUserAuthenticator(null, "username", "password");
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(System.getProperty("user.dir"));
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileObject fo = manager.resolveFile("d:" + file.getName().getPath(), opts);

    fo.createFile();

}

From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java

/**
 *  ? ?? ? ? ? ? ?? ?./*  ww  w. j av  a  2s .  c om*/
 * @throws Exception
 */
@Test
public void testCeateFile() throws Exception {
    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(System.getProperty("user.dir"));
    final FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //  ? 
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    // ? ?
    file.createFile();
    assertTrue(file.exists());
}

From source file:egovframework.rte.fdl.filehandling.FilehandlingServiceTest.java

/**
 *  ?  ??  ? ? .//w w  w .  j av a 2  s.  c o  m
 * ?    ? ?    ?? ?.
 * @throws Exception
 */
@Test
public void testAccessFile() throws Exception {

    FileSystemManager manager = VFS.getManager();

    FileObject baseDir = manager.resolveFile(System.getProperty("user.dir"));
    FileObject file = manager.resolveFile(baseDir, "testfolder/file1.txt");

    //  ? 
    file.delete(Selectors.SELECT_FILES);
    assertFalse(file.exists());

    // ? ?
    file.createFile();
    assertTrue(file.exists());

    FileContent fileContent = file.getContent();
    assertEquals(0, fileContent.getSize());

    // ? 
    String string = "test.";
    OutputStream os = fileContent.getOutputStream();

    try {
        os.write(string.getBytes());
        os.flush();
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        os.close();
    }
    assertNotSame(0, fileContent.getSize());

    // ? ?
    StringBuffer sb = new StringBuffer();
    FileObject writtenFile = manager.resolveFile(baseDir, "testfolder/file1.txt");
    FileContent writtenContents = writtenFile.getContent();
    InputStream is = writtenContents.getInputStream();

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        for (String line = ""; (line = reader.readLine()) != null; sb.append(line))
            ;

    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        is.close();
    }

    // ? ?
    assertEquals(sb.toString(), string);
}

From source file:be.ibridge.kettle.job.entry.createfile.JobEntryCreateFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);//from w w  w.  ja  v  a2s  .co  m

    if (filename != null) {
        String realFilename = getRealFilename();
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realFilename);

            if (fileObject.exists()) {
                if (isFailIfFileExists()) {
                    // File exists and fail flag is on.
                    result.setResult(false);
                    log.logError(toString(), "File [" + realFilename + "] exists, failing.");
                } else {
                    // File already exists, no reason to try to create it
                    result.setResult(true);
                    log.logBasic(toString(), "File [" + realFilename + "] already exists, not recreating.");
                }
            } else {
                //  No file yet, create an empty file.
                fileObject.createFile();
                log.logBasic(toString(), "File [" + realFilename + "] created!");
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    "Could not create file [" + realFilename + "], exception: " + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), "No filename is defined.");
    }

    return result;
}

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

public Result execute(Result previousResult, int nr, Repository rep, Job parentJob) throws KettleException {
    LogWriter log = LogWriter.getInstance();
    Result result = previousResult;
    result.setResult(false);//from  w ww . java2  s  . c  o  m

    if (filename != null) {
        String realFilename = getRealFilename();
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realFilename);

            if (fileObject.exists()) {
                if (isFailIfFileExists()) {
                    // File exists and fail flag is on.
                    result.setResult(false);
                    log.logError(toString(), "File [" + realFilename + "] exists, failing.");
                } else {
                    // File already exists, no reason to try to create it
                    result.setResult(true);
                    log.logBasic(toString(), "File [" + realFilename + "] already exists, not recreating.");
                }
                // add filename to result filenames if needed
                if (isAddFilenameToResult())
                    addFilenameToResult(realFilename, log, result, parentJob);
            } else {
                //  No file yet, create an empty file.
                fileObject.createFile();
                log.logBasic(toString(), "File [" + realFilename + "] created!");
                // add filename to result filenames if needed
                if (isAddFilenameToResult())
                    addFilenameToResult(realFilename, log, result, parentJob);
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    "Could not create file [" + realFilename + "], exception: " + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        log.logError(toString(), "No filename is defined.");
    }

    return result;
}

From source file:com.panet.imeta.job.entries.shell.JobEntryShell.java

private void executeShell(Result result, List<RowMetaAndData> cmdRows, String[] args) {
    LogWriter log = LogWriter.getInstance();
    FileObject fileObject = null;
    String realScript = null;//  ww w .j  av a 2  s . c  o m
    FileObject tempFile = null;

    try {
        // What's the exact command?
        String base[] = null;
        List<String> cmds = new ArrayList<String>();

        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.RunningOn", Const.getOS()));

        if (insertScript) {
            realScript = environmentSubstitute(script);
        } else {
            String realFilename = environmentSubstitute(getFilename());
            fileObject = KettleVFS.getFileObject(realFilename);
        }

        if (Const.getOS().equals("Windows 95")) {
            base = new String[] { "command.com", "/C" };
        } else if (Const.getOS().startsWith("Windows")) {
            base = new String[] { "cmd.exe", "/C" };
        } else {
            if (!insertScript) {
                // Just set the command to the script we need to execute...
                //
                base = new String[] { KettleVFS.getFilename(fileObject) };
            } else {
                // Create a unique new temporary filename in the working directory, put the script in there
                // Set the permissions to execute and then run it...
                //
                try {
                    tempFile = KettleVFS.createTempFile("kettle", "shell", workDirectory);
                    tempFile.createFile();
                    OutputStream outputStream = tempFile.getContent().getOutputStream();
                    outputStream.write(realScript.getBytes());
                    outputStream.close();
                    String tempFilename = KettleVFS.getFilename(tempFile);
                    // Now we have to make this file executable...
                    // On Unix-like systems this is done using the command "/bin/chmod +x filename"
                    //
                    ProcessBuilder procBuilder = new ProcessBuilder("chmod", "+x", tempFilename);
                    Process proc = procBuilder.start();
                    // Eat/log stderr/stdout all messages in a different thread...
                    StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(),
                            toString() + " (stderr)");
                    StreamLogger outputLogger = new StreamLogger(proc.getInputStream(),
                            toString() + " (stdout)");
                    new Thread(errorLogger).start();
                    new Thread(outputLogger).start();
                    proc.waitFor();

                    // Now set this filename as the base command...
                    //
                    base = new String[] { tempFilename };
                } catch (Exception e) {
                    throw new Exception("Unable to create temporary file to execute script", e);
                }
            }
        }

        // Construct the arguments...
        if (argFromPrevious && cmdRows != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmdline.append(' ');
                        cmdline.append(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                // Add the arguments from previous results...
                for (int i = 0; i < cmdRows.size(); i++) // Normally just
                // one row, but
                // once in a
                // while to
                // remain
                // compatible we
                // have
                // multiple.
                {
                    RowMetaAndData r = (RowMetaAndData) cmdRows.get(i);
                    for (int j = 0; j < r.size(); j++) {
                        cmds.add(optionallyQuoteField(r.getString(j, null), "\""));
                    }
                }
            }
        } else if (args != null) {
            // Add the base command...
            for (int i = 0; i < base.length; i++)
                cmds.add(base[i]);

            if (Const.getOS().equals("Windows 95") || Const.getOS().startsWith("Windows")) {
                // for windows all arguments including the command itself
                // need to be
                // included in 1 argument to cmd/command.

                StringBuffer cmdline = new StringBuffer(300);

                cmdline.append('"');
                if (insertScript)
                    cmdline.append(realScript);
                else
                    cmdline.append(optionallyQuoteField(KettleVFS.getFilename(fileObject), "\""));

                for (int i = 0; i < args.length; i++) {
                    cmdline.append(' ');
                    cmdline.append(optionallyQuoteField(args[i], "\""));
                }
                cmdline.append('"');
                cmds.add(cmdline.toString());
            } else {
                for (int i = 0; i < args.length; i++) {
                    cmds.add(args[i]);
                }
            }
        }

        StringBuffer command = new StringBuffer();

        Iterator<String> it = cmds.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first)
                command.append(' ');
            else
                first = false;
            command.append((String) it.next());
        }
        if (log.isBasic())
            log.logBasic(toString(), Messages.getString("JobShell.ExecCommand", command.toString()));

        // Build the environment variable list...
        ProcessBuilder procBuilder = new ProcessBuilder(cmds);
        Map<String, String> env = procBuilder.environment();
        String[] variables = listVariables();
        for (int i = 0; i < variables.length; i++) {
            env.put(variables[i], getVariable(variables[i]));
        }

        if (getWorkDirectory() != null && !Const.isEmpty(Const.rtrim(getWorkDirectory()))) {
            String vfsFilename = environmentSubstitute(getWorkDirectory());
            File file = new File(KettleVFS.getFilename(KettleVFS.getFileObject(vfsFilename)));
            procBuilder.directory(file);
        }
        Process proc = procBuilder.start();

        // any error message?
        StreamLogger errorLogger = new StreamLogger(proc.getErrorStream(), toString() + " (stderr)");

        // any output?
        StreamLogger outputLogger = new StreamLogger(proc.getInputStream(), toString() + " (stdout)");

        // kick them off
        new Thread(errorLogger).start();
        new Thread(outputLogger).start();

        proc.waitFor();
        if (log.isDetailed())
            log.logDetailed(toString(), Messages.getString("JobShell.CommandFinished", command.toString()));

        // What's the exit status?
        result.setExitStatus(proc.exitValue());
        if (result.getExitStatus() != 0) {
            if (log.isDetailed())
                log.logDetailed(toString(), Messages.getString("JobShell.ExitStatus",
                        environmentSubstitute(getFilename()), "" + result.getExitStatus()));

            result.setNrErrors(1);
        }

        // close the streams
        // otherwise you get "Too many open files, java.io.IOException" after a lot of iterations
        proc.getErrorStream().close();
        proc.getOutputStream().close();

    } catch (IOException ioe) {
        log.logError(toString(), Messages.getString("JobShell.ErrorRunningShell",
                environmentSubstitute(getFilename()), ioe.toString()));
        result.setNrErrors(1);
    } catch (InterruptedException ie) {
        log.logError(toString(), Messages.getString("JobShell.Shellinterupted",
                environmentSubstitute(getFilename()), ie.toString()));
        result.setNrErrors(1);
    } catch (Exception e) {
        log.logError(toString(), Messages.getString("JobShell.UnexpectedError",
                environmentSubstitute(getFilename()), e.toString()));
        result.setNrErrors(1);
    } finally {
        // If we created a temporary file, remove it...
        //
        if (tempFile != null) {
            try {
                tempFile.delete();
            } catch (Exception e) {
                Messages.getString("JobShell.UnexpectedError", tempFile.toString(), e.toString());
            }
        }
    }

    if (result.getNrErrors() > 0) {
        result.setResult(false);
    } else {
        result.setResult(true);
    }
}

From source file:org.apache.commons.vfs.example.Shell.java

/**
 * Does a 'touch' command./* w  w w .  ja  v  a 2  s.c  o  m*/
 */
private void touch(final String[] cmd) throws Exception {
    if (cmd.length < 2) {
        throw new Exception("USAGE: touch <path>");
    }
    final FileObject file = mgr.resolveFile(cwd, cmd[1]);
    if (!file.exists()) {
        file.createFile();
    }
    file.getContent().setLastModifiedTime(System.currentTimeMillis());
}

From source file:org.bibalex.gallery.storage.BAGStorage.java

public static URL cacheFileLocally(String cacheLocalPath, String fileUrlStr) throws BAGException {
    try {/*from ww w .  j a  va2s  .  c  om*/
        // String extension = "";
        //
        // int lastDotIx = fileUrlStr.lastIndexOf('.');
        // if (lastDotIx > fileUrlStr.lastIndexOf('/')) {
        // extension = fileUrlStr.substring(lastDotIx);
        // }
        // String cacheFileName = "cached" + fileUrlStr.hashCode() + extension;

        int lastSlashIx = fileUrlStr.lastIndexOf('/');

        String cacheFileName = fileUrlStr.substring(lastSlashIx + 1);

        String cacheFilePath = URLPathStrUtils.appendParts(cacheLocalPath, cacheFileName);

        FileSystemManager fsMgr = VFS.getManager();

        final FileObject cacheFileFO = fsMgr.resolveFile(cacheFilePath);
        final FileObject cacheDirFO = fsMgr.resolveFile(cacheLocalPath);

        if (!cacheFileFO.exists()) {
            synchronized (BAGStorage.class) {

                if (!cacheDirFO.exists()) {
                    cacheDirFO.createFolder();
                }

                cacheFileFO.createFile();

                OutputStream cacheFileOut = cacheFileFO.getContent().getOutputStream();
                try {
                    readRemoteFile(fileUrlStr, cacheFileOut);
                } finally {
                    cacheFileOut.close();
                }

            }
        }

        return cacheFileFO.getURL();

    } catch (FileSystemException e) {
        throw new BAGException(e);
    } catch (IOException e) {
        throw new BAGException(e);
    }
}

From source file:org.codehaus.cargo.util.VFSFileHandlerTest.java

/**
 * Test the {@link FileHandler#copyFile(java.lang.String, java.lang.String)} method.
 * @throws Exception If anything goes wrong.
 *//* w  w w  .j  a va 2  s  .c o  m*/
public void testCopyFile() throws Exception {
    String source = "ram:///some/path/file.war";
    String target = "ram:///other/path/newfile.war";

    FileObject sourceObject = this.fsManager.resolveFile(source);
    sourceObject.createFile();

    FileObject targetObject = this.fsManager.resolveFile(target);

    assertFalse(targetObject.exists());

    this.fileHandler.copyFile(source, target);

    assertTrue(targetObject.exists());
}

From source file:org.codehaus.cargo.util.VFSFileHandlerTest.java

/**
 * Test the {@link FileHandler#copyFile(java.lang.String, java.lang.String, boolean)} method.
 * @throws Exception If anything goes wrong.
 *//*from  w w w.j a va2 s . c om*/
public void testCopyFileOverwrite() throws Exception {
    String source = "ram:///some/path/file.war";
    String target = "ram:///other/path/newfile.war";

    FileObject sourceObject = this.fsManager.resolveFile(source);
    sourceObject.createFile();

    FileObject targetObject = this.fsManager.resolveFile(target);

    assertFalse(targetObject.exists());

    this.fileHandler.copyFile(source, target, true);

    assertTrue(targetObject.exists());
}