Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Here follows some example code of how client applications can set up a connection the PI Service of a running FEWS OC.

Setting up a connection in JAVA

Before starting the client will require the following library: xfire-all-1.2.5.jar. This library can be found in the bin directory of the FEWS system.

...

Code Block
ObjectServiceFactory serviceFactory = new ObjectServiceFactory();
Service service = serviceFactory.create(FewsPiService.class);
XFireProxyFactory proxyFactory = new XFireProxyFactory();
 //port Number must be equal to the number configured in the Explorer.xml
int portNumber = 8100;
//localhost can be replaced by the ip address of the machine on which the FEWS system is running.
FewsPiService serviceProxy = (FewsPiService) proxyFactory.create(service, "http://localhost:" + portNumber + "/FewsPiService")

Setting up

...

a connection in C

Before starting the client will require the following librarys: libtcl.so and the libraries belonging to the TclSOAP package.
While there is a C++ libraries to handle SOAP, we could not find a pure C library. At first sight the C++ libraries seem to make it necessary to define classes and so on before you can start using them. With the Tcl approach the code remains quite simple. (We have not investigated exactly what TclSOAP requires, but it can be downloaded from ActiveState)
<p>
For the example fewspi.tcl file used refer to the attachment fewspi-C.tgz

Code Block

#include <stdio.h>
#include <tcl.h>

/* Define some helper variables and functions */

Tcl_Interp *interp;

int main( int argc, char *argv[] ) {

    /* Get the library started */

    if ( Init( argv[0] ) != TCL_OK ) {
        fprintf( stderr, "Sorry, initialisation failed: %s\n",
            Tcl_GetStringResult( interp ) );
    }

    /* Here insert calls to Pi Service */
    fprintf( stdout, "Locations: %s\n", getLocations( "id not required" ) ); 
    fprintf( stdout, "New task: %s\n", createTask( "id not required" ) );
}

void TearDown () {Tcl_Finalize();}

int EvalFile (char *fileName) {
    return Tcl_EvalFile(interp, fileName);
}

int Init (char *argv0) {
    char *pchar;
    char  buffer[1000];

    /* Initialise the library itself */

    Tcl_FindExecutable(argv0);
    interp = Tcl_CreateInterp();
    if (Tcl_Init(interp) != TCL_OK) {
        return TCL_ERROR;
    }

    /* Initialise the FEWS PI services */

    strcpy( buffer, argv0 );
    pchar = strrchr( buffer, '/' );
    if ( pchar == NULL ) {
        pchar = strrchr( buffer, '\\' );
    }
    if ( pchar == NULL ) {
        pchar = buffer;
    }
    strcpy( buffer, "fewspi.tcl" );

    return EvalFile( buffer );
}

Setting up method calls JAVA

Here follow some code examples of how to query the PI Service proxy from the client application. The configuration used to make these examples can be found in the attached Example Configuration.

Code Block

   /**
     * Test the retrieval of system time.
     * <p/>
     * With this test the system time of a running Fews Region (on port 8191) can be retrieved. If the
     * system time of the region is changed then the returned value here will match the change.
     */
    public void testSystemTime() {
        String clientId = "not required";
        Date date = serviceProxy.getSystemTime(clientId);


        System.out.println("Current System time : " + dateFormat.format(date));
    }

    /**
     * Return the warm state times from the data base for the configured moduleState id=RSNWELEV_DETO3I
     * in the service configuration file = TestConfig.
     */
    public void testGetWarmStateTimes() {
        //name of service config file
        String clientId = "TestConfig";
        //id of moduleState element
        String moduleId = "RSNWELEV_DETO3I";

        Date[] stateTimes = serviceProxy.getAvailableStateTimes(clientId, moduleId);

        System.out.println("State times for Module " + moduleId);
        for (Date stateTime : stateTimes) {
            System.out.println("time: " + dateFormat.format(stateTime));
        }
    }

    /**
     * Return the cold state ids from the data base for the configured moduleState id=RSNWELEV_DETO3I
     * in the service configuration file = TestConfig

Here follow some code examples of how to query the PI Service proxy from the client application. The configuration used to make these examples can be found in the attached Example Configuration.

Code Block

   /**
     * Test the retrieval of system time.
     * <p/>
     * With this test the system time of a running Fews Region (on port 8191) can be retrieved. If the
     * system time of the region is changed then the returned value here will match the change.
     */
    public void testSystemTimetestGetColdStateIds() {
        String//name clientIdof =service "not required";config file
        DateString dateclientId = serviceProxy.getSystemTime(clientId);


        System.out.println("Current System time : " + dateFormat.format(date))"TestConfig";
    }

    //**
