Grid Portlet Service Examples


List of Examples

1. Resource Examples Class
2. Returns a list of all the hardware resources in the resource registry
3. Returns a list of all the service resources in the resource registry
4. Returns a list of all the software resources in the resource registry
5. Returns a list of service resources on a given host
6. Returns a list of software resources on a given host
7. Returns a list of hardware accounts on a given host
8. File Examples Class
9. Testing whether a file object exists at a given path
10. Getting info for a file object at a given path
11. Getting a user's home directory on a given host
12. Listing files on a given host at a given path
13. Listing files in the home diectory of a user on a given host
14. Creating a directory
15. Renaming a file or directory
16. Copying a set of files
17. Moving a set of files
18. Deleting a file or directory
19. Uploading a file from the local filesystem to a given host
20. Downloading a file from a given host to the local filesystem
21. Copying a file from GridSphere's secure directory to a given host
22. Job Examples Class
23. Getting a list of all the jobs submitted for a given user
24. Getting a list of active jobs for a given user
25. Getting a user's home directory on a given host
26. Submitting a "/bin/date" job
27. Submitting a "/bin/ls" job, specifying the directory
28. Submitting a "/bin/echo" with a given argument
29. Submitting an mpi job for an executable and parameter file
30. Gss Examples Class
31. Returns the distinguished names of the resources to which the given credential is able to authenticate
32. Returns the distinguished names of the resources to which the given user is able to authenticate

Portlet Service Examples

This guide serves as a quick and easy reference for Grid Portlet Services examples and recipes. For your convience, these examples are also included in the Developer Guide, which discusses the design and architecture of Grid Portlets in more detail.

Resource Service Examples

[Important]Important

All of the examples listed below can be found in org.gridlab.gridsphere.examples.services.resource.ResourceExamples. Please refer to this class and its javadocs wherever you have download Grid Portlets. ResourceExamples contains two member variables for maintaining an instance of PortletLog and a reference to an instance of ResourceRegisryService, both of which are used in the examples that follow. For your reference, here is a code snipet showing these two variable declarations and the constructor for ResourceExamples.

Example 1. Resource Examples Class


public class ResourceExamples {

    // Portlet log is very good for debugging, we make ample use of it here!
    private PortletLog log = SportletLog.getInstance(JobExamples.class);
    // The resource registry service is used in all the examples below
    private ResourceRegistryService resourceRegistryService = null;

    /**
     * Constructs an instance of ResourceExamples.
     * @throws PortletServiceUnavailableException If unable to get required portlet services.
     */
    public ResourceExamples() throws PortletServiceUnavailableException {
        log.info("Creating JobExamples");
        PortletServiceFactory factory = SportletServiceFactory.getInstance();
        try {
            resourceRegistryService = (ResourceRegistryService)
                    factory.createPortletService(ResourceRegistryService.class, null, true);
        } catch (PortletServiceNotFoundException e) {
            log.error("Unable to initialize required portlet services", e);
            throw new PortletServiceUnavailableException(e);
        }
    }

    // See additional methods in the Java class file...
}

                

The rest of the examples below make use of the two member variables above.

Some basic methods

We start with some basic tasks that are useful to many applications.

Example 2. Returns a list of all the hardware resources in the resource registry


/**
 * Returns all the resources of type <code>HardwareResourceType</code> in the resource registry.
 * @return The list of hardware resources in the resource registry
 * @see HardwareResource
 */
public List getHardwareResources() {
    return resourceRegistryService.getResources(HardwareResourceType.INSTANCE);
}

                    

Example 3. Returns a list of all the service resources in the resource registry


/**
 * Returns all the resources of type <code>ServiceResourceType</code> in the resource registry.
 * @return The list of service resources in the resource registry
 * @see ServiceResource
 */
public List getServiceResources() {
    return resourceRegistryService.getResources(ServiceResourceType.INSTANCE);
}

                    

Example 4. Returns a list of all the software resources in the resource registry


/**
 * Returns all the resources of type <code>SoftwareResource</code> in the resource registry.
 * @return The list of software resources in the resource registry
 * @see SoftwareResource
 */
public List getSoftwareResources() {
    return resourceRegistryService.getResources(SoftwareResourceType.INSTANCE);
}

                    

Example 5. Returns a list of service resources on a given host


