/*============================================================================
Name : FMEServerAPIDemo.cs
System : FME Server API
Language : C#
Purpose : FMEServerAPIDemo sample application
Author Date Changes made
------------------ ------------ -------------------------------
Sample Jun 19, 2008 Original definition
Copyright (c) 1994 - 2011, Safe Software Inc.
All Rights Reserved
This software may not be copied or reproduced, in all or in part,
without the prior written consent of Safe Software Inc.
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.
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.
============================================================================ */
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Safe.FMEServer.API;
namespace FMEServerAPIDemo
{
public class FMEServerAPIDemo
{
private IFMERepositoryManager repositoryMgr_;
private IFMEServerSession serverSession_;
private string userId_ = "";
private string password_ = "";
private string clientId_ = "app_apidemo";
public FMEServerAPIDemo(string host, int port)
{
serverSession_ = FMEServer.CreateServerSession();
GetConnectionInfo();
IFMEServerConnectionInfo connInfo_ = serverSession_.CreateServerConnectionInfo(host, port, userId_, password_);
IDictionary<string, string> directives = new Dictionary<string, string>();
directives.Add("CLIENT_ID", clientId_);
serverSession_.Init(connInfo_, directives);
repositoryMgr_ = serverSession_.GetRepositoryManager();
}
public void GetConnectionInfo()
{
Console.WriteLine("Please enter server connection credentials.");
Console.Write("UserId:");
userId_ = Console.ReadLine();
if (userId_ != "")
{
Console.Write("Password:");
password_ = Console.ReadLine();
}
}
public void Execute()
{
DisplayMainMenu();
try
{
int choice = GetMenuChoice();
ExecuteMenuChoice(choice);
}
catch (FormatException)
{
Console.Error.WriteLine("Invalid input!");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
}
}
private void Cleanup()
{
if (serverSession_ != null)
{
try
{
serverSession_.Disconnect();
serverSession_ = null;
}
catch (FMEServerException e)
{
Console.Error.WriteLine(e.Message);
}
}
}
private int GetMenuChoice()
{
return Int32.Parse(Console.ReadLine());
}
private void ExecuteMenuChoice(int choice)
{
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();
Environment.Exit(0);
break;
default:
Console.Error.WriteLine("Invalid option!");
return;
}
Console.WriteLine("\nThe operation was a success");
}
private void DisplayMainMenu()
{
Console.Write("\n\n"
+ "===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 void ListRepositories()
{
IFMERepository[] repositoryList = repositoryMgr_.GetRepositories(null);
foreach (IFMERepository repository in repositoryList)
{
Console.Write("{0} {1}\n", repository.Name, repository.Description);
}
}
private void AddRepository()
{
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()
{
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()
{
IFMERepository[] repositoryList = repositoryMgr_.GetRepositories(null);
foreach (IFMERepository repository in repositoryList)
{
IFMEWorkspaceSummary[] workspaceSummaries = repository.GetWorkspaceSummaries(null);
foreach (IFMEWorkspaceSummary workspaceSummary in workspaceSummaries)
{
Console.Write("Repository:{0} {1} {2} ON:{3}\n",
repository.Name,
workspaceSummary.Title,
workspaceSummary.Name,
workspaceSummary.IsEnabled);
}
}
}
private void AddWorkspace()
{
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 FileInfo(workspaceFilePath).Name;
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()
{
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 FileInfo(workspaceFilePath).Name;
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()
{
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()
{
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 RunWorkspace()
{
IFMETransformationManager transformationMgr = 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 <FMEServer-InstallDir>\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);
Console.WriteLine("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 = transformationMgr.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.
Console.WriteLine("Response received:\n");
Console.WriteLine(result.FMEServerResponse);
Console.WriteLine();
// 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.TransformationSuccess)
{
// 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.StatusMessage);
}
else
{
// The transformation was successful. We inform the user of this.
Console.WriteLine("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".
Console.WriteLine("The following information was parsed from the response:\n");
Console.WriteLine("============");
foreach (KeyValuePair<string, string> pair in result.GetAllProperties())
{
Console.WriteLine(pair.Key + " = " + pair.Value);
}
Console.WriteLine("============");
}
}
private void ListResources()
{
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);
IFMEResource[] resources = workspace.Resources;
foreach (IFMEResource resource in resources)
{
Console.Write("{0} {1}\n", resource.Name, resource.Description);
}
}
private void AddResource()
{
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 FileInfo(resourceFilePath).Name;
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()
{
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 FileInfo(resourceFilePath).Name;
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()
{
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()
{
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()
{
IFMEService[] services = repositoryMgr_.GetServices(null);
foreach (IFMEService service in services)
{
Console.Write("{0} {1} {2} ON:{3} {4}\n",
service.DisplayName,
service.Name,
service.URLPattern,
service.IsEnabled,
service.Description);
}
}
private void AddService()
{
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()
{
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()
{
string name = GetInput("Please enter the name for the service to remove:");
if (!repositoryMgr_.RemoveService(name))
{
throw new FMEServerException("There is no service with this name!");
}
}
private string GetInput(string promptMessage)
{
Console.Write(promptMessage + "\t");
return Console.ReadLine();
}
private static void ArgError()
{
Console.Error.WriteLine("USAGE:\n\tFMEServerAPIDemo <host> <port>");
Environment.Exit(0);
}
// 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)
{
string host = null;
int port = 0;
// Extract the arguments from the command line
if (args.Length != 2)
{
ArgError();
}
else
{
host = args[0];
try
{
port = Int32.Parse(args[1]);
}
catch (FormatException)
{
ArgError();
}
}
FMEServerAPIDemo demo = new FMEServerAPIDemo(host, port);
while (true)
{
demo.Execute();
}
}
}
}