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:com.msopentech.odatajclient.testservice.utils.FSManager.java

public InputStream readFile(final String relativePath, final Accept accept) {
    final String path = getAbsolutePath(relativePath, accept);
    LOG.info("Read {}", path);

    try {//from w ww .  j  ava 2 s .  com
        FileObject fileObject = fsManager.resolveFile(MEM_PREFIX + path);

        if (!fileObject.exists()) {
            LOG.warn("In-memory path '{}' not found", path);

            try {
                fileObject = fsManager.resolveFile(RES_PREFIX + path);
                fileObject = putInMemory(fileObject.getContent().getInputStream(), path);
            } catch (FileSystemException fse) {
                LOG.warn("Resource path '{}' not found", path, fse);
            }
        }

        if (!fileObject.exists()) {
            throw new NotFoundException();
        }

        // return new in-memory content
        return fileObject.getContent().getInputStream();
    } catch (IOException e) {
        throw new NotFoundException(e);
    }
}

From source file:net.sourceforge.fullsync.fs.connection.CommonsVfsConnection.java

private File buildNode(final File parent, final FileObject file)
        throws org.apache.commons.vfs2.FileSystemException {
    String name = file.getName().getBaseName();

    File n = new AbstractFile(this, name, parent, file.getType() == FileType.FOLDER, true);
    if (file.getType() == FileType.FILE) {
        FileContent content = file.getContent();
        n.setLastModified(content.getLastModifiedTime());
        n.setSize(content.getSize());//from   w  w  w.j  a  v  a2  s  .c om
    }
    return n;
}

From source file:io.dockstore.common.FileProvisioning.java

public void provisionOutputFile(FileInfo file, String cwlOutputPath) {
    File sourceFile = new File(cwlOutputPath);
    long inputSize = sourceFile.length();
    if (file.getUrl().startsWith("s3://")) {
        AmazonS3 s3Client = FileProvisioning.getAmazonS3Client(config);
        String trimmedPath = file.getUrl().replace("s3://", "");
        List<String> splitPathList = Lists.newArrayList(trimmedPath.split("/"));
        String bucketName = splitPathList.remove(0);

        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, Joiner.on("/").join(splitPathList),
                sourceFile);/*www. ja v a  2s .  co  m*/
        putObjectRequest.setGeneralProgressListener(new ProgressListener() {
            ProgressPrinter printer = new ProgressPrinter();
            long runningTotal = 0;

            @Override
            public void progressChanged(ProgressEvent progressEvent) {
                if (progressEvent.getEventType() == ProgressEventType.REQUEST_BYTE_TRANSFER_EVENT) {
                    runningTotal += progressEvent.getBytesTransferred();
                }
                printer.handleProgress(runningTotal, inputSize);
            }
        });
        try {
            s3Client.putObject(putObjectRequest);
        } finally {
            System.out.println();
        }
    } else {
        try {
            FileSystemManager fsManager;
            // trigger a copy from the URL to a local file path that's a UUID to avoid collision
            fsManager = VFS.getManager();
            // check for a local file path
            FileObject dest = fsManager.resolveFile(file.getUrl());
            FileObject src = fsManager.resolveFile(sourceFile.getAbsolutePath());
            copyFromInputStreamToOutputStream(src.getContent().getInputStream(), inputSize,
                    dest.getContent().getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException("Could not provision output files", e);
        }
    }
}

From source file:com.sshtools.appframework.ui.IconStore.java

private Icon get(String name, int size, String cacheKey, FileObject file)
        throws FileSystemException, IOException {
    Icon icon;/* ww w . ja  v a2s.  co m*/
    if (file.getName().getBaseName().toLowerCase().endsWith(".svg")) {
        InputStream in = file.getContent().getInputStream();
        try {
            icon = new SVGIcon(name + "-" + size, in, size, size);
        } finally {
            in.close();
        }
    } else {
        DataInputStream din = new DataInputStream(file.getContent().getInputStream());
        try {
            byte[] imgData = new byte[(int) file.getContent().getSize()];
            din.readFully(imgData);
            icon = new ImageIcon(imgData);
        } finally {
            din.close();
        }
    }
    if (icon.getIconWidth() != size && icon instanceof ImageIcon) {
        Image img = ((ImageIcon) icon).getImage();
        img = img.getScaledInstance(size, size, Image.SCALE_SMOOTH);
        icon = new ImageIcon(img);
    }
    cache.put(cacheKey, icon);
    return icon;
}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProviderTest.java