/**
 * Returns all the software resources on the hardware resource with the the given host.
 * Returns an empty list if no hardware resource is found for the given host.
 * @param host The hostname or internet address of the hardware resource
 * @return The list of service resources on the given host
 */
public List getServiceResources(String host) {
    HardwareResource resource = resourceRegistryService.getHardwareResourceByHost(host);
    if (resource == null) return new ArrayList();
    return resource.getServiceResources();
}

                    

Example 6. Returns a list of software resources on a given host


/**
 * Returns all the software resources on the hardware resource with the the given host.
 * Returns an empty list if no hardware resource is found for the given host.
 * @param host The hostname or internet address of the hardware resource
 * @return The list of software resources
 */
public List getSoftwareResources(String host) {
    HardwareResource resource = resourceRegistryService.getHardwareResourceByHost(host);
    if (resource == null) return new ArrayList();
    return resource.getSoftwareResources();
}

                    

Example 7. Returns a list of hardware accounts on a given host


/**
 * Returns all the hardware accounts on the hardware resource with the the given host.
 * Returns an empty list if no hardware resource is found for the given host.
 * @param host The hostname or internet address of the hardware resource
 * @return The list of software resources
 */
public List getHardwareAccounts(String host) {
    HardwareResource resource = resourceRegistryService.getHardwareResourceByHost(host);
    if (resource == null) return new ArrayList();
    return resource.getHardwareAccounts();
}

                    

File Service Examples

[Important]Important

All of the examples listed below can be found in org.gridlab.gridsphere.examples.file.FileExamples. Please refer to this class and its javadocs wherever you have download Grid Portlets. FileExamples contains two member variables for maintaining an instance of PortletLog and a reference to an instance of FileBrowserService, both of which are used in the examples that follow. For your reference, here is a code snipet showing these two variable declarations and the constructor for FileExamples.

Example 8. File Examples Class


public class FileExamples {

    // Portlet log is very good for debugging, we make ample use of it here!
    private PortletLog log = SportletLog.getInstance(FileExamples.class);
    // The file browser service is used in all the examples below
    private FileBrowserService fileBrowserService  = null;

    /**
     * Constructs an instance of FileExamples.
     * @throws PortletServiceUnavailableException If unable to get required portlet services.
     */
    public FileExamples() throws PortletServiceUnavailableException {
        log.info("Creating JobExamples");
        PortletServiceFactory factory = SportletServiceFactory.getInstance();
        try {
            fileBrowserService = (FileBrowserService)
                    factory.createPortletService(FileBrowserService.class, null, true);
        } catch (PortletServiceNotFoundException e) {
            log.error("Unable to initialize required portlet services", e);
            throw new PortletServiceUnavailableException(e);
        }
    }

    // See additional methods in the Java class file...
}

                

The rest of the examples below make use of the two member variables above.

Basic Examples

We start with some basic tasks that are useful to many applications.

Example 9. Testing whether a file object exists at a given path


    /**
     * Returns whether there is a file on the given host at the given path.
     * @param user The user
     * @param host The host
     * @param path The path (can be absolute or relative)
     * @return True if a file object exists on the given host at the given path, false otherwise
     * @throws FileException If there there is no file resource entry for the given host
     */
    public boolean exists(User user, String host, String path) throws FileException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        return fileBrowser.exists(path);
    }

                    

Example 10. Getting info for a file object at a given path


    /**
     * Returns a file location containg info about the associated
     * file object if there exists a file object on the given host
     * at the given path. If there is no file object at
     * the given path, this method will throw an exception.
     * @param user The user
     * @param host The host
     * @param path The path (can be absolute or relative)
     * @return A file location containing info about the associated file object
     * @throws FileException If there there is no file resource entry for the given host
     */
    public FileLocation info(User user, String host, String path) throws FileException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        return fileBrowser.info(path);
    }

                    

Example 11. Getting a user's home directory on a given host


    /**
     * Returns the home directory of the given user on the given host.
     * @param user The user
     * @param host The host
     * @return A list of <code>FileLocation</code> objects
     */
    public String getHomeDirectory(User user, String host) throws FileException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        // Simply return the home directory...
        return fileBrowser.getHomeDirectory();
    }

                    

Listing Files

To list files on a given resource, open a file browser on a given host and invoke one of the list methods provided.

