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

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

Introduction

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

Prototype

public FileObject resolveFile(String path) throws FileSystemException;

Source Link

Document

Finds a file, relative to this file.

Usage

From source file:org.josso.tooling.gshell.install.installer.WeblogicInstaller.java

@Override
public void installComponentFromSrc(JOSSOArtifact artifact, boolean replace) throws InstallException {

    try {/*from  w w  w. ja va2s .  c o m*/

        if (!artifact.getBaseName().contains(this.wlVersionStr))
            return;

        // Prepare paths

        FileObject homeDir = getFileSystemManager().resolveFile(System.getProperty("josso-gsh.home"));
        FileObject srcDir = homeDir
                .resolveFile("dist/agents/src/josso-weblogic" + wlVersionStr + "-agent-mbeans-src");
        FileObject jossoLibDir = homeDir.resolveFile("dist/agents/bin");
        FileObject thrdPartyLibDir = jossoLibDir.resolveFile("3rdparty");

        FileObject descriptorFile = srcDir.resolveFile(
                "org/josso/wls" + wlVersionStr + "/agent/mbeans/JOSSOAuthenticatorProviderImpl.xml");
        FileObject mbeanFile = this.targetJOSSOMBeansDir
                .resolveFile("josso-weblogic" + wlVersionStr + "-agent-mbeans.jar");

        FileObject javaDir = getFileSystemManager().resolveFile(System.getProperty("java.home") + "/../");
        FileObject javaToolsFile = javaDir.resolveFile("lib/tools.jar");
        FileObject javaFile = javaDir.resolveFile("bin/java");

        getPrinter().printMsg("Using JAVA JDK at " + getLocalFilePath(javaDir));

        if (!javaDir.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaDir));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaDir));
        }

        if (!javaToolsFile.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaToolsFile));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaToolsFile));
        }

        if (!javaToolsFile.exists()) {
            getPrinter().printActionErrStatus("Generate", "WL MBeans Descriptors",
                    "JAVA JDK is required : " + getLocalFilePath(javaToolsFile));
            throw new InstallException("JAVA JDK is required for WL : " + getLocalFilePath(javaToolsFile));
        }

        // Java CMD and Class path :
        String javaCmd = getLocalFilePath(javaFile);

        String classpath = "";
        String pathSeparator = "";

        // JOSSO Jars
        for (FileObject child : jossoLibDir.getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;

            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        // JOSSO 3rd party Jars
        for (FileObject child : thrdPartyLibDir.getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;

            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        for (FileObject child : this.targetDir.resolveFile("server/lib").getChildren()) {
            if (!child.getName().getBaseName().endsWith(".jar"))
                continue;
            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        classpath += pathSeparator + getLocalFilePath(javaToolsFile);
        pathSeparator = System.getProperty("path.separator");

        for (FileObject child : javaDir.resolveFile("jre/lib").getChildren()) {
            classpath += pathSeparator + getLocalFilePath(child);
            pathSeparator = System.getProperty("path.separator");
        }

        //  ----------------------------------------------------------------
        // 1. Create the MBean Descriptor Files
        //  ----------------------------------------------------------------

        {
            /*
               <argument>-Dfiles=${basedir}/target/generated-sources</argument>
               <argument>-DMDF=${project.build.directory}/generated-sources/org/josso/wls92/agent/mbeans/JOSSOAuthenticatorProviderImpl.xml</argument>
               <argument>-DtargetNameSpace=urn:org:josso:wls92:agent:mbeans</argument>
               <argument>-DpreserveStubs=false</argument>
               <argument>-DcreateStubs=true</argument>
               <argument>-classpath</argument>
               <classpath/>
               <argument>weblogic.management.commo.WebLogicMBeanMaker</argument>
            */

            ProcessBuilder generateMBeanDescriptorProcessBuilder = new ProcessBuilder(javaCmd,
                    "-Dfiles=" + getLocalFilePath(srcDir), "-DMDF=" + getLocalFilePath(descriptorFile),
                    "-DtargetNameSpace=urn:org:josso:wls" + wlVersionStr + ":agent:mbeans",
                    "-DpreserveStubs=false", "-DcreateStubs=true", "-classpath", classpath,
                    "weblogic.management.commo.WebLogicMBeanMaker");

            log.info("Executing: " + generateMBeanDescriptorProcessBuilder.command());

            Process generateMBeanDescriptorProcess = generateMBeanDescriptorProcessBuilder.start();

            PumpStreamHandler generateMBeanHandler = new PumpStreamHandler(getPrinter().getIo().inputStream,
                    getPrinter().getIo().outputStream, getPrinter().getIo().errorStream);
            generateMBeanHandler.attach(generateMBeanDescriptorProcess);
            generateMBeanHandler.start();

            log.debug("Waiting for process to exit...");
            int statusDescr = generateMBeanDescriptorProcess.waitFor();

            log.info("Process exited w/status: " + statusDescr);

            generateMBeanHandler.stop();
            getPrinter().printActionOkStatus("Generate", "WL MBeans Descriptors", "");
        }

        //  ----------------------------------------------------------------
        // 2. Create the MBean JAR File
        //  ----------------------------------------------------------------
        {
            /*
            <argument>-Dfiles=${project.build.directory}/generated-sources</argument>
            <argument>-DMJF=${project.build.directory}/josso-weblogic92-agent-mbeans-${pom.version}.jar</argument>
            <argument>-DpreserveStubs=false</argument>
            <argument>-DcreateStubs=true</argument>
            <argument>-classpath</argument>
            <classpath/>
            <argument>weblogic.management.commo.WebLogicMBeanMaker</argument>
                    
            */

            ProcessBuilder generateMBeanJarProcessBuilder = new ProcessBuilder(javaCmd,
                    "-Dfiles=" + getLocalFilePath(srcDir), "-DMJF=" + getLocalFilePath(mbeanFile),
                    "-DpreserveStubs=false", "-DcreateStubs=true", "-classpath", classpath,
                    "weblogic.management.commo.WebLogicMBeanMaker");

            log.info("Executing: " + generateMBeanJarProcessBuilder.command());

            Process generateMBeanJarProcess = generateMBeanJarProcessBuilder.start();

            PumpStreamHandler generateMBeanJarHandler = new PumpStreamHandler(getPrinter().getIo().inputStream,
                    getPrinter().getIo().outputStream, getPrinter().getIo().errorStream);
            generateMBeanJarHandler.attach(generateMBeanJarProcess);
            generateMBeanJarHandler.start();

            log.debug("Waiting for process to exit...");
            int statusJar = generateMBeanJarProcess.waitFor();
            log.info("Process exited w/status: " + statusJar);

            generateMBeanJarHandler.stop();
            getPrinter().printActionOkStatus("Generate", "WL MBeans JAR", getLocalFilePath(mbeanFile));

        }
    } catch (Exception e) {
        getPrinter().printActionErrStatus("Generate", "WL MBeans", e.getMessage());
        throw new InstallException("Cannot generate WL MBeans Descriptors : " + e.getMessage(), e);
    }

    // 2. Create the MBean JAR File

    // 3. Install the file in the target platform

    // We need to create WL Mbeans using MBean Maker!

}

From source file:org.josso.tooling.gshell.install.test.VFSTest.java

@Test
public void testUnjarExploded() throws Exception {

    FileObject home = fsm.resolveFile(System.getProperty("java.home"));
    assert home.exists() : "JAVA_HOME folder not found ? " + home.getName().getFriendlyURI();

    FileObject target = fsm.resolveFile(new File(".").getAbsolutePath() + "/target");
    assert target.exists() : "target folder not found : " + target.getName().getFriendlyURI();

    FileObject targetFolder = target.resolveFile("unjar");
    targetFolder.createFolder();//w w w . ja  v  a 2 s.co  m

    FileObject srcFile = home.resolveFile("./lib/rt.jar");
    assert srcFile.exists() : "File not found " + srcFile.getURL();

    log.info("JAR FILE    : " + srcFile.getName().getFriendlyURI());
    log.info("ROOT        : " + srcFile.getName().getRoot());
    log.info("ROOT URI    : " + srcFile.getName().getRootURI());
    log.info("PATH DECODED: " + srcFile.getName().getPathDecoded());
    log.info("ROOT DECODED: " + srcFile.getName().getRoot().getPathDecoded());
    log.info("PATH        : " + srcFile.getName().getPath());

    assert installer.installJar(srcFile, targetFolder, "rt.jar-exploded", true,
            true) : "Cannot unjar exploded !";

}

From source file:org.josso.tooling.gshell.install.test.VFSTest.java

@Test
public void testUnjar() throws Exception {

    FileObject home = fsm.resolveFile(System.getProperty("java.home"));
    assert home.exists() : "JAVA_HOME folder not found ? " + home.getName().getFriendlyURI();

    FileObject target = fsm.resolveFile(new File(".").getAbsolutePath() + "/target");
    assert target.exists() : "target folder not found : " + target.getName().getFriendlyURI();

    FileObject targetFolder = target.resolveFile("unjar");
    targetFolder.createFolder();//from   www . ja  va 2  s .  co  m

    FileObject srcFile = home.resolveFile("./lib/rt.jar");
    assert srcFile.exists() : "File not found " + srcFile.getURL();

    assert installer.installJar(srcFile, targetFolder, "rt.jar", false, true) : "Cannot unjar !";

}

From source file:org.kalypso.simulation.grid.GridJobSubmitter.java

public void submitJob(final FileObject workingDir, final String executable, ISimulationMonitor monitor,
        String... arguments) throws SimulationException {
    if (monitor == null) {
        monitor = new NullSimulationMonitor();
    }// www  .j  av  a 2  s  . c o m

    // prepare streams
    FileObject stdoutFile = null;
    FileObject stderrFile = null;
    int returnCode = IStatus.ERROR;
    try {
        // stream stdout and stderr to files
        stdoutFile = workingDir.resolveFile("stdout");
        stderrFile = workingDir.resolveFile("stderr");

        // create process handle
        final String processFactoryId = "org.kalypso.simulation.gridprocess";
        // TODO: refactor so tempdir is created inside process
        final String tempDirName = workingDir.getName().getBaseName();
        final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, tempDirName,
                executable, arguments);
        // process.setProgressMonitor( new SimulationMonitorAdaptor( monitor ) );
        process.environment().put("OMP_NUM_THREADS", "4");

        final FileContent stdOutContent = stdoutFile.getContent();
        final OutputStream stdOut = stdOutContent.getOutputStream();
        final FileContent stdErrContent = stderrFile.getContent();
        final OutputStream stdErr = stdErrContent.getOutputStream();

        // stage-in files
        final FileSystemManager manager = workingDir.getFileSystem().getFileSystemManager();
        for (final URI einput : m_externalInputs.keySet()) {
            final FileObject inputFile = manager.resolveFile(getUriAsString(einput));
            final String destName = m_externalInputs.get(einput);
            if (destName != null) {
                final FileObject destFile = workingDir.resolveFile(destName);
                VFSUtil.copy(inputFile, destFile, null, true);
            } else {
                VFSUtil.copy(inputFile, workingDir, null, true);
            }
        }

        // start process
        returnCode = process.startProcess(stdOut, stdErr, null, null);
    } catch (final CoreException e) {
        // when process cannot be created
        throw new SimulationException("Could not create process.", e);
    } catch (final ProcessTimeoutException e) {
        e.printStackTrace();
    } catch (final FileNotFoundException e) {
        // can only happen when files cannot be created in tmpdir
        throw new SimulationException("Could not create temporary files for stdout and stderr.", e);
    } catch (final IOException e) {
        throw new SimulationException("Process I/O error.", e);
    } finally {
        // close files
        if (stdoutFile != null) {
            try {
                stdoutFile.getContent().close();
            } catch (final FileSystemException e) {
                // gobble
            }
        }
        if (stderrFile != null) {
            try {
                stderrFile.getContent().close();
            } catch (final FileSystemException e) {
                // gobble
            }
        }
    }

    // process failure handling
    if (returnCode != IStatus.OK) {
        String errString = "Process failed.";
        try {
            final FileContent content = stderrFile.getContent();
            final InputStream input2 = content.getInputStream();
            errString = errString + "\n" + IOUtils.toString(input2);
            content.close();
        } catch (final IOException e) {
            // ignore
        }
        monitor.setFinishInfo(returnCode, errString);
        throw new SimulationException(errString);
    } else {
        monitor.setFinishInfo(IStatus.OK, "Process finished successfully.");
    }
}

