Dynamic Select sample (Java)

The Dynamic Select console sample demonstrates how to use the Dynamic Select feature of Data Abstract which provides a means to dynamically retrieve selected fields from a DataTable.

Getting Started

The Dynamic Select sample is installed in C:\Users\Public\Documents\RemObjects Samples\Data Abstract for Java\Java\Console\.

To build it you can either build & execute it from the command line or make use of the provided Eclipse .classpath and .project files.:

If using the command line remember that you will need to explicitly include the two jar files provided by the Data Abstract for Java package in the classpath. So for example to build and run this sample you'll need:

  • Build: javac -cp "C:/Program Files/RemObjects Software/Data Abstract for Java/Bin/com.remobjects.dataabstract.jar";"C:/Program Files/RemObjects Software/Data Abstract for Java/Bin/com.remobjects.sdk.jar";src src\com\remobjects\dataabstract\samples\dynamicselect\Program.java
  • Execute: java -cp "C:/Program Files/RemObjects Software/Data Abstract for Java/Bin/com.remobjects.dataabstract.jar";"C:/Program Files/RemObjects Software/Data Abstract for Java/Bin/com.remobjects.sdk.jar";src com.remobjects.dataabstract.samples.dynamicselect.Program

Like all the samples provided with Data Abstract for Java you will need to be running the Relativity Server with the DASamples Domain and the Simple Schema available.

Lastly this sample makes use of a convenience class (DataTableExtension) which is provided with Data Abstract for Java. It provides a single public method LogToString that takes a DataTable and converts its contents into a String in a pretty fashion that could be logged to a console or into a file. Please note that this class extension is intended for test purposes only.

Running the Sample

When run the sample sets up a connection to an instance of Relativity Server and logs in (Step 1). It then creates a TableRequestInfoV5 and specifies that we are interested in the "ClientId", "ClientName" and "ClientPhone" fields from the "Clients" table. The data is then retrieved and printed to the console.

Examining the Code

All of the code can be found in the Program.java source file.

The Clients schema table used here has ten fields, however we are only interested in the following three:

  • ClientId is the primary key and use an AutoInc data type.
  • ClientName is a string of up to 50 characters and is required for each new row
  • ClientPhone is also a string of up to 50 characters, the field is optional.

Setting up a Connection & Logging in (Step 1)

There are three stages to setting up a connection to an instance of Relativity Server.

In the first stage we initialize the underlying services that we will use to establish the connection to the server. The BinMessage is a message type that will be used to encode the data as a message. The HttpClientChannel is the communications channel over which the data will be sent, here we are establishing that it uses "HTTP" and specifying the address of the server. Finally an instance of Bin2DataStreamer is created which will handle the encoding and decoding of the data packets being transmitted.

The second stage is to configure a RemoteDataAdapter object that we interact with to communicate with the server. After its created you pass it the three objects we created previously and set the DataServiceName and LoginServiceName. At this point we have a working connection but we will be unable to manipulate the schema data until we log in. Attempting to do so will cause an ROException exception to be thrown with the message "Session could not be found.".

The final stage passes a special login string (lLoginString) to the login method to establish a login session. The login method returns a boolean which will be true if the login attempt was successful or false if it failed. The login string is comprised of 4 parts:

  • Username the username to attempt to login with
  • Password the password to use
  • Domain the name of the domain that the schema is located in
  • Schema the name of the schema we wish to use

For example, the login string from this sample is "User Id=simple;Password=simple;Domain=DASamples;Schema=Simple"

NOTE If there is a problem attempting to communicate with the server, or if the schema or domain name is incorrect then an ROException will be thrown and should be handled appropriately.

BinMessage lMessage = new BinMessage();
HttpClientChannel lChannel = new HttpClientChannel();
try {
    lChannel.setTargetUrl(new URI("http://localhost:7099/bin"));
} catch (URISyntaxException e1) {
    e1.printStackTrace();
    return;
}
System.out.println(String.format("Target URL is %s", lChannel
        .getTargetUrl().toString()));

System.out.println("RO SDK layer is configured.");

Bin2DataStreamer lDataStreamer = new Bin2DataStreamer();
RemoteDataAdapter lDataAdapter = new RemoteDataAdapter();
lDataAdapter.setDataStreamer(lDataStreamer);
lDataAdapter.setMessage(lMessage);
lDataAdapter.setClientChannel(lChannel);
lDataAdapter.setDataServiceName("DataService");
lDataAdapter.setLoginServiceName("LoginService");

System.out.println("RO DataAbstract layer is configured.");