Example 12. Listing files on a given host at a given path


        /**
         * Returns a list of file locations at at the given host and path.
         * @param user The user
         * @param host The host
         * @param path The path (can be absolute or relative)
         * @return A list of <code>FileLocation</code> objects
         * @see FileLocation
         * @throws FileException If there there is no file resource entry for the given host
         */
        public List listFiles(User user, String host, String path) throws FileException {
            // Create a file browser on the given host.
            // This will fail if there is no file resource entry for the given host.
            FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
            return fileBrowser.list(path);
        }

                    

Example 13. Listing files in the home diectory of a user on a given host


        /**
         * Returns a list of file locations in the home directory of the given user on the given host.
         * @param user The user
         * @param host The host
         * @return A list of <code>FileLocation</code> objects
         * @see FileLocation
         * @throws FileException If there there is no file resource entry for the given host
         */
        public List listFilesInHomeDir(User user, String host) throws FileException {
            // Create a file browser on the given host.
            // This will fail if there is no file resource entry for the given host.
            FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
            // If null or "" is given, then the user's home directory is assumed...
            return fileBrowser.list("");
        }

                    

File Tasks

Below we provide examples illustrating how to manipulate files. Note that in all the file tasks we illustrate here we block for completion of the task using the waitFor method on the Task interface. Please refer to the task section for how to perform and monitor these and other tasks asynchronously.

Example 14. Creating a directory


    /**
     * Creates a directory at the given path on the given host.
     * @param user The user
     * @param host The host
     * @param path The path of the directory (can be absolute or relative)
     * @throws FileException If there there is no file resource entry for the given host
     * @throws TaskException If the make directory task fails
     */
    public void makeDirectory(User user, String host, String path)
            throws FileException, TaskException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        FileMakeDir fileMakeDir = fileBrowser.makeDirectory(path);
        fileMakeDir.waitFor();
        if (fileMakeDir.getTaskStatus().equals(TaskStatus.FAILED)) {
            throw new TaskException("Failed to create directory with error " + fileMakeDir.getTaskStatusMessage());
        }
    }

                    

Example 15. Renaming a file or directory


    /**
     * Renames the file or directory at the given path on the given host with the given name.
     * @param user The user
     * @param host The host
     * @param path The path of the file to rename (can be absolute or relative)
     * @param newName The new name for the file
     * @throws MalformedURLException If the path results in an invalid url on the host
     * @throws FileException If there there is no file resource entry for the given host
     * @throws TaskException If the rename task fails
     */
    public void rename(User user, String host, String path, String newName)
            throws MalformedURLException, FileException, TaskException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        // Create a file location for the given path
        FileLocation fileLocation = new FileLocation("file:///" + path);
        FileNameChange fileNameChange = fileBrowser.rename(fileLocation, newName);
        fileNameChange.waitFor();
        if (fileNameChange.getTaskStatus().equals(TaskStatus.FAILED)) {
            throw new TaskException("Failed to rename file with error " + fileNameChange.getTaskStatusMessage());
        }
    }

                    

Example 16. Copying a set of files


    /**
     * Copies files at the source host and path to the destination host and path.
     * @param user The user
     * @param srcHost The source host
     * @param srcPath The source path (can be absolute or relative)
     * @param dstHost The destination host
     * @param dstPath The destination path (can be absolute or relative)
     * @throws FileException If there there is no file resource entry for the given host
     * @throws TaskException If the copy task fails
     */
    public void copy(User user, String srcHost, String srcPath, String dstHost, String dstPath)
            throws FileException, TaskException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser srcBrowser = fileBrowserService.createFileBrowser(user, srcHost);
        FileLocation srcLocation = srcBrowser.createFileLocation(srcPath);
        FileBrowser dstBrowser = fileBrowserService.createFileBrowser(user, dstHost);
        FileLocation dstLocation = dstBrowser.createFileLocation(dstPath);
        FileCopy copy = srcBrowser.copy(srcLocation, dstLocation);
        copy.waitFor();
        if (copy.getTaskStatus().equals(TaskStatus.FAILED)) {
            throw new TaskException("Failed to copy file with error " + copy.getTaskStatusMessage());
        }
    }

                    

