You are here: FME Server Developer's Guide > Developing with the Core APIs > Java > Java Example

Java Example

/*==============================================================================

Name : FMEServerAPIDemo.java

System : FME Server API

Language : Java

Purpose : FMEServerAPIDemo sample application

 

Author              Date          Changes made

------------------  ------------  -------------------------------

Sample              Jun 19, 2008   Original Definition

 

Copyright (c) 1994 - 2011, Safe Software Inc.

All Rights Reserved

The entire risk as to the results and performance of the software,

supporting text and other information contained in this file

(collectively called the "Software") is with the user. Although

Safe Software Incorporated has used considerable efforts in preparing

the Software, Safe Software Incorporated does not warrant the

accuracy or completeness of the Software. In no event will Safe Software

Incorporated be liable for damages, including loss of profits or

consequential damages, arising out of the use of the Software.

==============================================================================*/

import java.io.BufferedReader;

import java.io.File;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Map;

import COM.safe.fmeserver.api.*;

public class FMEServerAPIDemo

{

// The repository manager

private IFMERepositoryManager repositoryMgr_ = null;

 

// Used to read content from the user

private BufferedReader br_ = null;

 

// The server session

private IFMEServerSession serverSession_ = null;

 

private String userid_ = null;

private String password_ = null;

private String clientid_ = "app_apidemo";

 

public FMEServerAPIDemo(String host, int port) throws FMEServerException

{

serverSession_ = FMEServer.createServerSession();

 

br_ = new BufferedReader(new InputStreamReader(System.in));

 

try

{

getConnectionInfo();

}

catch (IOException e)

{

System.err.println(e.getMessage());

}

 

IFMEServerConnectionInfo connectionInfo_ = serverSession_.createServerConnectionInfo(host, port, userid_, password_);

Map<String, String> directives = new HashMap<String, String>();

directives.put(IFMEServerAPIConstants.kKeywordClientID, clientid_);

serverSession_.init(connectionInfo_, (Map<String, String>)(directives));

 

repositoryMgr_ = serverSession_.getRepositoryManager();

 

}

 

public void getConnectionInfo() throws IOException

{

System.out.println("Please enter server connection credentials.");

System.out.print("UserId:");

userid_ = br_.readLine();

 

if (!userid_.equals("") )

{

System.out.print("Password:");

password_ = br_.readLine();

}

}

 

public void execute()

{

displayMainMenu();

try

{

int choice = getMenuChoice();

executeMenuChoice(choice);

}

catch (NumberFormatException e)

{

System.err.println("Invalid input!");

}

catch (Exception e)

{

System.err.println(e.getMessage());

}

}

 

private void cleanup()

{

if (serverSession_ != null)

{

try

{

serverSession_.disconnect();

serverSession_ = null;

}

catch(FMEServerException e)

{

System.err.println(e.getMessage());

}

}

}

 

private void displayMainMenu()

{

System.out.print("\n\n"s

+ "===FME Server API Demo===\n"

+ "1. List available repositories\n"

+ "2. Add a repository\n"

+ "3. Remove a repository\n"

+ "4. List available workspaces\n"

+ "5. Add a workspace\n"

+ "6. Update a workspace\n"

+ "7. Get a workspace\n"

+ "8. Remove a workspace\n"

+ "9. List resources of a workspace\n"

+ "10. Add a resource\n"

+ "11. Update a resource\n"

+ "12. Get a resource\n"

+ "13. Remove a resource\n"

+ "14. List available services\n"

+ "15. Add a service\n"

+ "16. Update a service\n"

+ "17. Remove a service\n"

+ "18. Run a workspace\n"

+ "0. Quit\n"

+ "\nSELECT: ");

}

 

private int getMenuChoice() throws NumberFormatException, IOException

{

return Integer.parseInt(br_.readLine());

}

 

private void executeMenuChoice(int choice) throws Exception

{

switch (choice)

{

case 1:

listRepositories();

break;

case 2:

addRepository();

break;

case 3:

removeRepository();

break;

case 4:

listWorkspaces();

break;

case 5:

addWorkspace();

break;

case 6:

updateWorkspace();

break;

case 7:

getWorkspace();

break;

case 8:

removeWorkspace();

break;

case 9:

listResources();

break;

case 10:

addResource();

break;

case 11:

updateResource();

break;

case 12:

getResource();

break;

case 13:

removeResource();

break;

case 14:

listServices();

break;

case 15:

addService();

break;

case 16:

updateService();

break;

case 17:

removeService();

break;

case 18:

runWorkspace();

break;

case 0:

cleanup();

System.exit(0);

default:

System.err.println("Invalid option!");

return;

}

System.out.println("\nThe operation was a success");

}

 

private void listRepositories() throws Exception

{

ArrayList<IFMERepository> repositoryList = repositoryMgr_.getRepositories(null);

for (IFMERepository repository : repositoryList)

{

System.out.format("%s %s\n",

repository.getName(),

repository.getDescription());

}

}

 

private void addRepository() throws Exception

{

String name = getInput("Please enter the name for the new repository:");

String description = getInput("Please enter the description for the new repository:");

 

if (!repositoryMgr_.repositoryExists(name))

{

repositoryMgr_.addRepository(name, description);

}

else

{

throw new FMEServerException("There is already a repository with this name!");

}

}

 

private void removeRepository() throws Exception

{

String name = getInput("Please enter the name for the repository to remove:");

 

if (!repositoryMgr_.removeRepository(name))

{

throw new FMEServerException("There is no repository with this name!");

}

}

 

private void listWorkspaces() throws Exception

{

ArrayList<IFMERepository> repositories = repositoryMgr_.getRepositories(null);

for (IFMERepository repository : repositories)

{

ArrayList<IFMEWorkspaceSummary> workspaceSummaries = repository.getWorkspaceSummaries(null);

for (IFMEWorkspaceSummary workspaceSummary : workspaceSummaries)

{

System.out.format("Repository:%s %s %s ON:%s\n",

repository.getName(),

workspaceSummary.getTitle(),

workspaceSummary.getName(),

workspaceSummary.getIsEnabled());

}

}

}

 

private void addWorkspace() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the new workspace:");

String workspaceFilePath = getInput("Please enter the file path for the new workspace to add:");

String workspaceName = new File(workspaceFilePath).getName();

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (!repository.itemExists(workspaceName))

{

repository.addItem(workspaceName, workspaceFilePath);

}

else

{

throw new FMEServerException("There is already a workspace with this name!");

}

}

