// Copyright (c) Trend Micro Inc. 2004-2012, All Rights Reserved

package com.trendmicro.webserviceclient.samples;

import java.net.URL;

import com.trendmicro.webserviceclient.generated.*;
import com.trendmicro.webserviceclient.utils.ClientUtils;

/*
 * CreateIpList: This sample application is designed demonstrate how to correctly
 * create, modify, save and retrieve a new Transport class, such as IPListTransport.
 *
 * NOTE: All available Transport classes possess different properties. When creating
 * an unfamiliar Transport class from scratch, it is not necessary to set the ID
 * property as the manager service will automatically enumerate it. When saving a
 * new Transport class, the newly saved version will be returned and any manager
 * populated properties will be set. Any further modification to the class should be
 * applied to the returned class and not the original class created from scratch.
 */
public class CreateIpList extends ClientUtils {
	public static int arg_count = 5;
	public static String arg_usage =
		" <webservice url> <username> <password> <IP List Name> <IP List Items>\n" +
		"\n" +
		"  <IP List Name>:  Name must be double quoted\n" +
		"  <IP List Items>: List must be double quoted. Multiple items must be comma\n" +
		"                   delimited and in the following supported format:\n" +
		"    Masked IP:\n" +
		"      X.X.X.X/1-32          Example: 192.168.2.33/24\n" +
		"      X.X.X.X/Y.Y.Y.Y       Example: 192.168.2.33/255.255.255.0\n" +
		"      X.*.*.*               Example: 192.168.2.*\n" +
		"\n" +
		"    Range:\n" +
		"      X.X.X.X-Y.Y.Y.Y       Example: 192.168.0.2 - 192.168.0.125\n" +
		"\n" +
		"    Comments:\n" +
		"      IP or Range #Comment  Example: 255.255.255.255 #Broadcast IP\n" +
		"\n" +
		"Example:\n" +
		"  https://<manager>:4119/webservice/Manager <admin> <password> \"Test List\" \"192.168.0.1 - 192.168.0.25,10.0.0.1\"\n";
	public static int arg_endpoint = 0;
	public static int arg_user = 1;
	public static int arg_pass = 2;
	public static int arg_list_name = 3;
	public static int arg_list = 4;

	public static String sid = null;

	public CreateIpList(String app_name, String[] args) throws Exception {
		super(app_name, arg_count, arg_usage, args);
	}

	public void doCreateList() throws Exception {
		String endpoint = this.getArg(arg_endpoint);
		String user = this.getArg(arg_user);
		String pass = this.getArg(arg_pass);
		String ipListName = this.getArg(arg_list_name);
		String ipList = this.getArg(arg_list);

		_ManagerService = _Service.getManager(new URL(endpoint));
		try {
            /*
             * It is recommended that during initalization or start up, a version test of the
             * Web Service API be performed to ensure that Web Service API client implementations
             * built against a mis-matched version of the Deep Security Manager Web Service end
             * point does not unexpectedly break the client application.
             */
            this.log("Manager Web Service API Version: " + _ManagerService.getApiVersion());

            /*
             * When making any manager service call, such as attempting to authenticate,
             * ensure the Exception is caught. The resulting Exception message will contain
             * an explaination of any failures.
             */
			this.log("Attempting to authenticate to Manager WebService...");
			sid = _ManagerService.authenticate(user, pass);
			this.log("Authentication successful.");
			this.log("Authentication session ID string recieved: " + sid);

			this.log("IP List creation and modification parameters:");
			this.log(" - IP List name: " + ipListName);
			this.log(" - IP List items: " + ipList);

			/*
			 * When creating a new Transport class, always test to ensure that a duplicate
			 * Transport class does not already exist. Methods of Transport class can vary
			 * depending on the class type, but generally speaking testing for an existing
			 * Transport class by Name is a good idea.
			 */
			IPListTransport currentIpList = _ManagerService.IPListRetrieveByName(ipListName, sid);
			if(currentIpList == null) {
				this.log("IP List transport class named " + ipListName + " does not exist.");

				/*
				 * When creating a new Transport class from scratch, do not set the ID property
				 * as the server will enumerate it automatically.
				 */
				this.log("Creating new empty IP List transport class named " + ipListName + "...");
				IPListTransport newIpList = new IPListTransport();
				newIpList.setName(ipListName);
				newIpList.setItems(ipList);

				/*
				 * When saving a new Transport class, any further modification of
				 * the Transport class should be applied to the returned Transport class or
				 * the newly saved Transport class should be retrieved from the Manager.
				 */
				this.log("Saving new IP List transport class...");
				currentIpList = _ManagerService.IPListSave(newIpList, sid);
			} else {
				this.log("IP List transport class named " + ipListName + " already exists.");

				/*
				 * When saving a modified Transport class, any further modification of
				 * the Transport class should be applied to the returned Transport class or
				 * the Transport class should be retrieved from the Manager.
				 */
				this.log("Modifying IP List transport class with new items: " + ipList);
				currentIpList.setItems(ipList);
				_ManagerService.IPListSave(currentIpList, sid);
			}

			this.log("Retrieving newly created and modified IP List...");
			currentIpList = _ManagerService.IPListRetrieveByName(ipListName, sid);
			if(currentIpList == null) {
				/*
				 * Always test if a retrieved Transport class did not return as
				 * null before reading or writing to it, even when you're certain
				 * the class exists in the manager.
				 */
				throw new Exception("IP List could not be found.");
			} else {
				this.log("IP List name: " + currentIpList.getName());
				this.log("IP List ID: " + currentIpList.getID());
				this.log("IP List Items:\n" + currentIpList.getItems());
			}
		} catch(ManagerException em) {
			/*
			 * Any manager service call failures will be explained in the
			 * ManagerException fault string property.
			 */
			this.log(em.getFaultString());
		} catch(Exception e) {
			this.log("Error: " + e.getMessage());
		} finally {
			/*
			 * Always attempt to end the manager service session.
			 */
			if (sid != null)
			{
				this.log("");
				this.log("Ending session...");
				_ManagerService.endSession(sid);
				this.log("End session successful.");
			}
		}
	}

   /**
    * The main entry point.
    */
	public static void main(String[] args) throws Exception {
		CreateIpList client = new CreateIpList("CreateIpList", args);
		if(!client.validateArgs()) {
			client.printUsage("Invalid number of arguments found.");
			return;
		}
		client.doCreateList();
	}
}
