Run the code examples

The code examples in other Automation Center guides are structured differently than those in the First Steps guide. The following section describes how to create a framework for running the code examples for the SDK in each language.

Create a framework for running the code examples in the guides

Python

To run the code examples, create a framework for the Python client library that uses a main script to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main script imports  this file as a module, runs the functions of the file to make API calls to the Deep Security Manager and prints the returned output.

The below example shows how to run the code examples from the Configure Policy, Computer, and System Settings guide:

  1. Create a file named settings_examples.py and save the code examples from the Configure Policy, Computer, and System Settings guide into it.
  2. Create a file named properties.json and save the following JSON code into it, replacing the values for “url”  and “secretkey” with the URL and API key for your DSM:
    {
        "url": "https://192.168.17.143:4119/api",
        "secretkey": "2:HNVgA9U0Gf1F/+GtKB58ITFJkoCVxysoz/vTi5NmLPk="
    }

    Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

  3. Create a file named main.py and save the following code into it:
    import deepsecurity as api
    from deepsecurity.rest import ApiException as api_exception
    
    # Get the DSM URL and API key from the properties.json file
    import json
    
    with open('properties.json') as raw_properties:
        properties = json.load(raw_properties)
    
    secret_key = properties['secretkey']
    url =  properties['url']
    
    # Add the DSM information to the API client configuration
    configuration = api.Configuration() # Create a Configuration object
    configuration.host = url  # Set the URL of the DSM
    configuration.api_key['api-secret-key'] = secret_key  # Set the secret key for the DSM
    
    # Add the API version to a global variable
    api_version = 'v1'
    
    # Import the file with the code examples from the Create and Configure Policies guide
    import settings_examples
    
    # Add any additional global variables that will be shared across your functions
    # Variables for Settings examples
    settings_policy_id = 9
    
    def main():
        ''' Run the examples from the Create and Configure Policies guide
    
        Each function call passes the api client configuration information
        and any required variables and prints their output.
        '''
    
        # Settings examples
        print(
            "Displaying results from settings_examples.get_network_engine_mode:\n" +
            str(settings_examples.get_network_engine_mode(
                api, configuration, api_version, api_exception, settings_policy_id))
        )
    
        print(
            "Displaying results from settings_examples.set_network_engine_mode:\n" +
            str(settings_examples.set_network_engine_mode_to_inline(
                api, configuration, api_version, api_exception, settings_policy_id))
        )
    
    if __name__ == '__main__':
        main()
    
  4. Open a command line interface and type python main.py. The main.py script will run the settings_examples.py functions and print the returned output to the console.
JavaScript

To run the code examples, create a framework for the JavaScript client library that uses a main script to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main script imports this file as a module, runs the functions of the file to make API calls to the Deep Security Manager and prints the returned output.

The below example shows how to run the code examples from the Configure Policy, Computer, and System Settings guide:

    1. Create a new folder for your nodeJS project.
    2. Create a symbolic link from your nodeJS project to the @trendmicro/deepsecurity package (see the Link your project to the SDK package section on the JavaScript SDK page).
    3. Create a sub folder named ‘lib’.
    4. In the ‘lib’ folder, Create a file named SettingsExamples.js and save the code examples from the Configure Policy, Computer, and System Settings into it.
    5. Go back to the parent folder of ‘lib’.
    6. Create a file named properties.json and save the following JSON code into it, replacing the values for “url” and “secretkey” with the URL and API key for your DSM:
      {
          "url": "https://192.168.17.143:4119/api",
          "secretkey": "2:HNVgA9U0Gf1F/+GtKB58ITFJkoCVxysoz/vTi5NmLPk="
      }

      Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

    7. Create a file named App.js and save the following code into it:
      // Import the client library
      const api = require("@trendmicro/deepsecurity");
      const path = require("path");
      const fs = require('fs');
      
      // Get the DSM URL and API key from the properties.json file
      let rawProperties = fs.readFileSync("properties.json");
      let properties = JSON.parse(rawProperties);
      
      // Assign the API key to a variable
      const secretkey = properties.secretkey;
      
      // Create the client and configure the Deep Security Manager address
      const defaultClient = api.ApiClient.instance;
      defaultClient.basePath = properties.url;
      
      // Configure the client to use the API key
      const DefaultAuthentication = defaultClient.authentications['DefaultAuthentication'];
      DefaultAuthentication.apiKey = secretkey;
      
      // Import the SettingsExample module
      const SettingsExamples = require(path.resolve(__dirname, "lib/SettingsExamples.js"));
      
      // Assign value used by the settings examples to variables
      const settingsPolicyID = 9
      
      // Run functions
      SettingsExamples.getNetworkEngineMode(api, settingsPolicyID, "v1")
      .then(data => {
         console.log("Network engine mode is " + data);
      })
      .then( () => {
      return SettingsExamples.setNetworkEngineModeToInline(api, settingsPolicyID, "v1")
      .then(data => {
          console.log("Network engine mode has been set to " + data);
          })
      })
      .catch(error => {
        console.log(error);
      });
      
    8. Open a command line interface and type node App.js. The App.js script will run the SettingsExamples.js functions and print the returned output to the console.