id of moduleState element
  * Return the warm state times from the data base for the configured moduleState id= String moduleId = "RSNWELEV_DETO3I";

     * in the service configuration fileString[] stateIds = TestConfig.
serviceProxy.getColdStateIds(clientId, moduleId);

         */
    public void testGetWarmStateTimes() {
System.out.println("Cold state ids for model " + moduleId);
        for //name of service config file
(String id : stateIds) {
         String clientId = "TestConfig"System.out.println("cold state: " + id);
        //id of moduleState element}
    }

    String moduleId = "RSNWELEV_DETO3I";

 /**
     * Return Date[]the stateTimeswarm = serviceProxy.getAvailableStateTimes(clientId, moduleId);

        System.out.println("State times for Module " + moduleId);
        for (Date stateTime : stateTimes) {state file from the data base for the configured moduleState id=SNOW17_LSMO3U
     * in the service configuration file = TestConfig. Write file to location d:/temp/<moduleStateId>.zip
     */
    public   System.out.println("time: " + dateFormat.format(stateTime));void testGetModuleStateBinary() throws IOException {
        }
//name of service config }
file
    /**
     *String ReturnclientId the cold state ids from the data base for the configured moduleState id=RSNWELEV_DETO3I
 = "TestConfig";
        //id of moduleState element
    * in the service configurationString filemoduleId = TestConfig."SNOW17_LSMO3U";

     */
   Date[] publicstateTimes void= testGetColdStateIds() {
serviceProxy.getAvailableStateTimes(clientId, moduleId);
        byte[] binary  //name of service config file= serviceProxy.getModuleStateBinary(clientId, moduleId, stateTimes[0], null, -1);

        StringZipInputStream clientIdzipInputStream = "TestConfig";
 new ZipInputStream(new ByteArrayInputStream(binary));
        try {
    //id of moduleState element
     ZipUtils.unzipFiles(zipInputStream, new  StringFile("d:/temp/" + moduleId =+ "RSNWELEV_DETO3I";
.zip"));
        String[]} stateIds = serviceProxy.getColdStateIds(clientId, moduleId);
finally {
        System.out.println("Cold state ids for model " + moduleId zipInputStream.close();
        for (String id : stateIds) {}
    }

    /**
     * Returns  System.out.println("cold state: " + id);
        }
    }

the content of a client configuration file from the config directory PiClientConfigFiles.
     /**
     * ReturnOnly therequirement warmis statethat filea fromconfiguration thefile data(any basetype) forwith the configuredclientId moduleState id=SNOW17_LSMO3U
     * in the service configuration file = TestConfig. Write file to location d:/temp/<moduleStateId>.zipas name and moduleId as extension
     * must exist in this config directory.
     */
    public void testGetModuleStateBinarytestGetClientConfigurationFile() throws IOException {
        //nameName of serviceclient config file
        String clientId = "TestConfigMyClientConfigFile";
        //idextension of moduleState element
        String moduleId = "SNOW17_LSMO3U";
client file
        Date[]String stateTimesmoduleId = serviceProxy.getAvailableStateTimes(clientId, moduleId);"txt";

        byte[]String binaryclientText = serviceProxy.getModuleStateBinarygetClientConfigFile(clientId, moduleId, stateTimes[0], null, -1);

        ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(binary));System.out.println("Client file content: " + clientText);

    }

    try {/**
     * Retrieve the content of the locations ZipUtils.unzipFiles(zipInputStream, new File("xml. Write this to d:/temp/" + moduleId + ".zip"));locations.xml
     * @throws IOException
     */
    public void testGetLocations() }throws finallyIOException {

        String locations =  zipInputStreamserviceProxy.close(getLocations("id not required");

        }
    }

    /**System.out.println("Content of locations xml file: " + locations);
     * Returns the content of a client configuration file from the config directory PiClientConfigFiles. FileUtils.writeText("d:/temp/locations.xml", IOUtils.UTF8_CHARSET, locations);

    }

    /**
     *
 Return the member indices for the *ensemble Onlyid requirement= is"ESP" thatfrom athe configurationtimeseries filetable.
 (any type) with the clientId*
 as name and moduleId as* extension
This only works when there *are mustensemble existmembers in thisthe configTimeSeries directorytable.
     */
    public void testGetClientConfigurationFiletestGetEnsembleMemberIndices(){

        //NameString ofensembleId client file= "ESP";
        Stringint[] clientIdindices = "MyClientConfigFile";
        //extension of client file
   serviceProxy.getEnsembleMemberIndices("id not required", ensembleId);

        System.out.println("Ensemble id " + ensembleId + " contains " + indices.length + " members.");
     String moduleId = "txt";
System.out.println("indices are: ");
        Stringfor clientText(int = serviceProxy.getClientConfigFile(clientId, moduleId);

indice : indices) {
            System.out.println("Client file content: " + clientText);indice);
        }

    }

    /**
     * RetrieveGet the contentlogentries offor thean locationsImport xmlTaskId. Write this to d:/temp/locations.xml
     *
     * Check the LogEntries table to find a matching taskId.
     * 
     * @throws IOException
     */
    public void testGetLocationstestGetLogInformation() throws IOException {
 IOException {

        String taskId = "NWSNWMC00:0000026"; //=import
        String locationslogInfo = serviceProxy.getLocationsgetLogMessages("id not required", taskId);

        System.out.println("Content of locations xml filelog: " + locationslogInfo);
        FileUtils.writeText("d:/temp/locationslog.xml", IOUtils.UTF8_CHARSET, locationslogInfo);

    }

    /**
     * Return the member indices for the ensemble id = "ESP" from the timeseries table.
     *
     * This only works when there are ensemble members defined in the TimeSeriesservice table.
configuration file under timeSeries element */
with    public void testGetEnsembleMemberIndices(){

        String ensembleId = "ESP";id 'Reservoir'.
     *
   int[] indices = serviceProxy.getEnsembleMemberIndices("id not required", ensembleId);

        System.out.println("Ensemble id " + ensembleId + " contains " + indices.length + " members.");
        System.out.println("indices are: ");* Filter using parameter ids QIN and RQIN and location ids DETO3, GPRO3 and FOSO3
     *
     * Check timeseries table to look for existing times for these timeseries.
     *
   for (int indice* : indices) {@throws IOException
     */
    public   System.out.println(indice);
   void testGetTimeSeries() throws IOException {

     }

   Date }

systemTime = serviceProxy.getSystemTime("id  /**
 not required");
    * Get the logentries forCalendar aninstance Import TaskId.= GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));
     *
   instance.set(2009,  * Check the LogEntries table to find a matching taskId.4, 1);
        Date start = instance.getTime();
     * 
  instance.set(2009,   * @throws IOException4, 11);
     */
   Date publicend void= testGetLogInformation() throws IOException {
instance.getTime();
        String[] taskIdparams = new String[]{"QIN", "NWSNWMC00:0000026RQIN"}; //=import
        String[] logInfolocs = serviceProxy.getLogMessages("id not required", taskId);

 new String[]{"DETO3","GPRO3","FOSO3"};
        String System.out.println("Content of log: " + logInfo);
        FileUtils.writeText("d:/temp/log.xml", IOUtils.UTF8_CHARSET, logInfoheaders = serviceProxy.getTimeSeriesHeaders("TestConfig", "Reservoir", null, start, systemTime, end, params, locs, null, -1);

    }

    /**
     * Return the timeseries defined in the service configuration file under timeSeries element with id 'Reservoir'.
     *
     * Filter using parameter ids QIN and RQIN and location ids DETO3, GPRO3 and FOSO3
     System.out.println("Content of tineseries headers: " + headers);

        String timeseriesfile = serviceProxy.getTimeSeries("TestConfig", "Reservoir", null, start, systemTime, end, params, locs, null, -1);

        FileUtils.writeText("d:/temp/timeseries.xml", IOUtils.UTF8_CHARSET, timeseriesfile);

    }

    /**
     * CheckUpload timeseriesa tablepi_diag tolog lookfile forto existing times for these timeseriesthe region.
     *
     * @throwsMake IOException
sure to create an input */
file in   public void testGetTimeSeries() throws IOException {
corresponding directory.
        Date systemTime = serviceProxy.getSystemTime("id not required");*
     *   Calendar instance = GregorianCalendar.getInstance(TimeZone.getTimeZone("GMT"));@throws IOException
        instance.set(2009, 4, 1);
*/
    public void testInsertLogMessages() throws IOException Date{

 start = instance.getTime();
     String logText = instanceFileUtils.set(2009, 4, 11readText("d:/temp/inputlog.xml");
        Date end = instance.getTime(serviceProxy.putLogMessage("used as description", logText);
    }

    String[] params = new String[]{"QIN", "RQIN"};
        String[] locs = new String[]{"DETO3","GPRO3","FOSO3"};
        String headers = serviceProxy.getTimeSeriesHeaders("TestConfig", "Reservoir", null, start, systemTime, end, params, locs, null, -1);

        System.out.println("Content of tineseries headers: " + headers);

        String timeseriesfile = serviceProxy.getTimeSeries("TestConfig", "Reservoir", null, start, systemTime, end, params, locs, null, -1);

        FileUtils.writeText/**
     * Upload a pi_timeseries file to the Region. The timeseries in this file must be linked to timeseries configured
     * in the PiServiceConfig file.
     *
     * Make sure to create an input file in the corresponding directory.
     *
     * @throws IOException
     */
    public void testInsertTimeSeries() throws IOException {

        String timeseriesText = FileUtils.readText("d:/temp/timeseriesinputtimeseries.xml", IOUtils.UTF8_CHARSET, timeseriesfile);

        }

    /**System.out.println("Input timeseries: " + timeseriesText);
     * Upload a pi_diag log file to the region. serviceProxy.putTimeSeries("TestConfig", null, "Reservoir", timeseriesText, null, -1);
     *}

     /**
 Make sure to create an* inputSchedule filea intask correspondingrun directory.
and wait for it to *finish.
     * @throws IOException
     */
    public void testInsertLogMessagestestRunningTask() throws IOException {

        String logTexttaskId = FileUtilsserviceProxy.readTextcreateTask("d:/temp/inputlog.xmlid not required");
        Date date = serviceProxy.putLogMessagegetSystemTime("used as description", logText);
    }

    /**
     * Upload a pi_timeseries file to the Region. The timeseries in this file must be linked to timeseries configured
     * in the PiServiceConfig file.
System.out.println("Starting task with id " + taskId + " time=" + new Date(System.currentTimeMillis()));
      *
  String taskRunId  * Make sure to create an input file in the corresponding directory.
     *
= serviceProxy.runTask("id not required", taskId, "Santiam_Forecast", date, date, date, null, null, "Test user", "PiWebservice taskrun");

        *boolean @throwsresult IOException
     */= serviceProxy.waitForTask("id not required", taskRunId, 120000);
    public void testInsertTimeSeries() throws IOException {

        String timeseriesText = FileUtils.readText("d:/temp/inputtimeseries.xml" System.out.println("Task with id " + taskId + (result ? " finished successfully" : " failed"));
        System.out.println("Input timeseries: " + timeseriesText);"time=" + new Date(System.currentTimeMillis()));
    }

Setting up method calls C

Here follow some code examples of how to query the PI Service proxy from the client application. The configuration used to make these examples can be found in the attached Example Configuration.

Code Block

/* Fews PI services: wrapper functions */

char *getLocations( char *clientId ) {
    char buffer[1000];

   serviceProxy.putTimeSeries("TestConfig", null strcpy( buffer, "Reservoir", timeseriesText, null, -1getLocations " );
    strcat( buffer, clientId });

    if  /**
     * Schedule a task run and wait for it to finish.( Tcl_Eval( interp, buffer ) != TCL_OK )
{
        return NULL;
    } *else {
     */
   return public void testRunningTask(){Tcl_GetStringResult( interp ) ;
    }
}

char *createTask( char *clientId ) String{
 taskId = serviceProxy.createTask("id not required"); Tcl_Obj *obj[2];

        Date dateobj[0] = serviceProxy.getSystemTime(""Tcl_NewStringObj( "createTask", -1 );
    obj[1]    System.out.println("Starting task with id " + taskId + " time=" + new Date(System.currentTimeMillis()));
        String taskRunId = serviceProxy.runTask("id not required", taskId, "Santiam_Forecast", date, date, date, null, null, "Test user", "PiWebservice taskrun");
= Tcl_NewStringObj( clientId, -1 );

    Tcl_IncrRefCount( obj[0] ) ;
    Tcl_IncrRefCount( obj[1] ) ;

    if ( Tcl_EvalObjv( interp, 2, obj, 0 ) != TCL_OK ) {
        booleanreturn resultNULL;
 = serviceProxy.waitForTask("id not required", taskRunId, 120000);} else {

        System.out.println("Task with id " + taskId + (result ? " finished successfully" : " failed"));
Tcl_DecrRefCount( obj[0] ) ;
        Tcl_DecrRefCount( obj[1] ) ;
         System.out.println("time=" + new Date(System.currentTimeMillis()))return Tcl_GetStringResult( interp ) ;
    }
}

Appendix

FewsPiService WSDL

...