private void updateWorkspace() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the workspace to update:");

String workspaceFilePath = getInput("Please enter the file path for the workspace to update:");

String workspaceName = new File(workspaceFilePath).getName();

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (repository.itemExists(workspaceName))

{

repository.updateItem(workspaceName, workspaceFilePath);

}

else

{

throw new FMEServerException("There is no workspace with this file name!");

}

}

private void getWorkspace() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the workspace to get:");

String workspaceName = getInput("Please enter the name of the workspace to get:");

String workspaceFilePath = getInput("Please enter the local file path for the workspace to get:");

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (repository.itemExists(workspaceName))

{

repository.getItem(workspaceName, workspaceFilePath);

}

else

{

throw new FMEServerException("There is no workspace with this file name!");

}

}

 

private void removeWorkspace() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the workspace to remove:");

String workspaceName = getInput("Please enter the name of the workspace to remove:");

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (!repository.removeItem(workspaceName))

{

throw new FMEServerException("There is no workspace with this file name!");

}

}

 

private void listResources() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the resources:");

String workspaceName = getInput("Please enter the workspace name for the resources:");

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

IFMEWorkspace workspace = repository.getWorkspace(workspaceName);

 

ArrayList<IFMEResource> resources = workspace.getResources();

for (IFMEResource resource : resources)

{

System.out.format("%s %s\n",

resource.getName(),

resource.getDescription());

}

}

 

private void addResource() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the new resource:");

String workspaceName = getInput("Please enter the workspace name for the new resource:");

String resourceFilePath = getInput("Please enter the file path for the new resource to add:");

String resourceName = new File(resourceFilePath).getName();

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (!repository.resourceExists(workspaceName, resourceName))

{

repository.addResource(workspaceName, resourceName, resourceFilePath);

}

else

{

throw new FMEServerException("There is already a resource with this name!");

}

}

 

private void updateResource() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the resource to update:");

String workspaceName = getInput("Please enter the workspace name for the resource to update:");

