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

Community Tip - Did you know you can set a signature that will be added to all your posts? Set it here! X

Create An Extension Part 3

100% helpful (2/2)

 

Step 7: Add JAR Resources

 

You can add external JARs for use by your extension. Every third-party JAR that is not already included in either the ThingWorx Extension SDK or ThingWorx Core needs to be added to your extension project as a JAR Resource. These JAR resources are added to your metadata.xml as a tag and are used to reference the Java classes in the third-party JAR on which the extension depends. You can either use the Add button

 

thingworx-plus-symbol.jpg


or the ThingWorx Menu from the menu bar to add a new JAR resource. By doing so, the JAR is automatically updated in the metadata file and added to the build path.

Although ThingWorx allows developers to include jar files for third-party libraries in their code, it is recommended that you avoid adding jar files for common libraries and instead use the jar files that are included with the SDK. Adding jar files to an extension could cause conflicts with jar files already used by the ThingWorx server, either when uploading an extension, or when an extension executes. Even if your extension works today, future updates to ThingWorx may require updates to your extensions. Similarly, packaging a verison of a commonly used library may mean that a customer will not be able to use your extension together with someone else’s extension.

 

  1. Select the project to which you want to add the jar file to and select New Jar Resource.
     


    add-jar-resource.jpg

     

     

  2. Open the directory in which you have stored the training files for this tutorial. Browse to the Jars directory.
  3. Select the json-simple-1.1.1.jar file. Add a description and click Finish.

    add-new-jar-resource.png



    NOTE
    : This will automatically add json-simple-1.1.1.jar to the lib folder and to your project’s build path.

  4. Add httpclient-4.5.6.jar, httpcore-4.4.10.jar and commons-logging-1.2.jar directly into the twx-lib folder in the Project folder.

    NOTE: These JARs are included in the group of JARs used by ThingWorx by default.

  5. In order to build your extension locally, without bundling the jars into your extension that are available on the ThingWorx server, add the above JARs to your project's build path by right-clicking on your project in the Package Explorer, right-click Your_Extension_Project (ie, MyThingWorxWeatherExtension) and select Build Path -> Configure Build Path. Verify the jars we added are in the build path. Otherwise, click Add JARs, then browse to the directory containing these JARs (lib) and add them.

    NOTE: twx-lib folder is a hidden folder and does not appear in the Eclipse package explorer. The twx-lib folder can be found in the WeatherExtension project inside the Eclipse workspace directory.

 

Step 8: Create Services

 

Now that you have created properties, configuration tables and added the required jars, you can begin to add services to your WeatherThingTemplate.

 

In this part of the lesson, we’ll add a service, UpdateWeatherInfo that will take a City parameter and update the properties of this template using the values obtained from the openWeatherMap API.

 

  1. Right click inside the WeatherThingTemplate and select ThingWorx Source->Add Service.

  2. Create a new service with name UpdateWeatherInfo.

  3. Click Add in the Input Parameters frame to add City parameter with a base type STRING.

    add-service.jpg


    add-service-2.png

     

  4. Set the name and base type of the Output Parameter based on the value that you want the service to return. For simplification, assume this service returns nothing. Set the Base Type to NOTHING.

  5. Click Finish to create the service.

  6. Copy and Paste the code for UpdateWeatherInfo as specified below.

    @ThingworxServiceDefinition(name = "UpdateWeatherInfo", description = "updates weather description and temperature properties", category = "", isAllowOverride = false, aspects = {
            "isAsync:false" })
    @ThingworxServiceResult(name = "Result", description = "", baseType = "NOTHING")
    public void UpdateWeatherInfo(
            @ThingworxServiceParameter(name = "City", description = "city name", baseType = "STRING") String City) throws Exception {
            _logger.trace("Entering Service: UpdateWeatherInfo");
            String cityProp = this.getPropertyValue("CurrentCity").getStringValue();
            if (City == null){
                City = cityProp;
            } else {
                this.setPropertyValue("CurrentCity", new StringPrimitive(City));
            }
            
            String url = "http://api.openweathermap.org/data/2.5/weather?q=" +URLEncoder.encode(City,"UTF-8") + "&appid="+ _appid+"&units=imperial";
            
            // create a http client
            HttpClient client = new DefaultHttpClient();
            
            // create a get request with the URL
            HttpGet getRequest = new HttpGet(url);
            
            // add Accept header to accept json format response
            getRequest.addHeader("Accept", "application/json");
            
            // send the get request and obtain a response
            HttpResponse response = client.execute(getRequest);
            
            // if response is successful the status code will be 200.
            if (response.getStatusLine().getStatusCode() == 200) {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                JSONParser parser = new JSONParser();
                JSONObject json = (JSONObject) parser.parse(sb.toString());
                JSONArray weather = (JSONArray) json.get("weather");
                Iterator<JSONObject> it = weather.iterator();
                String description = (String) it.next().get("description");
                this.setPropertyValue("WeatherDescription", new StringPrimitive(description));
                double temp = (Double) ((JSONObject) json.get("main")).get("temp");
                this.setPropertyValue("Temperature", new NumberPrimitive(temp));
    
                /* fire event BadWeather */
                _logger.trace("Exiting Service: UpdateWeatherInfo");
            }
    }

 

