cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Community Tip - New to the community? Learn how to post a question and get help from PTC and industry experts! X

Java SDK Tutorial Part 2

No ratings

 

 

Step 3: Test Connectivity 

 

Before you can begin developing with the ThingWorx Java SDK, you will need to generate an Application Key and add it to the source code provided.

 

Generate Application Key

  1. On the Home screen of Composer click + New the top left.
     


    select_new.png

     

  2. In the dropdown list, click Application Key.

    create_new_appkey.png

     

  3. Give your Application Key a name (i.e., MyAppKey) and set the Project (ie, PTCDefaultProject).

  4. Assign the application key to a User.

    save_app_key.png

     

  5. Click Save.

After saving, a Key ID is generated and appears above the Expiration Date. This is the secret key that you will use to make secure connections. If you have not updated the Expiration Date field, the default will be one day.

This is an example of the Application Key ID that you will use for a successfull connection.

app_key_id.png

 

NOTE: Using the Application Key for the default Administrator is not recommended. If administrative access is absolutely necessary, create a User and place the user as a member of Admins.

 

Modify Source File

 

  1. At the top level, locate the SimpleClient Java source file in a package under the src folder.

  2. Open the SimpleClient.java source file and update the URI with the IP address of your ThingWorx instance. For example:

    config.setUri("ws://127.0.0.1:80/Thingworx/WS");

     

  3. In the SimpleClient.java source file, update the Application Key with the Application Key you stored from the last section. For example:

    config.setSecurityClaims(new SamplePasswordCallback(cmd.getOptionValue("b3d06be7-c9e1-4a9c-b967-28cd4c49fa80"))); //SET YOUR APPLICATION KEY HERE

     


     

Compile and Run Code

 

  1. Right-click the SimpleClient.java file.

  2. Scroll to Run As then select Java Application.

    Step-Java-Console.png

     

    The output in the Eclipse console will confirm connection and authentication to the ThingWorx platform.
     

 

Step 4: Run Sample Applications

 

The Java code provided in the download is pre-configured to run and connect to the Entities in the ThingWorxEntitiesExport.xml file. Keep track of the IP address of the ThingWorx Composer you are using. Many of the utilized libraries are based on the use of Java 1.8. Use other versions at your own risk.

 

  1. Within your Eclipse ThingWorx Development project, navigate to the com.thingworx.sdk.examples package and open ExampleClient.java.


    Step-Connect1.png

     

  2. The URI structure is as follows: ws://host_name:port_number/Thingworx/WS. Update the host_name and port_number to the host and port of your ThingWorx server. Navigate to the following line and update the IP and port if necessary:

    config.setUri("ws:// 127.0.0.1:80/Thingworx/WS");

    TIP: To enable secure https connection, change “ws” to “wss” and port number to 443. (default port for https is 443).

  3. Navigate to the following line in ExampleClient.java and update the value of appKey to the keyId in the “admin_key” Application Key in the ThingWorx Composer. If this connect fails, attempt to use the "admin_key" Application Key in the ThingWorx Composer. Using the default admin's key is not recommended. For future development, create users and add them to be a member of the group of Administrators:

    config.setSecurityClaims(new SamplePasswordCallback(cmd.getOptionValue("b3d06be7-c9e1-4a9c-b967-28cd4c49fa80"))); //SET YOUR APPLICATION KEY HERE 

  4. Right-click ExampleClient.java, scroll to Run As, and select Java Application.

    Step-Connect2.png
  5. You should be able to see a new Thing in your Composer called SimpleThing_2.

 

To check the connected Entities, go to the Monitoring screen.

 

  1. Click Monitoring.

  2. Click Remote Things from the list to see the connection status.

    RemoteMonitoring.png

     



  3. You will now be able to see and select the Entity within the list.

    NOTE: SimpleThing_1 and SimpleThing_2 will also have an update to the lastConnection property. While SimpleThing_1 is unbound, SimpleThing_2 is bound for the duration of the application run time.

 

 

Step 5: Example Client Connection

 

The Java code provided in the ExampleClient.java file initiates a number of actions from establishing a connection to defining Services and Properties.

 

Configuration

 

In the first step of connecting to the platform (Establish Physical Websocket), we create a ClientConfigurator instance to hold the location (URI) needed to point to the websocket of the ThingWorx Composer. It is also used to:

 

  • Configure the ThingWorx URI of the server

  • Set the Application Key used for authentication

  • Set the connection reconnection interval

  • Ignore ssl errors
ClientConfigurator config = new ClientConfigurator();
config.setUri("ws://127.0.0.1:80/Thingworx/WS");

 

Authentication

 

In the second step of connecting to the platform (Authenticate), we provide this ClientConfigurator instance an Application Key that belongs to the default_user that was imported to the ThingWorx Composer. The Application Key must match the keyId value for the User you would want to have the specific control and permissions.

 

**WARNING: It is not best practice to utilize the Administrator’s Application Keys in Edge development. For the reason that Application Keys in java source code are vulnerable to de-compilation and storing them in a configuration file is dangerous, the best practice is to create new Users, and give them any permission deemed necessary.

 

config.setSecurityClaims(new SamplePasswordCallback(cmd.getOptionValue("b3d06be7-c9e1-4a9c-b967-28cd4c49fa80"))); //SET YOUR APPLICATION KEY HERE

 

NOTE: If you are not using SSL/TLS, use this code to test against a server using a self-signed certificate: config.ignoreSSLErrors(true);

 

Create Client Communication

 

To create a client with the above configuration, create an instance of ExampleClient and pass the configurator created in the step above. ExampleClient is a class that extends ConnectedThingClient. The ConnectedThingClient facilitates communication to the ThingWorx server as well as manages any contained VirtualThing. ExampleClient.java is an example of this and creates the instance on the line:

ExampleClient client = new ExampleClient(config);


Create and Bind Thing

Before starting the client, it is best to bind all VirtualThings that will be bound in order to decrease the necessary request messages. Binding Things before starting the client creates one bind request message to go to the ThingWorx server with all of the Things included. Starting the client then binding Things creates a bind request for each Thing that is being bound.

// Create a new VirtualThing. The name parameter should correspond with the 
// name of a RemoteThing on the Platform. In this example, the SimpleThing_1 is used.
VirtualThing thing = new VirtualThing(ThingName, "A basic virtual thing", client);

// Bind the VirtualThing to the client. This will tell the Platform that
// the RemoteThing 'SimpleThing_1' is now connected and that it is ready to 
// receive requests.
client.bindThing(thing); 

 

Start Connection

 

You can now start the client, which will establish the AlwaysOn protocol with the ThingWorx Composer. This protocol provides bi-directional communication between the ThingWorx Composer and the running client application.

 

// Start the client. The client will connect to the server and authenticate
// using the ApplicationKey specified above.
client.start();

 

 

 

Click here to view Part 3 of this guide.

 

 

Version history
Last update:
‎Oct 17, 2022 04:02 PM
Updated by:
Labels (1)
Contributors