Java
  • To run the code examples, create a framework for the Java client library that uses a main class to import the client library and configure authentication with the Deep Security Manager. Save the code examples in a separate file. The main class imports this file as a class and runs the methods of the file to make API calls to the Deep Security Manager.You should use a Java IDE. If you don’t already have an IDE installed, we suggest that you use Eclipse. You can find instructions for configuring the client library in the Java SDK guide.
  • The below example shows how to run some of the code examples from the Create and Configure Policies guide:
    • Note: This example uses the package name of com.trendmicro.deepsecurity.docs. If you use a different package name you will need to modify the examples accordingly.

      1. Open the Deep Security project in Eclipse.
      2. Right-click the com.trendmicro.deepsecurity.docs package and click New > Folder. Name the folder ‘Resources’ and click Finish.
      3. Right-click the parent package (for example, com.trendmicro.deepsecurity.docs) and click New > Class, type ‘PolicyExample’ for the name, and click Finish.
      4. In the PolicyExample.java file, below the package declaration, add the following imports:
        import java.lang.reflect.Method;
        import com.trendmicro.deepsecurity.ApiException;
        import com.trendmicro.deepsecurity.model.Computer;
        import com.trendmicro.deepsecurity.model.LogInspectionRule;
        import com.trendmicro.deepsecurity.model.Policies;
        import com.trendmicro.deepsecurity.model.Policy;
        import com.trendmicro.deepsecurity.model.SearchCriteria;
        import com.trendmicro.deepsecurity.model.SearchFilter;
        import com.trendmicro.deepsecurity.api.ComputersApi;
        import com.trendmicro.deepsecurity.api.PoliciesApi;
        import com.trendmicro.deepsecurity.api.PolicyLogInspectionRuleDetailsApi;
      5. Inside the class block, add the following code examples from the Create and Configure Policies guide, then save the file:
        • Create a policy below Base Policy
        • Search for a policy and add it to a computer
        • Selectively reset overrides of a rule
      6. Right-click the ‘Resources’ package and click New > File, name it ‘example.properties’, and click Finish.
      7. Add the following text to the file, and replace the values for “secretkey” and “url” with the URL and API key for your DSM:
        secretkey=2:7jj01PcE9JiHgaXc0Mmo8oMURAgwtkBXV+zn/XcF+iE=
        url=https://192.168.17.143:4119

        Note: The Deep Security Manager URL and API key are sensitive data. By storing them outside of your script, you can prevent them from entering any shared spaces or repositories your scripts belong to.

      8. Right-click the parent package (for example, com.trendmicro.deepsecurity.docs) and click New > Class, type ‘Main’ for the class name, and click Finish.
      9. Overwrite the template code with the following:
        package com.trendmicro.deepsecurity.docs;
        
        import java.io.IOException;
        import java.io.InputStream;
        import java.util.Properties;
        import java.util.concurrent.ThreadLocalRandom;
        
        import com.trendmicro.deepsecurity.ApiClient;
        import com.trendmicro.deepsecurity.Configuration;
        import com.trendmicro.deepsecurity.auth.ApiKeyAuth;
        
        import com.trendmicro.deepsecurity.docs.PolicyExample;
        import com.trendmicro.deepsecurity.model.Policy;
        
        /*
         * A simple framework for running code examples from the Deep Security Automation Center guides.
         */
        public class Main {
        	
        	//Values to use for example method arguments. Edit according to your environment.
        	private static String policyName = "Test Policy " + ThreadLocalRandom.current().nextInt(1, 1000);  //Random suffix avoids collisions
        	private static Integer computerID = new Integer(1);
        	private static Integer policyID = new Integer(8);
        	private static Integer liRuleID = new Integer(20);
        
        	public static void main(String[] args) {
        
        		//Retrieve the DSM url and secret key from the properties file
        		Properties prop = new Properties();
        		ClassLoader loader = Thread.currentThread().getContextClassLoader();           
        		InputStream stream = loader.getResourceAsStream("com/trendmicro/deepsecurity/docs/Resources/example.properties");
        		try {
        			prop.load(stream);
        		} catch (IOException e) {
        			System.out.println(e.getMessage());
        			e.printStackTrace();
        		}
        
        		//Configure ApiClient
        		ApiClient dsmClient = Configuration.getDefaultApiClient();
        		dsmClient.setBasePath(prop.getProperty("url") + "/api");
        		ApiKeyAuth DefaultAuthentication = (ApiKeyAuth) dsmClient.getAuthentication("DefaultAuthentication");
        		DefaultAuthentication.setApiKey(prop.getProperty("secretkey"));
        
        		//Run the policy examples
        		runPolicyExamples();
        	}
        
        	/*
        	 * Runs the examples in the com.trendmicro.deepsecurity.docs.PolicyExample class.
        	 * The policy name, computer ID, and Log Inspection rule ID values are stored
        	 * in global variables.
        	 */
        	private static void runPolicyExamples() {
        		PolicyExample policyExample = new PolicyExample();
        		Policy testPolicy = policyExample.createPolicy(policyName);
        		policyExample.assignLinuxServerPolicy(computerID);
        		policyExample.selectiveResetForLogInspectionRuleOnPolicy(policyID, liRuleID);
        	}
        
        }
      10. To run the code examples, click Run > Run As > Java Application.