From source file:org.kalypso.simulation.grid.SimpleGridProcess.java

private FileObject createSandbox(final String tempDirName) throws FileSystemException {
    final String gridFtpRoot = "gridftp://" + m_targetHostName;
    final FileObject remoteRoot = m_manager.resolveFile(gridFtpRoot);
    final FileSystem fileSystem = remoteRoot.getFileSystem();

    // get home directory of user who created this job
    final String homeDirString = (String) fileSystem.getAttribute("HOME_DIRECTORY");
    final FileObject homeDir = remoteRoot.resolveFile(homeDirString);
    final FileObject workingDir = homeDir.resolveFile(tempDirName);
    workingDir.createFolder();/*w  w w  .j  a v  a  2  s.  co  m*/
    return workingDir;
}

From source file:org.kalypso.simulation.grid.TestGridFTP.java

public void testGridFTP() throws Exception {
    final FileSystemManager manager = VFSUtilities.getManager();

    final FileObject remoteRoot = manager.resolveFile("gsiftp://gramd1.gridlab.uni-hannover.de");
    final FileSystem fileSystem = remoteRoot.getFileSystem();
    final String homeDirString = (String) fileSystem.getAttribute(GsiFtpFileProvider.ATTR_HOME_DIR);
    final FileObject homeDir = remoteRoot.resolveFile(homeDirString);
    final String testDirName = "test";
    final FileObject localDir = manager.toFileObject(new File(testDirName));
    final FileObject remoteDir = homeDir.resolveFile(testDirName);
    final FileSynchronizer fileSynchronizer = new FileSynchronizer(localDir, remoteDir);
    fileSynchronizer.updateRemote();/* w w w . j  a  v  a  2s  .co  m*/
    fileSynchronizer.updateLocal();
}