Example 17. Moving a set of files


    /**
     * Moves files at the source host and path to the destination host and path.
     * @param user The user
     * @param srcHost The source host
     * @param srcPaths A list of source paths (as strings, can be absolute or relative)
     * @param dstHost The destination host
     * @param dstPath The destination path (can be absolute or relative)
     * @throws FileException If there there is no file resource entry for the given host
     * @throws TaskException If the move task fails
     */
    public void move(User user, String srcHost, List srcPaths, String dstHost, String dstPath)
            throws FileException, TaskException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser srcBrowser = fileBrowserService.createFileBrowser(user, srcHost);
        List srcLocations = new ArrayList();
        for (int ii = 0; ii < srcPaths.size(); ++ii) {
            String srcPath = (String)srcPaths.get(ii);
            FileLocation srcLocation = srcBrowser.createFileLocation(srcPath);
            srcLocations.add(srcLocation);
        }
        FileSet srcFileSet = new FileLocationSet(srcLocations);
        FileBrowser dstBrowser = fileBrowserService.createFileBrowser(user, dstHost);
        FileLocation dstLocation = dstBrowser.createFileLocation(dstPath);
        FileMove move = srcBrowser.move(srcFileSet, dstLocation);
        move.waitFor();
        if (move.getTaskStatus().equals(TaskStatus.FAILED)) {
            throw new TaskException("Failed to move files with error " + move.getTaskStatusMessage());
        }
    }

                    

Example 18. Deleting a file or directory


    /**
     * Deletes the file or directory at the given path on the given host.
     * @param user The user
     * @param host The host
     * @param path The path of the directory (can be absolute or relative)
     * @throws FileException If there there is no file resource entry for the given host
     * @throws TaskException If the delete task fails
     */
    public void delete(User user, String host, String path)
            throws FileException, TaskException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        FileLocation fileLocation = fileBrowser.createFileLocation(path);
        FileDeletion delete = fileBrowser.delete(fileLocation);
        delete.waitFor();
        if (delete.getTaskStatus().equals(TaskStatus.FAILED)) {
            throw new TaskException("Failed to delete file with error " + delete.getTaskStatusMessage());
        }
    }

                    

Example 19. Uploading a file from the local filesystem to a given host


/**
 * Uploads the file at the given source path to the given destination host and path
 * @param user The user
 * @param srcPath The source path (can be absolute or relative)
 * @param dstHost The destination host
 * @param dstPath The destination path (can be absolute or relative)
 * @throws FileException If there there is no file resource entry for the given host
 * @throws TaskException If the upload task fails
 */
public void upload(User user, String srcPath, String dstHost, String dstPath)
        throws FileException, TaskException {
    // Create a file browser on the given host.
    // This will fail if there is no file resource entry for the given host.
    FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, dstHost);
    FileLocation dstLocation = fileBrowser.createFileLocation(dstPath);
    FileUpload upload = fileBrowser.upload(srcPath, dstLocation);
    upload.waitFor();
    if (upload.getTaskStatus().equals(TaskStatus.FAILED)) {
        throw new TaskException("Failed to upload file with error " + upload.getTaskStatusMessage());
    }
}

                    

Example 20. Downloading a file from a given host to the local filesystem


/**
 * Downloads the file from the given source host and path to the given local path
 * @param user The user
 * @param srcHost The destination host
 * @param srcPath The source path (can be absolute or relative)
 * @param dstPath The destination path (can be absolute or relative)
 * @throws FileException If there there is no file resource entry for the given host
 * @throws TaskException If the download task fails
 */
public void download(User user, String srcHost, String srcPath, String dstPath)
        throws FileException, TaskException {
    // Create a file browser on the given host.
    // This will fail if there is no file resource entry for the given host.
    FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, srcHost);
    FileLocation srcLocation = fileBrowser.createFileLocation(srcPath);
    FileDownload download = fileBrowser.download(srcLocation, dstPath);
    download.waitFor();
    if (download.getTaskStatus().equals(TaskStatus.FAILED)) {
        throw new TaskException("Failed to download file with error " + download.getTaskStatusMessage());
    }
}

                    

Advanced Examples

The Grid Portlets file package offers many features for managing files on a portal and on remote resources. Here are more examples illustrating the kinds of tasks that can be performed with Grid Portlets.

Example 21. Copying a file from GridSphere's secure directory to a given host


