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

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

Introduction

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

Prototype

FileContent getContent() throws FileSystemException;

Source Link

Document

Returns this file's content.

Usage

From source file:pl.otros.vfs.browser.table.VfsTableModel.java

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    FileObject fileObject = fileObjects[rowIndex];
    boolean isFile = false;
    try {/*  ww w. jav a 2  s .  c  om*/
        isFile = FileType.FILE.equals(fileObject.getType());
    } catch (FileSystemException e1) {
        LOGGER.warn("Can't check file type " + fileObject.getName().getBaseName(), e1);
    }
    if (columnIndex == COLUMN_NAME) {
        try {
            return new FileNameWithType(fileObject.getName(), fileObject.getType());
        } catch (FileSystemException e) {
            return new FileNameWithType(fileObject.getName(), null);
        }
    } else if (columnIndex == COLUMN_TYPE) {
        try {
            return fileObject.getType().getName();
        } catch (FileSystemException e) {
            LOGGER.warn("Can't get file type " + fileObject.getName().getBaseName(), e);
            return "?";
        }
    } else if (columnIndex == COLUMN_SIZE) {
        try {
            long size = -1;
            if (isFile) {
                size = fileObject.getContent().getSize();
            }
            return new FileSize(size);
        } catch (FileSystemException e) {
            LOGGER.warn("Can't get size " + fileObject.getName().getBaseName(), e);
            return new FileSize(-1);
        }
    } else if (columnIndex == COLUMN_LAST_MOD_DATE) {
        try {

            long lastModifiedTime = 0;
            if (!VFSUtils.isHttpProtocol(fileObject)) {
                lastModifiedTime = fileObject.getContent().getLastModifiedTime();
            }
            return new Date(lastModifiedTime);
        } catch (FileSystemException e) {
            LOGGER.warn("Can't get last mod date " + fileObject.getName().getBaseName(), e);
            return null;
        }
    }
    return "?";
}

From source file:pl.otros.vfs.browser.util.VFSUtils.java

public static boolean pointToItself(FileObject fileObject) throws FileSystemException {
    if (!fileObject.getURL().getProtocol().equalsIgnoreCase("file")
            && FileType.FILE.equals(fileObject.getType())) {
        LOGGER.debug("Checking if {} is pointing to itself", fileObject.getName().getFriendlyURI());
        FileObject[] children = VFSUtils.getChildren(fileObject);
        LOGGER.debug("Children number of {} is {}", fileObject.getName().getFriendlyURI(), children.length);
        if (children.length == 1) {
            FileObject child = children[0];
            if (child.getContent().getSize() != child.getContent().getSize()) {
                return false;
            }//from   w w  w .ja  va 2 s. c o m
            if (child.getName().getBaseName().equals(fileObject.getName().getBaseName())) {
                return true;
            }
        }
    }
    return false;
}

From source file:poisondog.android.image.ImageDiskCache.java

public synchronized void put(String key, Bitmap value) throws FileSystemException, IOException {
    FileObject file = VFS.getManager().resolveFile(cache + "/" + HashFunction.md5(key));
    OutputStream output = file.getContent().getOutputStream();
    value.compress(Bitmap.CompressFormat.JPEG, 90, output);
    output.close();/*from   w ww  . j  av a 2s .  c o  m*/
}

From source file:poisondog.android.image.ImageFetcher.java