From source file:org.kalypso.simulation.grid.TestSimpleGridProcess.java

public void testGridProcess() throws Exception {
    final String processFactoryId = "org.kalypso.simulation.gridprocess";
    System.setProperty("GLOBUS_LOCATION", "d:/workspace3.4/org.globus.ws.core");
    final String sandboxRoot = "testRma";

    final FileSystemManagerWrapper manager = VFSUtilities.getNewManager();

    final String rmaName = "RMA10Sk_35";

    final IProcess process = KalypsoCommonsExtensions.createProcess(processFactoryId, sandboxRoot, rmaName);
    process.environment().put("OMP_NUM_THREADS", "4");

    final String sandboxDirectory = process.getSandboxDirectory();
    final FileObject workingDir = manager.resolveFile(sandboxDirectory);
    copyFileToWorking(manager, workingDir, rmaName);
    copyFileToWorking(manager, workingDir, "model.2d");
    copyFileToWorking(manager, workingDir, "control.r10");

    process.startProcess(System.out, System.err, null, null);

    final FileObject resultFile = workingDir.resolveFile("A0001.2d");
    if (!resultFile.exists())
        fail("Result was not created!");

    manager.close();//from ww  w  .  j  ava 2  s .c o  m
}

From source file:org.objectweb.proactive.extensions.dataspaces.vfs.VFSNodeScratchSpaceImpl.java