@Test
public void A005_testContent() throws Exception {
    String currAccountStr = testProperties.getProperty("s3.access.id");
    String currKey = testProperties.getProperty("s3.access.secret");
    String currContainerStr = testProperties.getProperty("s3.test0001.bucket.name");
    String currHost = testProperties.getProperty("s3.host");
    String currRegion = testProperties.getProperty("s3.region");
    String currFileNameStr;//from  ww w .  ja  v  a2s . co m

    SS3FileProvider currSS3 = new SS3FileProvider();

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(SS3Constants.S3SCHEME, currSS3);
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "file05";
    String currUriStr = String.format("%s://%s/%s/%s", SS3Constants.S3SCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);

    FileContent content = currFile.getContent();
    long size = content.getSize();
    Assert.assertTrue(size >= 0);

    long modTime = content.getLastModifiedTime();
    Assert.assertTrue(modTime > 0);
}

From source file:com.flicklib.folderscanner.AdvancedFolderScanner.java

protected FileMeta createFileMeta(FileObject f, MovieFileType type) throws FileSystemException {
    return new FileMeta(f.getName().getBaseName(), type, f.getContent().getSize());
}

From source file:com.sludev.commons.vfs.simpleshell.SimpleShell.java

/**
 * Does a 'touch' command.//w ww.  jav  a 2s .c o  m
 * 
 * @param cmd
 * @throws java.lang.Exception
 */
public 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:de.innovationgate.wgpublisher.design.fs.AbstractDesignFile.java

/**
 * creates a reader which depends on the configured fileEncoding for DesignSync
 * F000037B2//from www. j a  va  2 s .c o  m
 * @param file
 * @return
 * @throws UnsupportedEncodingException
 * @throws FileNotFoundException
 * @throws FileSystemException 
 */
protected Reader createReader(FileObject file)
        throws UnsupportedEncodingException, FileNotFoundException, FileSystemException {

    InputStream in = file.getContent().getInputStream();

    // If obfuscation enabled, use cipher to read code/metadata of script and tml deployments
    DESEncrypter cipher = getManager().getCipher();
    if (cipher != null && (getType() == WGDocument.TYPE_TML || getType() == WGDocument.TYPE_CSSJS)) {
        in = new CipherInputStream(in, cipher.getDcipher());
    }

    String encoding = getManager().getFileEncoding();
    // No more used because this creates a lot of problems with empty files
    // CharsetDecoder deco = Charset.forName(encoding).newDecoder();
    // deco.onMalformedInput(CodingErrorAction.REPORT);
    // deco.onUnmappableCharacter(CodingErrorAction.REPORT);
    return new BufferedReader(new InputStreamReader(in, encoding));

}

From source file:com.sludev.commons.vfs2.provider.azure.AzFileProviderTest.java