/**
 * Copies from a remote resource to GridSphere's "secure directory". Note that the actual root
 * path of GridSphere's secure directory lies somewhere in ${WEBSERVER_HOME}/gridsphere/WEB-INF!
 * @param user The user
 * @param srcHost The source host
 * @param srcPath The source path (can be absolute or relative)
 * @param dstPath The destination path in the secure directory (can be absolute or relative)
 * @throws FileException If there there is no file resource entry for the given host
 * @throws TaskException If the copy task fails
 */
public void copyToSecureDirectory(User user, String srcHost, String srcPath, String dstPath)
        throws FileException, TaskException {
    // Create a file browser on the given host.
    // This will fail if there is no file resource entry for the given host.
    FileBrowser srcBrowser = fileBrowserService.createFileBrowser(user, srcHost);
    FileLocation srcLocation = srcBrowser.createFileLocation(srcPath);
    // Create a file browser on the local host.
    // The local host is represented by the <localhost-resource> entry in Resources.xml
    // This will fail if there is no file resource entry for the given host.
    FileBrowser dstBrowser = fileBrowserService.createFileBrowser(user, "localhost");
    FileLocation dstLocation = dstBrowser.createFileLocation(dstPath);
    FileCopy copy = srcBrowser.copy(srcLocation, dstLocation);
    copy.waitFor();
    if (copy.getTaskStatus().equals(TaskStatus.FAILED)) {
        throw new TaskException("Failed to copy file with error " + copy.getTaskStatusMessage());
    }
}

                    

Job Service Examples

Because Grid Portlets has a layered architecture, there is usually more than one way to acheive a given a objective. Here we illustrate the recommended approach for some of the most common job-related operations.

[Important]Important

All of the examples listed below can be found in org.gridlab.gridsphere.examples.services.job.JobExamples. Please refer to this class and its javadocs wherever you have download Grid Portlets. JobExamples contains two member variables for maintaining an instance of PortletLog and a reference to an instance of JobSubmissionService, both of which are used in the examples that follow. For your reference, here is a code snipet showing these two variable declarations and the constructor for JobExamples.

Example 22. Job Examples Class


public class JobExamples {

    // Portlet log is very good for debugging, we make ample use of it here!
    private PortletLog log = SportletLog.getInstance(JobExamples.class);
    // The job submission service is used in all the examples below
    private JobSubmissionService jobSubmissionService  = null;

    /**
     * Constructs an instance of JobExamples.
     * @throws PortletServiceUnavailableException If unable to get required portlet services.
     */
    public JobExamples() throws PortletServiceUnavailableException {
        log.info("Creating JobExamples");
        PortletServiceFactory factory = SportletServiceFactory.getInstance();
        try {
            jobSubmissionService = (JobSubmissionService)
                    factory.createPortletService(JobSubmissionService.class, null, true);
        } catch (PortletServiceNotFoundException e) {
            log.error("Unable to initialize required portlet services", e);
            throw new PortletServiceUnavailableException(e);
        }
    }

    // See additional methods in the Java class file...
}

                

The rest of the examples below make use of the two member variables above.

Basic Examples

We start with some basic tasks that are useful to many applications.

Example 23. Getting a list of all the jobs submitted for a given user


/**
 * Returns all the jobs submitted by the given user.
 * @param user The user
 * @return A list of <code>Job</code> objects.
 */
public List getJobList(User user) {
    // Note one could specify a particular job type if so desired
    // so that this method only returned jobs of the given type.
    return jobSubmissionService.getJobs(user, JobType.INSTANCE);
}

                    

Example 24. Getting a list of active jobs for a given user


/**
 * Returns all the "active" jobs for the given user. Active jobs are jobs
 * with a task status of "ACTIVE".
 * @param user The user
 * @return A list of <code>Job</code> objects.
 */
public List getActiveJobList(User user) {
    // Note one could specify a particular job type if so desired
    // so that this method only returned jobs of the given type.
    Iterator jobIterator = jobSubmissionService.getJobs(user, JobType.INSTANCE).iterator();
    List activeJobList = new ArrayList();
    while (jobIterator.hasNext()) {
        Job job = (Job)jobIterator.next();
        if (job.getTaskStatus().equals(TaskStatus.ACTIVE)) {
            activeJobList.add(job);
        }
    }
    return activeJobList;
}

                    