private FileObject createEmptyDirectoryRelative(final FileObject parent, final String path)
        throws org.apache.commons.vfs.FileSystemException {

    FileObject f = parent.resolveFile(path);
    f.delete(Selectors.EXCLUDE_SELF);/*from w  ww . j  a  v a 2s .  co m*/
    f.createFolder();
    return f;
}

From source file:org.objectweb.proactive.extensions.dataspaces.vfs.VFSSpacesMountManagerImpl.java

/**
 * Internal method for resolving a file, will mount the file system if it is not mounted yet
 * @param uri virtual uri of the file/*from ww w.  j ava 2 s.co  m*/
 * @param ownerActiveObjectId Id of active object requesting this file
 * @param spaceRootFOUri root file system to use
 * @return
 * @throws FileSystemException
 */
private DataSpacesFileObject doResolveFile(final DataSpacesURI uri, final String ownerActiveObjectId,
        String spaceRootFOUri) throws FileSystemException {

    DataSpacesURI spacePart = uri.getSpacePartOnly();

    if (spaceRootFOUri != null) {
        ensureFileSystemIsMounted(spacePart, spaceRootFOUri);
    } else {
        try {
            readLock.lock();
            LinkedHashSet<String> los = accessibleFileObjectUris.get(spacePart);
            spaceRootFOUri = los.iterator().next();
        } finally {
            readLock.unlock();
        }
        ensureFileSystemIsMounted(spacePart, spaceRootFOUri);
    }

    final String relativeToSpace = uri.getRelativeToSpace();
    try {
        readLock.lock();

        if (!mountedSpaces.containsKey(spacePart)) {
            throw new FileSystemException("Could not access file that should exist (be mounted)");
        }

        final ConcurrentHashMap<String, FileObject> spaceRoots = mountedSpaces.get(spacePart);
        FileObject spaceRoot = spaceRoots.get(spaceRootFOUri);
        FileName dataSpaceVFSFileName = null;

        final FileObject file;
        // the dataspace "File name" (it is actually a File Path) is computed using the Virtual Space root
        if (dataSpaceVFSFileName == null) {
            dataSpaceVFSFileName = spaceRoot.getName();
        }
        try {
            if (relativeToSpace == null)
                file = spaceRoot;
            else
                file = spaceRoot.resolveFile(relativeToSpace);
            final DataSpacesLimitingFileObject limitingFile = new DataSpacesLimitingFileObject(file, spacePart,
                    spaceRoot.getName(), ownerActiveObjectId);
            return new VFSFileObjectAdapter(limitingFile, spacePart, dataSpaceVFSFileName,
                    new ArrayList<String>(accessibleFileObjectUris.get(spacePart)), spaceRootFOUri, this,
                    ownerActiveObjectId);
        } catch (org.apache.commons.vfs.FileSystemException x) {
            logger.error("[VFSMountManager] Could not access file within a space: " + uri);

            throw new FileSystemException(x);
        } catch (FileSystemException e) {
            ProActiveLogger.logImpossibleException(logger, e);
            throw new ProActiveRuntimeException(e);
        }

    } finally {
        readLock.unlock();
    }
}

