/**
   * TO get list of values /rows for a given modules based on selection criteria
   *
   * @param sessionID
   * @param binding
   * @param moduleName TODO
   * @param select_fields
   * @param l
   * @param offset
   */
  private static void retreiveEntriesByModule(
      String sessionID,
      SugarsoapBindingStub binding,
      String moduleName,
      String[] select_fields,
      int offset,
      int rowCount) {
    Link_name_to_fields_array[] link_name_to_fields_array = null;

    Get_entry_result_version2 getEntryResponse = null;
    Get_entry_list_result_version2 entryListResultVersion2 = null;

    // Trying to get entry
    try {
      /*
       * getEntryResponse = binding.get_entry(sessionID,moduleName, null,
       * select_fields, link_name_to_fields_array);
       */
      entryListResultVersion2 =
          binding.get_entry_list(
              sessionID,
              moduleName,
              "",
              "",
              offset,
              select_fields,
              link_name_to_fields_array,
              rowCount,
              0);
      // getEntryResponse = binding.get_entries(sessionID, moduleName,
      // null, new String[]{"name","description"},
      // link_name_to_fields_array);

    } catch (RemoteException e) {
      System.out.println("Get entry failed. Message: " + e.getMessage());
      e.printStackTrace();
    }
    System.out.println("Get entry was successful! Response: ");

    // Getting the fields for entry we got.
    Entry_value[] entryList = entryListResultVersion2.getEntry_list();
    for (int k = 0; k < entryList.length; k++) {
      Entry_value entry = entryList[k];
      Name_value[] entryNameValueList = entry.getName_value_list();
      System.out.println();
      for (int j = 0; j < entryNameValueList.length; j++) {
        Name_value entryNameValue = entryNameValueList[j];
        // Outputting only non empty fields
        if (!entryNameValue.getValue().isEmpty()) {
          System.out.print(entryNameValue.getName() + ":" + entryNameValue.getValue() + "    ;   ");
        }
      }
    }
  }
  /**
   * Main Program
   *
   * @param args
   */
  public static void main(String[] args) throws Exception {
    String sessionID = null;

    try {
      // Create a URL end point for the client
      URL wsdlUrl = null;
      if (END_POINT_URL.isEmpty()) {
        wsdlUrl = new URL(new SugarsoapLocator().getsugarsoapPortAddress() + "?wsdl");
      } else {
        wsdlUrl = new URL(END_POINT_URL);
      }

      System.out.println("URL endpoint created successfully!");

      // Create Service for test configuration
      ServiceFactory serviceFactory = ServiceFactory.newInstance();
      Service service =
          serviceFactory.createService(wsdlUrl, new SugarsoapLocator().getServiceName());

      System.out.println("Service created successfully");
      System.out.println("Service Name:" + service.getServiceName().toString());
      System.out.println("Service WSDL:" + service.getWSDLDocumentLocation().toString());

      // Trying to create a stub
      SugarsoapBindingStub binding = new SugarsoapBindingStub(wsdlUrl, service);
      binding.setTimeout(TIMEOUT);
      System.out.println("Stub created successfully!");

      /**
       * Try to login on SugarCRM
       *
       * <p>1) Prepare a MD5 hash password 2) Prepare a User Auth object 3) Execute login
       */

      // 1. Prepare a MD5 hash password
      MessageDigest messageDiget = MessageDigest.getInstance("MD5");
      messageDiget.update(USER_PASSWORD.getBytes());

      // 2. Prepare a User Auth object
      User_auth userAuthInfo = new User_auth();
      userAuthInfo.setUser_name(USER_NAME);
      userAuthInfo.setPassword((new BigInteger(1, messageDiget.digest())).toString(16));

      try {
        // 3. Execute login
        Entry_value loginResult = binding.login(userAuthInfo, APPLICATION_NAME, null);
        System.out.println("Login Successfully for " + USER_NAME);
        System.out.println("Your session Id: " + loginResult.getId());
        sessionID = loginResult.getId();
      } catch (RemoteException ex) {
        System.out.println("Login failed. Message: " + ex.getMessage());
        ex.printStackTrace();
      }
      // binding.
      // binding.get_available_modules(session);
      // retreiveEntriesByModule(sessionID, binding, "Accounts",new
      // String[]{"name","description"},0,10);
      retreiveEntriesByModule(
          sessionID,
          binding,
          "Leads",
          new String[] {
            "name", "description", "account_name", "campaign_name",
            "salutation", "first_name", "last_name", "full_name",
            "title", "department", "email1", "email2"
          },
          0,
          10);
      retreiveEntriesByModule(
          sessionID,
          binding,
          "Campaigns",
          new String[] {
            "name", "description", "assigned_user_name", "status", "campaign_type", "expected_cost"
          },
          0,
          10);
      // retreiveModuleFields(sessionID, binding);
      // retreiveModules(sessionID, binding);
      // createAndRetreiveContact(sessionID, binding);

      /** Logout */
      try {
        binding.logout(sessionID);
        System.out.println("Logout Successfully for " + USER_NAME);
        sessionID = null;
      } catch (RemoteException ex) {
        System.out.println("Login failed. Message: " + ex.getMessage());
        ex.printStackTrace();
      }

    } catch (MalformedURLException ex) {
      System.out.println("URL endpoing creation failed. Message: " + ex.getMessage());
      ex.printStackTrace();
    } catch (ServiceException ex) {
      System.out.println("Service creation failed. Message: " + ex.getMessage());
      ex.printStackTrace();
    } catch (AxisFault ex) {
      System.out.println("AxisFault. Message: " + ex.getMessage());
      ex.printStackTrace();
    }
  }
  /**
   * Sample to show how to do creation operation using webservice
   *
   * @param sessionID
   * @param binding
   */
  private static void createAndRetreiveContact(String sessionID, SugarsoapBindingStub binding) {
    /**
     * Create a new Contact
     *
     * <p>1) Setting a new entry 2) Setting up parameters for set_entry call 3) Creating a name
     * value list array from a hash map. This is not necessary just more elegant way to initialize
     * and add name values to an array
     */
    HashMap<String, String> nameValueMap = new HashMap<String, String>();
    nameValueMap.put("first_name", "Suresh");
    nameValueMap.put("last_name", "Paladugu");
    nameValueMap.put("title", "IT Senior Consultant");
    nameValueMap.put("description", "Test Client SOAP Java");
    nameValueMap.put("email1", "*****@*****.**");

    // Creating a new Name_value array and adding each map entry as 'name'
    // and 'value'
    Name_value nameValueListSetEntry[] = new Name_value[nameValueMap.size()];
    int i = 0;
    for (Entry<String, String> entry : nameValueMap.entrySet()) {
      Name_value nameValue = new Name_value();
      nameValue.setName(entry.getKey());
      nameValue.setValue(entry.getValue());
      nameValueListSetEntry[i] = nameValue;
      i++;
    }

    // Trying to set a new entry
    New_set_entry_result setEntryResponse = null;
    try {
      setEntryResponse = binding.set_entry(sessionID, "Contacts", nameValueListSetEntry);
    } catch (RemoteException e) {
      System.out.println("Set entry failed. Message: " + e.getMessage());
      e.printStackTrace();
    }
    System.out.println("Set entry was successful! Contacts Id: " + setEntryResponse.getId());

    /** Getting an Contacts Entry (the one we just set) */
    Link_name_to_fields_array[] link_name_to_fields_array = null;
    String[] select_fields = null;

    Get_entry_result_version2 getEntryResponse = null;

    // Trying to get entry
    try {
      getEntryResponse =
          binding.get_entry(
              sessionID,
              "Contacts",
              setEntryResponse.getId(),
              select_fields,
              link_name_to_fields_array);
    } catch (RemoteException e) {
      System.out.println("Get entry failed. Message: " + e.getMessage());
      e.printStackTrace();
    }
    System.out.println("Get entry was successful! Response: ");

    // Getting the fields for entry we got.
    Entry_value[] entryList = getEntryResponse.getEntry_list();
    for (int k = 0; k < entryList.length; k++) {
      Entry_value entry = entryList[k];
      Name_value[] entryNameValueList = entry.getName_value_list();
      for (int j = 0; j < entryNameValueList.length; j++) {
        Name_value entryNameValue = entryNameValueList[j];
        // Outputting only non empty fields
        if (!entryNameValue.getValue().isEmpty()) {
          System.out.println(
              "Attribute Name: '"
                  + entryNameValue.getName()
                  + "' Attribute Value: '"
                  + entryNameValue.getValue()
                  + "'");
        }
      }
    }
  }