Example 25. Getting a user's home directory on a given host


    /**
     * Returns the home directory of the given user on the given host.
     * @param user The user
     * @param host The host
     * @return A list of <code>FileLocation</code> objects
     */
    public String getHomeDirectory(User user, String host) throws FileException {
        // Create a file browser on the given host.
        // This will fail if there is no file resource entry for the given host.
        FileBrowser fileBrowser = fileBrowserService.createFileBrowser(user, host);
        // Simply return the home directory...
        return fileBrowser.getHomeDirectory();
    }

                    

Simple Job Examples

The job package is best illustrated with specific examples. Below we provide just a few. The behavior of the job package relies ultimately on the job resources made available to Grid Portlets. In general, most job submission resources, including all based on Globus, should support the kind of examples shown here.

Note that in all the file tasks we illustrate here we block for completion of the task using the waitFor method on the Task interface. Please refer to the task section for how to perform and monitor these and other tasks asynchronously.

Note, also, in order to get the output of a job, we use the FileReaderUtil in the file package.

Example 26. Submitting a "/bin/date" job


    /**
     * Provides an example of submitting "/bin/date" for a given user to
     * a given host. Illustrates how to do a simple job submission and
     * get the job output as a string. Returns null if the job status
     * is failed when the job ends.
     * @param user The user
     * @param host The host on which to run /bin/date
     * @return Returns the value return by the job, null if the job failed.
     * @throws PortletException If a exception occurs during job submission or getting job output.
     */
    public String doBinDate(User user, String host) throws PortletException {
        String answer = null;
        try {
            // Create a job spec using the generic job type
            // Note one could specify a particular job type if so desired
            log.debug("Creating job spec for " + user.getUserName());
            JobSpec jobSpec = jobSubmissionService.createJobSpec(JobType.INSTANCE);
            jobSpec.setUser(user);
            FileLocation executable = new FileLocation("/bin/date");
            jobSpec.setExecutableLocation(executable);
            jobSpec.setHostName(host);
            log.debug("Submiting /bin/date to  " + host);
            Job job = jobSubmissionService.submitJob(jobSpec);
            job.waitFor();
            if (job.getTaskStatus().equals(TaskStatus.FAILED)) {
                log.error("Job failed with message " + job.getTaskStatusMessage());
                return null;
            }
            FileLocation stdout = job.getStdoutLocation();
            if (stdout != null) {
                log.debug("Reading stdout from " + stdout.getUrl());
                FileHandle fileHandle = new FileHandle(stdout);
                answer = fileHandle.readContents(user);
            }
        } catch (JobException e) {
            log.error("Unable to submit job", e);
            throw new PortletException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("Unable to create file location", e);
            throw new PortletException(e.getMessage());
        } catch (IOException e) {
            log.error("Unable to read stdout location", e);
            throw new PortletException(e.getMessage());
        }
        log.debug("answer = " + answer);
        return answer;
    }

                    

Example 27. Submitting a "/bin/ls" job, specifying the directory


    /**
     * Provides an example of submitting "/bin/ls" for a given user to
     * a given host with a given directory. Illustrates how to set the
     * directory in which to run a job and get the job output as a string.
     * Returns null if the job status is failed when the job ends.
     * @param user The user
     * @param host The host on which to run /bin/ls
     * @param directory The directory in which to run /bin/ls
     * @return Returns the value return by the job, null if the job failed.
     * @throws PortletException If a exception occurs during job submission or getting job output.
     */
    public String doBinLs(User user, String host, String directory) throws PortletException {
        PortletLog log = SportletLog.getInstance(getClass());
        String answer = null;
        try {
            // Create a job spec using the generic job type
            // Note one could specify a particular job type if so desired
            log.debug("Creating job spec for " + user.getUserName());
            JobSpec jobSpec = jobSubmissionService.createJobSpec(JobType.INSTANCE);
            jobSpec.setUser(user);
            FileLocation executable = new FileLocation("/bin/ls");
            jobSpec.setDirectory(directory);
            jobSpec.setExecutableLocation(executable);
            jobSpec.setHostName(host);
            log.debug("Submiting /bin/ls to  " + host + " in " + directory);
            Job job = jobSubmissionService.submitJob(jobSpec);
            job.waitFor();
            if (job.getTaskStatus().equals(TaskStatus.FAILED)) {
                log.error("Job failed with message " + job.getTaskStatusMessage());
                return null;
            }
            FileLocation stdout = job.getStdoutLocation();
            if (stdout != null) {
                log.debug("Reading stdout from " + stdout.getUrl());
                FileHandle fileHandle = new FileHandle(stdout);
                answer = fileHandle.readContents(user);
            }
        } catch (JobException e) {
            log.error("Unable to submit job", e);
            throw new PortletException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("Unable to create file location", e);
            throw new PortletException(e.getMessage());
        } catch (IOException e) {
            log.error("Unable to read stdout location", e);
            throw new PortletException(e.getMessage());
        }
        log.debug("answer = " + answer);
        return answer;
    }

                    