Troubleshooting

IssueSolution
The iterator() is undefined in JSONArrayImport only org.json.simple.*. Importing other JSON libraries can give this error.
HttpClient/HttpGet could not be resolved to a type.Make sure you have imported the jars: httpclient-4.5.2.jar, httpcore-4.4.5.jar and commons-logging-1.2.jar, json-simple-1.1.1.jar as indicated in the previous chapter. Make sure you have imported the following packages in your template by Eclipse

 

Your code should be similar to the following:

 

package com.thingworx.weather;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.Iterator;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import com.thingworx.logging.LogUtilities;
import com.thingworx.metadata.annotations.ThingworxBaseTemplateDefinition;
import com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinition;
import com.thingworx.metadata.annotations.ThingworxConfigurationTableDefinitions;
import com.thingworx.metadata.annotations.ThingworxDataShapeDefinition;
import com.thingworx.metadata.annotations.ThingworxFieldDefinition;
import com.thingworx.metadata.annotations.ThingworxPropertyDefinition;
import com.thingworx.metadata.annotations.ThingworxPropertyDefinitions;
import com.thingworx.metadata.annotations.ThingworxServiceDefinition;
import com.thingworx.metadata.annotations.ThingworxServiceParameter;
import com.thingworx.metadata.annotations.ThingworxServiceResult;
import com.thingworx.things.Thing;
import com.thingworx.types.primitives.NumberPrimitive;
import com.thingworx.types.primitives.StringPrimitive;
@ThingworxBaseTemplateDefinition(name = "GenericThing")
@ThingworxPropertyDefinitions(properties = {
@ThingworxPropertyDefinition(name = "CurrentCity", description = "", category = "", baseType = "STRING", isLocalOnly = false, aspects = {
"defaultValue:Boston", "isPersistent:true", "isLogged:true", "dataChangeType:VALUE" }), @ThingworxPropertyDefinition(name = "Temperature", description = "", category = "", baseType = "NUMBER", isLocalOnly = false, aspects = {
"defaultValue:0", "isPersistent:true", "isLogged:true", "dataChangeType:VALUE" }), @ThingworxPropertyDefinition(name = "WeatherDescription", description = "", category = "", baseType = "STRING", isLocalOnly = false, aspects = {
"dataChangeType:VALUE" }) })
@ThingworxConfigurationTableDefinitions(tables = {
@ThingworxConfigurationTableDefinition(name = "OpenWeatherMapConfigurationTable", description = "", isMultiRow = false, ordinal = 0, dataShape = @ThingworxDataShapeDefinition(fields = {
@ThingworxFieldDefinition(name = "appid", description = "", baseType = "STRING", ordinal = 0, aspects = {
"isRequired:true" }) })) })
public class WeatherThingTemplate extends Thing {
private static final long serialVersionUID = -5294151832877452442L;
public WeatherThingTemplate() {}
private static Logger _logger = LogUtilities.getInstance().getApplicationLogger(WeatherThingTemplate.class);
private String _appid;
@Override
public void initializeThing() throws Exception {
    super.initializeThing();
    _appid = (String) this.getConfigurationSetting("OpenWeatherMapConfigurationTable", "appid");
}
@ThingworxServiceDefinition(name = "UpdateWeatherInfo", description = "updates weather description and temperature properties", category = "", isAllowOverride = false, aspects = {
    "isAsync:false" })
@ThingworxServiceResult(name = "Result", description = "", baseType = "NOTHING")
public void UpdateWeatherInfo(
    @ThingworxServiceParameter(name = "City", description = "city name", baseType = "STRING") String City) throws Exception {
    _logger.trace("Entering Service: UpdateWeatherInfo");
    String cityProp = this.getPropertyValue("CurrentCity").getStringValue();
    if (City == null){
        City = cityProp;
    } else {
        this.setPropertyValue("CurrentCity", new StringPrimitive(City));
    }

    String url = "http://api.openweathermap.org/data/2.5/weather?q=" +URLEncoder.encode(City,"UTF-8") + "&appid="+ _appid+"&units=imperial";

    // create a http client
    HttpClient client = HttpClientBuilder.create().build();

    // create a get request with the URL
    HttpGet request = new HttpGet(url);

    // add Accept header to accept json format response
    request.addHeader("Accept", "application/json");

    // send the get request and obtain a response
    HttpResponse response = client.execute(request);

    // if response is successful the status code will be 200.
    if (response.getStatusLine().getStatusCode() == 200) {
        BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder sb = new StringBuilder();
        String line = "";
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject) parser.parse(sb.toString());
        JSONArray weather = (JSONArray) json.get("weather");
        Iterator<JSONObject> it = weather.iterator();
        String description = (String) it.next().get("description");
        this.setPropertyValue("WeatherDescription", new StringPrimitive(description));
        Double temp = (Double) ((JSONObject) json.get("main")).get("temp");
        Number number = (Number) temp;
        this.setPropertyValue("Temperature", new NumberPrimitive(number));
        _logger.trace("Exiting Service: UpdateWeatherInfo");
    }
}
}

 

 

Click here to view Part 4 of this guide.

Version history
Last update:
‎Nov 11, 2022 05:09 PM
Updated by:
Labels (2)
Contributors