System.out.println("");
System.out.println("");
System.out.println("STEP 1: Login to DataService");
String RelativityConnectionStringTemplate = "User Id=\"%s\";Password=\"%s\";Domain=\"%s\";Schema=\"%s\"";
String lLoginString = String.format(RelativityConnectionStringTemplate,
        "simple", "simple", "DASamples", "Simple");
System.out.print(String.format("Login string is %s", lLoginString));
Boolean lLogged = lDataAdapter.login(lLoginString);

if (lLogged) {
    System.out.println("Login has been successful. Going further...");
} else {
    System.out
            .println("Cannot login. Please check your user name  and password. Exiting...");
    return;
}

Issuing a DynamicSelect request (Step 2)

To use Dynamic Select we first need to create a TableRequestInfoV5 object that means we can specify custom parameters for the data request. We pass "-1" to setMaxRecords to request all of the table's records, if a positive value is passed then the number of records is limited to that. To request the schema to be returned in the results we pass "true" to setIncludeSchema.

To specify which fields we are interested in we need to create a StringArray object and add a String object per field we are interested in. Here we pass an empty StringArray to the setDynamicSelectFieldNames method and then loop through a normal array of Strings of adding each String to the StringArray which is retrieved using getDynamicSelectFieldNames.

Finally we tell the RemoteDataAdapter to use Dynamic Select by passing "true" to setDynamicSelect.

The next step is create a DataTable which will hold the results from the server. The name passed to the constructor should be the name of the table you wish to retrieve data from; here it is "Clients"

Finally to retrieve the data we pass the TableRequestInfoV5 and DataTable to the fill method of RemoteDataAdapter which executes in a synchronous fashion delaying further processing until the request completes. Once the data has been retrieved it is printed to the console.

An alternative option is shown in Working Asynchronously with the Remote Data Adapter.

System.out.println("STEP 2: Retrieving data using Dynamic Select");

TableRequestInfoV5 lRequestInfo = new TableRequestInfoV5();
lRequestInfo.setMaxRecords(-1); // no limits - return all records
lRequestInfo.setIncludeSchema(true); // update schema in the result data
                                    // table to match recieved data
                                    // (not necessarily).

// Array of field names to select - this is DynamicSelect feature
// itself.
String[] lDynamicSelect = new String[] { "ClientId", "ClientName",
       "ClientPhone" };
System.out.println(String.format("DynamicSelect is: %s",
       StringExtensions.Join(", ", lDynamicSelect)));

lRequestInfo.setDynamicSelectFieldNames(new StringArray());
for (int i = 0; i < lDynamicSelect.length; i++) {
   lRequestInfo.getDynamicSelectFieldNames()
           .addItem(lDynamicSelect[i]);
}
// And finally enable Dynamic Select feature at DataAdapter level
lDataAdapter.setDynamicSelect(true);
System.out.println("DynamicSelect feature has been enabled.");

DataTable lTable = new DataTable("Clients");
lDataAdapter.fill(lTable, lRequestInfo);

System.out.println(String.format(
       "Data has been retrieved. Table: %s; columns count: %d",
       lTable.getTableName(), lTable.getColumns().getCount()));
System.out.println(DataTableExtension.LogToString(lTable));
System.out.println("DONE! Please press return to exit.");

Note a shorter way of setting the fields required for the Dynamic Select request is to use the constructor of StringArray to pass in an array of Strings.

lRequestInfo.setDynamicSelectFieldNames(new StringArray(new String[] {
        "ClientId", "ClientName", "ClientPhone" }));

Example Output

This is an example of the output you will see when the sample is run. In Step 2 you can see there are only three fields/columns in the "Clients" table rather than the 10 available in the schema table.

Dynamic Select sample has been started.
Target URL is http://localhost:7099/bin
RO SDK layer is configured.
RO DataAbstract layer is configured.


STEP 1: Login to DataService
Login string is User Id="simple";Password="simple";Domain="DASamples";Schema="Simple"Login has been successful. Going further...


STEP 2: Retrieving data using Dynamic Select
DynamicSelect is: , ClientId, ClientName, ClientPhone
DynamicSelect feature has been enabled.
Data has been retrieved. Table: Clients; columns count: 3

Table: Clients (7 rows from 7)
|------------------------------------------------------|
|ClientId      |ClientName         |ClientPhone        |
|------------------------------------------------------|
|18            |Brian L. Rowles    |(908) 385-7809     |
|19            |Angela W. Vanover  |(610) 463-9999     |
|20            |Anna H. Kugler     |(817) 249-9525     |
|21            |Randy R. Howard    |(234) 567-8909     |
|22            |Kenny S. Lay       |(817) 249-9525     |
|23            |Maryann C. Bach... |(907) 722-6777     |
|24            |Lillie R. Schro... |(312) 476-1404     |
|------------------------------------------------------|


DONE! Please press return to exit.