protected Bitmap processBitmap(Object data) {
    if (!(data instanceof String))
        return null;
    try {/* w ww .j  a  va 2 s. c o  m*/
        FileObject remote = VFS.getManager().resolveFile((String) data);
        if (remote.getURL().getProtocol() == "file")
            return super.processBitmap(remote.getURL().toString());

        //         FileObject file = CacheDirectory.download(remote);
        FileObject file = mDestination.resolveFile(remote.getName().getBaseName());
        CopyTask task = new CopyTask(remote.getContent().getInputStream(), file.getContent().getOutputStream());
        task.transport();

        if (file == null) {
            return null;
        }
        return super.processBitmap(file.getURL().toString());
    } catch (FileSystemException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:poisondog.commons.vfs.LastModifiedComparator.java

public int compare(FileObject obj1, FileObject obj2) {
    try {//from  w ww. j  a v  a 2 s .  c o m
        if (obj1.getType() == FileType.FOLDER && obj2.getType() != FileType.FOLDER)
            return -1;
        if (obj1.getType() != FileType.FOLDER && obj2.getType() == FileType.FOLDER)
            return 1;
        long time1 = obj1.getContent().getLastModifiedTime();
        long time2 = obj2.getContent().getLastModifiedTime();
        if (time2 > time1)
            return 1;
        if (time2 < time1)
            return -1;
        return 0;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return 0;
}

From source file:pt.webdetails.cpk.utils.ZipUtil.java

private ZipOutputStream writeEntriesToZip(Collection<FileObject> files, ZipOutputStream zipOut) {
    int i = 0;/*  w ww  .jav  a2s. c o  m*/
    try {
        for (FileObject file : files) {
            i++;
            logger.debug("Files to process:" + files.size());
            logger.debug("Files processed: " + i);
            logger.debug("Files remaining: " + (files.size() - i));
            logger.debug(file.getName().getPath());

            fileListing.add(removeTopFilenamePathFromString(file.getName().getPath()));

            ZipEntry zip = null;

            if (file.getType() == FileType.FOLDER) {
                zip = new ZipEntry(
                        removeTopFilenamePathFromString(file.getName().getPath() + File.separator + ""));
                zipOut.putNextEntry(zip);
            } else {
                zip = new ZipEntry(removeTopFilenamePathFromString(file.getName().getPath()));
                zipOut.putNextEntry(zip);
                byte[] bytes = IOUtils.toByteArray(file.getContent().getInputStream());
                zipOut.write(bytes);
                zipOut.closeEntry();
            }
        }

    } catch (Exception exception) {
        logger.error(exception);
    }
    return zipOut;
}

From source file:se.kth.hopsworks.zeppelin.notebook.repo.FSNotebookRepo.java

@Override
public void save(Note note) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();/*from   w ww  .j  a  v a  2  s .co  m*/
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);

    FileObject rootDir = getRootDir();

    FileObject projectDir = rootDir.resolveFile(this.project.getName(), NameScope.CHILD);
    if (!projectDir.exists()) {
        projectDir.createFolder();
    }
    if (!isDirectory(projectDir)) {
        throw new IOException(projectDir.getName().toString() + " is not a directory");
    }

    FileObject noteDir = projectDir.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));
}

From source file:sf.net.experimaestro.connectors.UnixScriptProcessBuilder.java