Example 28. Submitting a "/bin/echo" with a given argument


    /**
     * Provides an example of submitting "/bin/echo" for a given user to
     * a given host with a given message. Illustrates how to pass an argument
     * to a job and get the job output as a string. Returns null if
     * the job status is failed when the job ends.
     * @param user The user
     * @param host The host on which to run /bin/ls
     * @param message The message to echo
     * @return Returns the value return by the job, null if the job failed.
     * @throws PortletException If a exception occurs during job submission or getting job output.
     */
    public String doBinEcho(User user, String host, String message) throws PortletException {
        PortletLog log = SportletLog.getInstance(getClass());
        String answer = null;
        try {
            // Create a job spec using the generic job type
            // Note one could specify a particular job type if so desired
            log.debug("Creating job spec for " + user.getUserName());
            JobSpec jobSpec = jobSubmissionService.createJobSpec(JobType.INSTANCE);
            jobSpec.setUser(user);
            FileLocation executable = new FileLocation("/bin/echo");
            jobSpec.setExecutableLocation(executable);
            jobSpec.addArgument(message);
            jobSpec.setHostName(host);
            log.debug("Submiting /bin/echo " + message + " to " + host);
            Job job = jobSubmissionService.submitJob(jobSpec);
            job.waitFor();
            if (job.getTaskStatus().equals(TaskStatus.FAILED)) {
                log.error("Task failed with message " + job.getTaskStatusMessage());
                return null;
            }
            FileLocation stdout = job.getStdoutLocation();
            if (stdout != null) {
                log.debug("Reading stdout from " + stdout.getUrl());
                FileHandle fileHandle = new FileHandle(stdout);
                answer = fileHandle.readContents(user);
            }
        } catch (JobException e) {
            log.error("Unable to submit job", e);
            throw new PortletException(e.getMessage());
        } catch (MalformedURLException e) {
            log.error("Unable to create file location", e);
            throw new PortletException(e.getMessage());
        } catch (IOException e) {
            log.error("Unable to read stdout location", e);
            throw new PortletException(e.getMessage());
        }
        log.debug("answer = " + answer);
        return answer;
    }

                    

Example 29. Submitting an mpi job for an executable and parameter file


    /**
     * Provides an example of submitting an mpi job to run a given executable
     * and a given parameter file on a given number of cpus. In this case, we
     * don't want to get job output. Instead we simply want to get a handle
     * to the job that results.
     * @param user The user
     * @param host The host on which to run the executable
     * @param numCpus The number of cpus
     * @param executable The executable file location
     * @param executable The parameter file location
     * @return Returns the value return by the job, null if the job failed.
     * @throws PortletException If a exception occurs during job submission or getting job output.
     */
    public Job submitMpiJob(User user,
                            String host,
                            int numCpus,
                            FileLocation executable,
                            FileLocation parameterFile) throws PortletException {
        PortletLog log = SportletLog.getInstance(getClass());
        Job job = null;
        try {
            // Create a job spec using the generic job type
            // Note one could specify a particular job type if so desired
            log.debug("Creating job spec for " + user.getUserName());
            JobSpec jobSpec = jobSubmissionService.createJobSpec(JobType.INSTANCE);
            jobSpec.setUser(user);
            // Set the executable location
            // The executable could be on the local host
            // on the same host as job, or some other host
            jobSpec.setExecutableLocation(executable);
            // Add the parameter file name as an argument
            jobSpec.addArgument(parameterFile.getFileName());
            // Add the parameter file as a file stage parameter
            // The parameter file will be staged to same directory
            // in which job is run
            jobSpec.addFileStageParameter(parameterFile);
            // Set host name
            jobSpec.setHostName(host);
            // Set execution method to mpi
            jobSpec.setExecutionMethod(ExecutionMethod.MPI);
            // Set cpu count to given num of cpus
            jobSpec.setCpuCount(new Integer(numCpus));
            // Submit the job
            log.debug("Executing " + executable.getUrl() + " on " + host);
            job = jobSubmissionService.submitJob(jobSpec);
        } catch (JobException e) {
            log.error("Unable to submit job", e);
            throw new PortletException(e.getMessage());
        }
        return job;
    }

                    