From source file:org.ofbiz.commons.vfs.ofbiz.OfbizComponentProvider.java

public FileObject findFile(FileObject base, String name, FileSystemOptions properties)
        throws FileSystemException {
    try {/*  www. j  a v  a 2  s .  co m*/
        //name = name.replaceAll("^ofbiz-component://", "");
        int nameLength = name.length();
        int componentNameStart = 16;
        while (componentNameStart < nameLength && name.charAt(componentNameStart) == '/')
            componentNameStart++;
        if (componentNameStart == nameLength)
            throw new IllegalArgumentException("Invalid name(" + name + ")");
        int componentNameEnd = componentNameStart;
        while (componentNameEnd < nameLength && name.charAt(componentNameEnd) != '/')
            componentNameEnd++;
        if (componentNameEnd == nameLength)
            throw new IllegalArgumentException("Invalid name(" + name + ")");
        int restStart = componentNameEnd;
        while (restStart < nameLength && name.charAt(restStart) == '/')
            restStart++;
        if (restStart == nameLength)
            throw new IllegalArgumentException("Invalid name(" + name + ")");
        String componentName = name.substring(componentNameStart, componentNameEnd);
        URL location = FlexibleLocation.resolveLocation("component://" + componentName + "/.");
        FileObject ofbizBase = getContext().resolveFile(location.toString(), properties);
        return VFSUtil.toFileObject(ofbizBase.getFileSystem().getFileSystemManager(),
                ofbizBase.resolveFile(name.substring(restStart)).getURL().toString(), properties);
    } catch (Exception e) {
        FileSystemException fse = new FileSystemException(e.getMessage(), null, e);
        fse.initCause(e);
        throw fse;
    }
}