@Override
final public XPMProcess start() throws LaunchException, IOException {
    final FileObject runFile = connector.resolveFile(path);
    final FileObject basepath = runFile.getParent();
    final String baseName = runFile.getName().getBaseName();

    try (CommandContext env = new CommandContext.FolderContext(connector, basepath, baseName)) {
        // Prepare the commands
        commands().prepare(env);//from w w  w  .  jav  a2s  .  c o  m

        // First generate the run file
        PrintWriter writer = new PrintWriter(runFile.getContent().getOutputStream());

        writer.format("#!%s%n", shPath);

        writer.format("# Experimaestro generated task: %s%n", path);
        writer.println();

        // A command fails if any of the piped commands fail
        writer.println("set -o pipefail");
        writer.println();

        writer.println();
        if (environment() != null) {
            for (Map.Entry<String, String> pair : environment().entrySet())
                writer.format("export %s=\"%s\"%n", pair.getKey(), protect(pair.getValue(), QUOTED_SPECIAL));
        }

        if (directory() != null) {
            writer.format("cd \"%s\"%n", protect(env.resolve(directory()), QUOTED_SPECIAL));
        }

        if (!lockFiles.isEmpty()) {
            writer.format("%n# Checks that the locks are set%n");
            for (String lockFile : lockFiles) {
                writer.format("test -f %s || exit 017%n", lockFile);
            }
        }

        writer.format(
                "%n%n# Set traps to cleanup (remove locks and temporary files, kill remaining processes) when exiting%n%n");
        writer.format("trap cleanup EXIT SIGINT SIGTERM%n");
        writer.format("cleanup() {%n");
        for (String file : lockFiles) {
            writer.format("  rm -f %s;%n", file);
        }

        commands().forEachCommand(Streams.propagate(c -> {
            final CommandContext.NamedPipeRedirections namedRedirections = env.getNamedRedirections(c, false);
            for (FileObject file : Iterables.concat(namedRedirections.outputRedirections,
                    namedRedirections.errorRedirections)) {
                writer.format("  rm -f %s;%n", env.resolve(file));
            }
        }));

        // Kills remaining processes
        writer.println("  jobs -pr | xargs kill");
        writer.format("}%n%n");

        // Write the command
        final StringWriter sw = new StringWriter();
        PrintWriter exitWriter = new PrintWriter(sw);
        exitWriter.format("code=$?; if test $code -ne 0; then%n");
        if (exitCodePath != null)
            exitWriter.format(" echo $code > \"%s\"%n", protect(exitCodePath, QUOTED_SPECIAL));
        exitWriter.format(" exit $code%n");
        exitWriter.format("fi%n");

        String exitScript = sw.toString();

        writer.format("%n%n");

        switch (input.type()) {
        case INHERIT:
            break;
        case READ:
            writer.format("cat \"%s\" | ", connector.resolve(input.file()));
            break;
        default:
            throw new UnsupportedOperationException("Unsupported input redirection type: " + input.type());
        }

        writer.println("(");

        // The prepare all the commands
        writeCommands(env, writer, commands());

        writer.print(") ");

        writeRedirection(writer, output, 1);
        writeRedirection(writer, error, 2);

        writer.println();
        writer.print(exitScript);

        if (exitCodePath != null)
            writer.format("echo 0 > \"%s\"%n", protect(exitCodePath, QUOTED_SPECIAL));
        if (donePath != null)
            writer.format("touch \"%s\"%n", protect(donePath, QUOTED_SPECIAL));

        writer.close();

        // Set the file as executable
        runFile.setExecutable(true, false);

        processBuilder.command(protect(path, SHELL_SPECIAL));

        processBuilder.detach(true);
        processBuilder.redirectOutput(output);
        processBuilder.redirectError(error);

        processBuilder.job(job);

        return processBuilder.start();
    } catch (Exception e) {
        throw new LaunchException(e);
    }

}

From source file:sf.net.experimaestro.connectors.XPMProcess.java

/**
 * Returns the error code/*from  w  w  w.jav a  2 s  .co  m*/
 */
public int exitValue() {
    // Check for done file
    try {
        if (job.getLocator().resolve(connector, Resource.DONE_EXTENSION).exists())
            return 0;

        // If the job is not done, check the ".code" file to get the error code
        // and otherwise return -1
        final FileObject codeFile = job.getMainConnector()
                .resolveFile(job.getLocator().getPath() + Job.CODE_EXTENSION);
        if (codeFile.exists()) {
            final InputStream stream = codeFile.getContent().getInputStream();
            final BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
            String s = reader.readLine();
            int code = s != null ? Integer.parseInt(s) : -1;
            reader.close();
            return code;
        }
    } catch (IOException e) {
        throw new IllegalThreadStateException();
    }

    // The process failed, but we do not know how
    return -1;

}

From source file:sf.net.experimaestro.connectors.XPMProcess.java

/**
 * Asynchronous check the state of the job monitor
 *///  w  w w .  j  av a 2s.c o  m
public void check() throws Exception {
    if (!isRunning()) {
        // We are not running: send a message
        LOGGER.debug("End of job [%s]", job);
        final FileObject file = job.getLocator().resolve(connector, Resource.CODE_EXTENSION);
        final long time = file.exists() ? file.getContent().getLastModifiedTime() : -1;
        job.notify(new EndOfJobMessage(exitValue(), time));
        dispose();
    }
}