GSS Examples

[Important]Important

All of the examples listed below can be found in org.gridlab.gridsphere.examples.services.security.gss.GssExamples. Please refer to this class and its javadocs wherever you have download Grid Portlets. ResourceExamples contains two member variables for maintaining an instance of PortletLog, a reference to CredentialManagerService and a reference to an instance of ResourceRegisryService, both of which are used in the examples that follow. For your reference, here is a code snipet showing these threee variable declarations and the constructor for ResourceExamples.

Example 30. Gss Examples Class


public class GssExamples {

    // Portlet log is very good for debugging, we make ample use of it here!
    private PortletLog log = SportletLog.getInstance(GssExamples.class);
    // The credential schedulerer service is used in all the examples below
    private CredentialManagerService credentialManagerService = null;
    // The resource registry service is used in all the examples below
    private ResourceRegistryService resourceRegistryService = null;

    /**
     * Constructs an instance of GssExamples.
     * @throws PortletServiceUnavailableException If unable to get required portlet services.
     */
    public GssExamples() throws PortletServiceUnavailableException {
        log.info("Creating JobExamples");
        PortletServiceFactory factory = SportletServiceFactory.getInstance();
        try {
            credentialManagerService = (CredentialManagerService)
                    factory.createPortletService(CredentialManagerService.class, null, true);
            resourceRegistryService = (ResourceRegistryService)
                    factory.createPortletService(ResourceRegistryService.class, null, true);
        } catch (PortletServiceNotFoundException e) {
            log.error("Unable to initialize required portlet services", e);
            throw new PortletServiceUnavailableException(e);
        }
    }

    // See additional methods in the Java class file...
}

                

The rest of the examples below make use of the three member variables above.

Some basic examples

Example 31. Returns the distinguished names of the resources to which the given credential is able to authenticate


/**
 * Returns the distinguished names of all the resources to which the given
 * credential successfully authenticates. If there are no gss enabled
 * resources in the resource registry, this method will return an empty list.
 * @param credential The credential
 * @return The list of resource of dns (strings)
 */
public List getValidGssEnabledResourceDns(GSSCredential credential) {
    List validResourceList = new ArrayList();
    Iterator gssResourceIter = resourceRegistryService.getResources(GssEnabledResourceType.INSTANCE).iterator();
    while (gssResourceIter.hasNext()) {
        GssEnabledResource gssResource = (GssEnabledResource)gssResourceIter.next();
        String resourceDn = gssResource.getDn();
        log.debug("Testing whether credential authenticates to " + resourceDn);
        try {
            gssResource.authenticates(credential);
            validResourceList.add(resourceDn);
        } catch (Exception e) {
            log.debug("Credential failed to authenticate to resource " + resourceDn + " with error " + e.getMessage());
        }
    }
    return validResourceList;
}

                    

Example 32. Returns the distinguished names of the resources to which the given user is able to authenticate


/**
 * Returns the distinguished names of all the resources to which the given user
 * is able to authenticate with his/her active credentials. If the user
 * has no active credentials or there are no gss enabled resources in
 * the resource registry, this method will return an empty list.
 * @param user The user
 * @return The list of resource of dns (strings)
 */
public List getValidGssEnabledResourceDns(User user) {
    List validResourceList = new ArrayList();
    Iterator credentialIter = credentialManagerService.getActiveCredentials(user).iterator();
    while (credentialIter.hasNext()) {
        GSSCredential credential = (GSSCredential)credentialIter.next();
        validResourceList.addAll(getValidGssEnabledResourceDns(credential));
    }
    return validResourceList;
}