String resourceFilePath = getInput("Please enter the file path for the resource to update:");

String resourceName = new File(resourceFilePath).getName();

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (repository.resourceExists(workspaceName, resourceName))

{

repository.updateResource(workspaceName, resourceName, resourceFilePath);

}

else

{

throw new FMEServerException("There is no resource with this name!");

}

}

 

private void getResource() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the resource to get:");

String workspaceName = getInput("Please enter the workspace name for the resource to get:");

String resourceName = getInput("Please enter the resource name for the resource to get:");

String resourceFilePath = getInput("Please enter the local file path for the resource to get:");

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (repository.resourceExists(workspaceName, resourceName))

{

repository.getResource(workspaceName, resourceName, resourceFilePath);

}

else

{

throw new FMEServerException("There is no resource with this name!");

}

}

 

private void removeResource() throws Exception

{

String repositoryName = getInput("Please enter the repository name for the resource to remove:");

String workspaceName = getInput("Please enter the workspace name for the resource to remove:");

String resourceName = getInput("Please enter the resource name for the resource to remove:");

 

IFMERepository repository = repositoryMgr_.getRepository(repositoryName);

if (!repository.removeResource(workspaceName, resourceName))

{

throw new FMEServerException("There is no resource with this name!");

}

}

 

private void listServices() throws Exception

{

ArrayList<IFMEService> services = repositoryMgr_.getServices(null);

for (IFMEService service : services)

{

System.out.format("%s %s %s ON:%s %s\n",

service.getDisplayName(),

service.getName(),

service.getURLPattern(),

service.getIsEnabled(),

service.getDescription());

}

}

 

private void addService() throws Exception

{

String name = getInput("Please enter the name of the new service:");

String urlPattern = getInput("Please enter the URL pattern of the new service:");

String displayName = getInput("Please enter the display name of the new service:");

String description = getInput("Please enter the description of the new service:");

 

IFMEService service = serverSession_.createService(name, displayName, description, urlPattern);

 

if (!repositoryMgr_.serviceExists(name))

{

repositoryMgr_.addService(service);

}

else

{

throw new FMEServerException("There is already a service with this name!");

}

}

 

private void updateService() throws Exception

{

String name = getInput("Please enter the name of the service to update:");

String urlPattern = getInput("Please enter the URL pattern of the service to update:");

String displayName = getInput("Please enter the display name of the service to update:");

String description = getInput("Please enter the description of the service to update:");

 

IFMEService service = serverSession_.createService(name, displayName, description, urlPattern);

 

if (repositoryMgr_.serviceExists(name))

{

repositoryMgr_.updateService(service);

}

else

{

throw new FMEServerException("There is no service with this name!");

}

}

 

private void removeService() throws Exception

{

String name = getInput("Please enter the name of the service to remove:");

 

if (!repositoryMgr_.removeService(name))

{

throw new FMEServerException("There is no service with this name!");

}

}

 

private void runWorkspace() throws Exception