@Test
public void A004_getContentSize() throws Exception {
    String currAccountStr = testProperties.getProperty("azure.account.name");
    String currKey = testProperties.getProperty("azure.account.key");
    String currContainerStr = testProperties.getProperty("azure.test0001.container.name");
    String currHost = testProperties.getProperty("azure.host"); // <account>.blob.core.windows.net
    String currFileNameStr;//from   w  w w. j  a va  2 s.c o  m

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(AzConstants.AZSBSCHEME, new AzFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", AzConstants.AZSBSCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);

    log.info(String.format("exist() file '%s'", currUriStr));

    FileContent cont = currFile.getContent();
    long contSize = cont.getSize();

    Assert.assertTrue(contSize > 0);

}

From source file:de.innovationgate.wgpublisher.design.fs.FileSystemDesignProvider.java

public static OverlayStatus determineOverlayStatus(FileSystemDesignProvider sourceDesignProvider,
        PluginID baseId, FileObject targetDirectory, String targetEncoding, Logger log,
        DesignFileValidator validator) throws Exception {

    OverlayStatus status = new OverlayStatus();

    // Copy an overlay flag file to the system file container
    FileObject targetFCFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_FILES);
    FileObject systemFC = targetFCFolder.resolveFile("system");
    if (!systemFC.exists()) {
        systemFC.createFolder();//ww  w  .  ja  va  2  s.c  om
    }

    // Import overlay data, if available
    FileObject overlayDataFile = systemFC.resolveFile(OverlayDesignProvider.OVERLAY_DATA_FILE);
    if (overlayDataFile.exists()) {
        try {
            InputStream in = new BufferedInputStream(overlayDataFile.getContent().getInputStream());
            status.setOverlayData(OverlayData.read(in));
            in.close();
        } catch (Exception e) {
            log.error("Exception reading overlay status. Creating new status file", e);
        }

        if (status.getOverlayData() != null
                && !status.getOverlayData().getBasepluginName().equals(baseId.getUniqueName())) {
            throw new WGDesignSyncException("The overlay folder '" + targetDirectory.getName().getPath()
                    + "' is used with plugin '" + status.getOverlayData().getBasepluginName() + "' not '"
                    + baseId.getUniqueName() + "'. Overlay status determination was canceled.");
        }
    }

    Version providerVersion = baseId.getVersion();
    if (status.getOverlayData() == null) {
        OverlayData overlayData = new OverlayData();
        overlayData.setBasepluginName(baseId.getUniqueName());
        status.setOverlayData(overlayData);
        status.setNewOverlay(true);
        overlayData.setInitialBasepluginVersion(providerVersion.toString());
    }

    // Test for version compatibility between base design and overlay

    status.setCurrentBaseVersion(providerVersion);
    if (status.getOverlayData().getBasepluginVersion() != null) {
        Version baseVersion = new Version(status.getOverlayData().getBasepluginVersion());

        // Base design version is different than the compliance version of the overlay. Look if it higher (=upgrade) or lower (=error)
        if (!providerVersion.equals(baseVersion)
                || providerVersion.getBuildVersion() != baseVersion.getBuildVersion()) {
            if (providerVersion.compareTo(baseVersion) >= 0 || (providerVersion.equals(baseVersion)
                    && providerVersion.getBuildVersion() > baseVersion.getBuildVersion())) {
                status.setUpdatedBaseDesign(true);
            } else if (providerVersion.compareTo(baseVersion) < 0) {
                throw new WGDesignSyncException("The used base design version (" + providerVersion.toString()
                        + ") is lower than the compliant version for the overlay ("
                        + status.getOverlayData().getBasepluginVersion() + ").");
            }
        }

    }

    if (status.isUpdatedBaseDesign()) {
        log.info("Used version of base design is " + providerVersion.toString()
                + ". Overlay currently complies with base design version "
                + status.getOverlayData().getBasepluginVersion() + ". The overlay can be upgraded.");
    }

    // Gather changed resources in base design, so we can priorize them against the overlay resources
    FileObject sourceTmlFolder = sourceDesignProvider.getTmlFolder();
    FileObject targetTmlFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_TML);
    if (sourceTmlFolder.exists() && sourceTmlFolder.getType().equals(FileType.FOLDER)) {
        for (FileObject mediaKeyFolder : sourceTmlFolder.getChildren()) {
            FileObject overlayFolder = mediaKeyFolder.resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
            if (overlayFolder.exists()) {
                FileObject targetMediaKeyFolder = targetTmlFolder
                        .resolveFile(mediaKeyFolder.getName().getBaseName());
                determineChangedResources(WGDocument.TYPE_TML, targetMediaKeyFolder, overlayFolder,
                        targetMediaKeyFolder, targetDirectory, sourceDesignProvider.getFileEncoding(),
                        targetEncoding, status, log, validator);
            }
        }
    }

    FileObject targetScriptFolder = targetDirectory.resolveFile(DesignDirectory.FOLDERNAME_SCRIPT);
    FileObject sourceScriptFolder = sourceDesignProvider.getScriptFolder();
    if (sourceScriptFolder.exists() && sourceScriptFolder.getType().equals(FileType.FOLDER)) {
        for (FileObject scriptTypeFolder : sourceScriptFolder.getChildren()) {
            FileObject overlayFolder = scriptTypeFolder.resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
            if (overlayFolder.exists()) {
                FileObject targetScriptTypeFolder = targetScriptFolder
                        .resolveFile(scriptTypeFolder.getName().getBaseName());
                determineChangedResources(WGDocument.TYPE_CSSJS, targetScriptTypeFolder, overlayFolder,
                        targetScriptTypeFolder, targetDirectory, sourceDesignProvider.getFileEncoding(),
                        targetEncoding, status, log, validator);
            }
        }
    }

    FileObject overlayFolder = sourceDesignProvider.getFilesFolder()
            .resolveFile(OverlayDesignProvider.OVERLAY_FOLDER);
    if (overlayFolder.exists()) {
        determineChangedFileContainerResources(targetFCFolder, overlayFolder, targetFCFolder, targetDirectory,
                null, null, status, log, validator);
    }

    return status;

}