{

IFMETransformationManager transformer = serverSession_.getTransformationManager();

 

// Create an IFMETransformationnRequest object to encapsulate our

// transformation request that will be submitted to the server. The

// createTransformationRequest(...) method expects three parameters: 1.

// The name of an FME Server node subsection, as defined in the node's

// configuration. SERVER_CONSOLE_CLIENT is one such subsection that is

// part of the default configuration that ships with the FME Server. Each

// subsection specifies various processing directives (e.g., the folder

// where output should be placed). For information on the different

// subsections, please refer to

// &lt;FMEServer-InstallDir&gt;\Server\fmeServerConfig.txt 2. The unique name

// for the repository that contains the mapping file or command file to be

// executed by FME.

String repositoryName = getInput("Please enter the repository name for the workspace to run:");

String workspaceName = getInput("Please enter the name of the workspace to run:");

 

IFMETransformationRequest req

= serverSession_.createTransformationRequest("SERVER_CONSOLE_CLIENT",

repositoryName,

workspaceName);

 

 

// Set published parameters that have been exposed by the workspace. Both

// the name of the published parameter and the desired value are simple

// Strings, even if the value happens to have a numeric interpretation.

// Here, we set a published parameter called MAX_FEATURES that controls

// how many features will be read in from the source dataset(s). Published

// parameters depend on the workspace that is being run.

 

req.setPublishedParameter("MAX_FEATURES", "2000");

 

 

// We can also set certain transformation manager directives that

// determine how our transformation request will be processed. Unlike

// published parameters, which are determined by each workspace's author

// and thus vary from one workspace to another, the available directives

// are constant for all transformation requests. A complete list of

// directives can be found in the FME Server documentation. Here, we set a

// high priority for this job to suggest that it should be given

// precedence over other, lower-priority, jobs.

 

req.setTMDirective("priority", 42);

System.out.println("Sending a transformation request to the FME Server...\n");

 

 

// Submit the transformation request. This method will block until

// transformation results are available. (Users who wish to submit jobs

// asynchronously should instead use the submitJob(...) method.) The

// returned results are stored in an IFMETransformationResult object,

// which is the companion to the IFMETransformationRequest object that we

// submitted.

 

IFMETransformationResult result = transformer.transactJob(req);

 

 

// The transformation result object receives a result string from the

// server and parses it to extract many different pieces of information

// about the job result. However, users who wish to do their own parsing

// of the raw server response, or wish to log this string, may obtain the

// unparsed response string using the getFMEServerResponse() method. Here,

// we use that method to print out the response string to the standard

// output.

 

System.out.println("Response received:\n");

System.out.println(result.getFMEServerResponse());

System.out.println();

 

 

// The IFMETransformationResult interface defines many accessor methods

// for retrieving specific information from the parsed result. We only

// demonstrate a small subset of those methods here; a full list is

// available in the FME Server API documentation. The

// getTransformationSuccess() method returns true if, and only if, the

// transformation was successful. Here, we check to see if the

// transformation was successful and then print out a message accordingly.

 

if (!result.getTransformationSuccess())

{

 

// The transformation was not successful. We inform the user of this

// and then use getStatusMessage() to get the error message that was

// returned by the server (e.g., "File austin.fmw could not be found.")

 

throw new FMEServerException("Transformation failed.\nThe error was: "

+ result.getStatusMessage());

}

else

{

// The transformation was successful. We inform the user of this.

System.out.println("Transformation successful!");

 

 

// The transformation result object contains many name-value pairs that

// are extracted from the SUCCESS_RESPONSE defined in the FME Server

// node subsection. In addition to these pairs, there are also several

// name-value pairs added by the server: the time that the job was sent

// to an FME Server node for processing (timeStarted), the job ID (id),

// etcetera. The getAllProperties() method returns a map of all these

// name-value pairs. Here, we iterate over this map -- using its entry

// set -- and simply print out its contents in the form "name = value".

 

System.out.println("The following information was parsed from the response:\n");

System.out.println("============");

for (Map.Entry&lt;String, String&gt; prop : result.getAllProperties().entrySet())

{

 

// It is possible for keys to be present that have a null value (for

// example, "priority" will map to null if no priority was specified

// for this job). We want to skip over such name-value pairs,

// printing out only those pairs for which a non-null value exists.

// We filter the pairs by checking whether the length of the value

// string is greater than 0 -- i.e., that a useful value exists:

 

if (prop.getValue().length() &gt; 0)

{

System.out.println(prop.getKey() + " = " + prop.getValue());

}

}

System.out.println("============");

}

}

 

private String getInput(String promptMessage) throws Exception

{

System.out.print(promptMessage + "\t");

return br_.readLine();

}

 

/**

* This program accepts two parameters.

*

* First parameter is the FME Server host. ie. localhost

* Second parameter is the FME Server port. ie. 7071

*/

public static void main(String args[]) throws FMEServerException

{

String host = null;

int port = 0;

 

// Extract the arguments from the command line

if (args.length != 2)

{

argError();

}

else

{

host = args[0];

try

{

port = Integer.parseInt(args[1]);

}

catch (NumberFormatException nfe)

{

argError();

}

}

 

FMEServerAPIDemo demo = new FMEServerAPIDemo(host, port);

 

while (true)

{

demo.execute();

}

}

 

private static void argError()

{

System.err.println("USAGE:\n\tFMEServerAPIDemo &lt;host&gt; &lt;port&gt;");

System.exit(-1);

}

}

Safe Software Inc. www.safe.com