Exemple #1
0
  public PaymentWS createPaymentWS(Integer userId, Date date, String note) throws Exception {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    PaymentWS payment = new PaymentWS();
    payment.setAmount(new BigDecimal("15.00"));
    payment.setIsRefund(new Integer(0));
    payment.setMethodId(Constants.PAYMENT_METHOD_CHEQUE);
    payment.setPaymentDate(date);
    payment.setCreateDatetime(date);
    payment.setResultId(Constants.RESULT_ENTERED);
    payment.setCurrencyId(new Integer(1));
    payment.setUserId(userId);
    payment.setPaymentNotes(note);
    payment.setPaymentPeriod(new Integer(1));

    PaymentInformationWS cheque =
        com.sapienter.jbilling.server.user.WSTest.createCheque("ws bank", "2232-2323-2323", date);

    payment.getPaymentInstruments().add(cheque);
    System.out.println("Applying payment");
    Integer ret = api.applyPayment(payment, new Integer(35));
    System.out.println("Created payemnt " + ret);
    assertNotNull("Didn't get the payment id", ret);

    payment.setId(ret);
    return payment;
  }
Exemple #2
0
  public void testDelete() {
    try {
      JbillingAPI api = JbillingAPIFactory.getAPI();
      Integer invoiceId = new Integer(1);
      assertNotNull(api.getInvoiceWS(invoiceId));
      api.deleteInvoice(invoiceId);
      try {
        api.getInvoiceWS(invoiceId);
        fail("Invoice should not have been deleted");
      } catch (Exception e) {
        // ok
      }

      // try to delete an invoice that is not mine
      try {
        api.deleteInvoice(new Integer(75));
        fail("Not my invoice. It should not have been deleted");
      } catch (Exception e) {
        // ok
      }

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    }
  }
Exemple #3
0
  public void testCreateInvoiceFromOrder() throws Exception {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    final Integer USER_ID = 10730; // user has no orders

    // setup orders
    OrderWS order = new OrderWS();
    order.setUserId(USER_ID);
    order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
    order.setPeriod(1); // once
    order.setCurrencyId(1);
    order.setActiveSince(new Date());

    OrderLineWS line = new OrderLineWS();
    line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
    line.setDescription("Order line");
    line.setItemId(1);
    line.setQuantity(1);
    line.setPrice(new BigDecimal("10.00"));
    line.setAmount(new BigDecimal("10.00"));

    order.setOrderLines(new OrderLineWS[] {line});

    // create orders
    Integer orderId1 = api.createOrder(order);
    Integer orderId2 = api.createOrder(order);

    // generate invoice using first order
    Integer invoiceId = api.createInvoiceFromOrder(orderId1, null);

    assertNotNull("Order 1 created", orderId1);
    assertNotNull("Order 2 created", orderId2);
    assertNotNull("Invoice created", invoiceId);

    Integer[] invoiceIds = api.getLastInvoices(USER_ID, 2);
    assertEquals("Only 1 invoice was generated", 1, invoiceIds.length);

    InvoiceWS invoice = api.getInvoiceWS(invoiceId);
    assertEquals("Invoice total is $10.00", new BigDecimal("10.00"), invoice.getTotalAsDecimal());
    assertEquals("Only 1 order invoiced", 1, invoice.getOrders().length);
    assertEquals("Invoice generated from 1st order", orderId1, invoice.getOrders()[0]);

    // add second order to invoice
    Integer invoiceId2 = api.createInvoiceFromOrder(orderId2, invoiceId);
    assertEquals("Order added to the same invoice", invoiceId, invoiceId2);

    invoiceIds = api.getLastInvoices(USER_ID, 2);
    assertEquals("Still only 1 invoice generated", 1, invoiceIds.length);

    invoice = api.getInvoiceWS(invoiceId);
    assertEquals("Invoice total is $20.00", new BigDecimal("20.00"), invoice.getTotalAsDecimal());
    assertEquals("2 orders invoiced", 2, invoice.getOrders().length);

    // cleanup
    api.deleteInvoice(invoiceId);
    api.deleteOrder(orderId1);
    api.deleteOrder(orderId2);
  }
Exemple #4
0
  @BeforeClass
  protected void setUp() throws Exception {
    api = JbillingAPIFactory.getAPI();
    mordorApi = JbillingAPIFactory.getAPI("apiClientMordor");
    CURRENCY_USD = Constants.PRIMARY_CURRENCY_ID;
    CURRENCY_AUD = Integer.valueOf(11);
    LANGUAGE_ID = Constants.LANGUAGE_ENGLISH_ID;
    PRANCING_PONY_ACCOUNT_TYPE = Integer.valueOf(1);
    MORDOR_ACCOUNT_TYPE = Integer.valueOf(2);
    PAYMENT_PERIOD = Integer.valueOf(1);
    ORDER_PERIOD_ONCE = Integer.valueOf(1);
    ORDER_CHANGE_STATUS_APPLY = getOrCreateOrderChangeStatusApply(api);
    STATUS_SUSPENDED = getOrCreateSuspendedStatus(api);

    CC_PAYMENT_TYPE = api.createPaymentMethodType(PaymentMethodHelper.buildCCTemplateMethod(api));
    ACH_PAYMENT_TYPE = api.createPaymentMethodType(PaymentMethodHelper.buildACHTemplateMethod(api));
    CHEQUE_PAYMENT_TYPE =
        api.createPaymentMethodType(PaymentMethodHelper.buildChequeTemplateMethod(api));
  }
Exemple #5
0
  public void testGetPaperInvoicePDF() throws Exception {
    final Integer USER_ID = 2; // user has invoices

    JbillingAPI api = JbillingAPIFactory.getAPI();

    Integer[] invoiceIds = api.getLastInvoices(USER_ID, 1);
    assertEquals("Invoice found for user", 1, invoiceIds.length);

    byte[] pdf = api.getPaperInvoicePDF(invoiceIds[0]);
    assertTrue("PDF invoice bytes returned", pdf.length > 0);
  }
Exemple #6
0
 public void testCreateInvoiceSecurity() {
   try {
     JbillingAPI api = JbillingAPIFactory.getAPI();
     try {
       api.createInvoice(13, false);
       fail("User 13 belongs to entity 2");
     } catch (Exception e) {
     }
   } catch (Exception e) {
     e.printStackTrace();
     fail("Exception caught:" + e);
   }
 }
Exemple #7
0
  public void testGetTotalAsDecimal() {
    List<Integer> invoiceIds = new ArrayList<Integer>();
    List<Integer> orderIds = new ArrayList<Integer>();
    JbillingAPI api = null;
    try {
      final Integer USER_ID = 10730; // user has no orders
      api = JbillingAPIFactory.getAPI();

      // test BigDecimal behavior
      assertFalse(new BigDecimal("1.1").equals(new BigDecimal("1.10")));
      assertTrue(new BigDecimal("1.1").compareTo(new BigDecimal("1.10")) == 0);

      // with items 2 and 3 10% discount should apply
      orderIds.add(
          api.createOrder(
              com.sapienter.jbilling.server.order.WSTest.createMockOrder(
                  USER_ID, 3, new BigDecimal("0.32"))));
      orderIds.add(
          api.createOrder(
              com.sapienter.jbilling.server.order.WSTest.createMockOrder(
                  USER_ID, 3, new BigDecimal("0.32"))));

      invoiceIds.addAll(Arrays.asList(api.createInvoice(USER_ID, false)));
      assertEquals(1, invoiceIds.size());

      InvoiceWS invoice = api.getInvoiceWS(invoiceIds.get(0));
      assertEquals("1.7300000000", invoice.getTotal());
      assertEquals(new BigDecimal("1.730"), invoice.getTotalAsDecimal());

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    } finally {
      try {
        for (Integer integer : invoiceIds) {
          api.deleteInvoice(integer);
        }
        System.out.println("Successfully deleted invoices: " + invoiceIds.size());
        for (Integer integer : orderIds) {
          api.deleteOrder(integer);
        }
        System.out.println("Successfully deleted orders: " + orderIds.size());
      } catch (Exception ignore) {
      }
    }
  }
Exemple #8
0
  @Test
  public void testNewGetPaymentsApiMethods() throws Exception {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    // Create a user with balance $1.00
    UserWS user = com.sapienter.jbilling.server.user.WSTest.createUser(true, null, null);

    List<PaymentWS> payments = new ArrayList<PaymentWS>();

    for (int i = 0; i < 5; i++) {
      payments.add(
          createPaymentWS(
              user.getUserId(), new DateTime().plusMonths(i).toDate(), String.valueOf(i)));
    }

    // get two latest payments except the latest one.
    Integer[] paymentsId = api.getLastPaymentsPage(user.getUserId(), 2, 1);

    assertEquals(2, paymentsId.length);

    assertEquals("3", api.getPayment(paymentsId[0]).getPaymentNotes());
    assertEquals("2", api.getPayment(paymentsId[1]).getPaymentNotes());

    // get the payments between next month and four months from now.
    Integer[] paymentsId2 =
        api.getPaymentsByDate(
            user.getUserId(),
            new DateTime().plusDays(1).toDate(),
            new DateTime().plusMonths(3).plusDays(1).toDate());

    assertEquals(3, paymentsId2.length);

    assertEquals("3", api.getPayment(paymentsId2[0]).getPaymentNotes());
    assertEquals("2", api.getPayment(paymentsId2[1]).getPaymentNotes());
    assertEquals("1", api.getPayment(paymentsId2[2]).getPaymentNotes());

    // Delete orders
    for (PaymentWS payment : payments) {
      api.deletePayment(payment.getId());
    }
    // Delete user
    api.deleteUser(user.getUserId());
  }
  public static UserWS createUser() throws JbillingAPIException, IOException {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    // Create - This passes the password validation routine.

    UserWS newUser = new UserWS();
    newUser.setUserId(0); // it is validated
    newUser.setUserName("testUserName-" + Calendar.getInstance().getTimeInMillis());
    newUser.setPassword("P@ssword1");
    newUser.setLanguageId(Integer.valueOf(1));
    newUser.setMainRoleId(Integer.valueOf(5));
    newUser.setAccountTypeId(Integer.valueOf(1));
    newUser.setParentId(null); // this parent exists
    newUser.setStatusId(UserDTOEx.STATUS_ACTIVE);
    newUser.setCurrencyId(new Integer(1));
    newUser.setInvoiceChild(new Boolean(false));

    return newUser;
  }
Exemple #10
0
  public void testGetUserInvoicesByDate() {
    try {
      final Integer USER_ID = 2; // user has some invoices
      JbillingAPI api = JbillingAPIFactory.getAPI();

      // invoice dates: 2006-07-26
      // select the week
      Integer[] result = api.getUserInvoicesByDate(USER_ID, "2006-07-23", "2006-07-29");
      // note: invoice 1 gets deleted
      assertEquals("Number of invoices returned", 3, result.length);
      assertEquals("Invoice id 4", 4, result[0].intValue());
      assertEquals("Invoice id 3", 3, result[1].intValue());
      assertEquals("Invoice id 2", 2, result[2].intValue());

      // test since date inclusive
      result = api.getUserInvoicesByDate(USER_ID, "2006-07-26", "2006-07-29");
      assertEquals("Number of invoices returned", 3, result.length);
      assertEquals("Invoice id 4", 4, result[0].intValue());
      assertEquals("Invoice id 3", 3, result[1].intValue());
      assertEquals("Invoice id 2", 2, result[2].intValue());

      // test until date inclusive
      result = api.getUserInvoicesByDate(USER_ID, "2006-07-23", "2006-07-26");
      assertEquals("Number of invoices returned", 3, result.length);
      assertEquals("Invoice id 4", 4, result[0].intValue());
      assertEquals("Invoice id 3", 3, result[1].intValue());
      assertEquals("Invoice id 2", 2, result[2].intValue());

      // test date with no invoices
      result = api.getUserInvoicesByDate(USER_ID, "2005-07-23", "2005-07-29");
      // Note: CXF returns null for empty array
      if (result != null) {
        assertEquals("Number of invoices returned", 0, result.length);
      }

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    }
  }
Exemple #11
0
  public void testGet() {
    try {
      JbillingAPI api = JbillingAPIFactory.getAPI();

      // get
      // try getting one that doesn't belong to us
      try {
        System.out.println("Getting invalid invoice");
        api.getInvoiceWS(75);
        fail("Invoice 75 belongs to entity 2");
      } catch (Exception e) {
      }

      System.out.println("Getting invoice");
      InvoiceWS retInvoice = api.getInvoiceWS(15);
      assertNotNull("invoice not returned", retInvoice);
      assertEquals("invoice id", retInvoice.getId(), new Integer(15));
      System.out.println("Got = " + retInvoice);

      // latest
      // first, from a guy that is not mine
      try {
        api.getLatestInvoice(13);
        fail("User 13 belongs to entity 2");
      } catch (Exception e) {
      }
      System.out.println("Getting latest invoice");
      retInvoice = api.getLatestInvoice(2);
      assertNotNull("invoice not returned", retInvoice);
      assertEquals("invoice's user id", retInvoice.getUserId(), new Integer(2));
      System.out.println("Got = " + retInvoice);
      Integer lastInvoice = retInvoice.getId();

      // List of last
      // first, from a guy that is not mine
      try {
        api.getLastInvoices(13, 5);
        fail("User 13 belongs to entity 2");
      } catch (Exception e) {
      }
      System.out.println("Getting last 5 invoices");
      Integer invoices[] = api.getLastInvoices(2, 5);
      assertNotNull("invoice not returned", invoices);

      retInvoice = api.getInvoiceWS(invoices[0]);
      assertEquals("invoice's user id", new Integer(2), retInvoice.getUserId());
      System.out.println("Got = " + invoices.length + " invoices");
      for (int f = 0; f < invoices.length; f++) {
        System.out.println(" Invoice " + (f + 1) + invoices[f]);
      }

      // now I want just the two latest
      System.out.println("Getting last 2 invoices");
      invoices = api.getLastInvoices(2, 2);
      assertNotNull("invoice not returned", invoices);
      retInvoice = api.getInvoiceWS(invoices[0]);
      assertEquals("invoice's user id", new Integer(2), retInvoice.getUserId());
      assertEquals("invoice's has to be latest", lastInvoice, retInvoice.getId());
      assertEquals("there should be only 2", 2, invoices.length);

      // get some by date
      System.out.println("Getting by date (empty)");
      Integer invoices2[] = api.getInvoicesByDate("2000-01-01", "2005-01-01");
      // CXF returns null instead of empty arrays
      // assertNotNull("invoice not returned", invoices2);
      if (invoices2 != null) {
        assertTrue("array not empty", invoices2.length == 0);
      }

      System.out.println("Getting by date");
      invoices2 = api.getInvoicesByDate("2006-01-01", "2007-01-01");
      assertNotNull("invoice not returned", invoices2);
      assertFalse("array not empty", invoices2.length == 0);
      System.out.println("Got array " + invoices2.length + " getting " + invoices2[0]);
      retInvoice = api.getInvoiceWS(invoices2[0]);
      assertNotNull("invoice not there", retInvoice);
      System.out.println("Got invoice " + retInvoice);

      System.out.println("Done!");

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    }
  }
Exemple #12
0
  /**
   * Tests that when a past due invoice is processed it will generate a new invoice for the current
   * period that contains all previously un-paid balances as the carried balance.
   *
   * <p>Invoices that have been carried still show the original balance for reporting/paper-trail
   * purposes, but will not be re-processed by the system as part of the normal billing process.
   *
   * @throws Exception
   */
  public void testCreateWithCarryOver() throws Exception {
    final Integer USER_ID = 10743; // user has one past-due invoice to be carried forward
    final Integer OVERDUE_INVOICE_ID = 70; // holds a $20 balance

    JbillingAPI api = JbillingAPIFactory.getAPI();

    // new order witha  single line item
    OrderWS order = new OrderWS();
    order.setUserId(USER_ID);
    order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
    order.setPeriod(1); // once
    order.setCurrencyId(1);
    order.setActiveSince(new Date());

    OrderLineWS line = new OrderLineWS();
    line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
    line.setDescription("Order line");
    line.setItemId(1);
    line.setQuantity(1);
    line.setPrice(new BigDecimal("10.00"));
    line.setAmount(new BigDecimal("10.00"));

    order.setOrderLines(new OrderLineWS[] {line});

    // create order
    Integer orderId = api.createOrder(order);

    // create invoice
    Integer invoiceId = api.createInvoice(USER_ID, false)[0];

    // validate that the overdue invoice has been carried forward to the newly created invoice
    InvoiceWS overdue = api.getInvoiceWS(OVERDUE_INVOICE_ID);

    assertEquals(
        "Status updated to 'unpaid and carried'",
        Constants.INVOICE_STATUS_UNPAID_AND_CARRIED,
        overdue.getStatusId());
    assertEquals("Carried invoice will not be re-processed", 0, overdue.getToProcess().intValue());
    assertEquals(
        "Overdue invoice holds original balance",
        new BigDecimal("20.00"),
        overdue.getBalanceAsDecimal());

    assertEquals(
        "Overdue invoice delegated to the newly created invoice",
        invoiceId,
        overdue.getDelegatedInvoiceId());

    // validate that the newly created invoice contains the carried balance
    InvoiceWS invoice = api.getInvoiceWS(invoiceId);

    assertEquals(
        "New invoice balance is equal to the current period charges",
        new BigDecimal("10.00"),
        invoice.getBalanceAsDecimal());
    assertEquals(
        "New invoice holds the carried balance equal to the old invoice balance",
        overdue.getBalanceAsDecimal(),
        invoice.getCarriedBalanceAsDecimal());
    assertEquals(
        "New invoice total is equal to the current charges plus the carried total",
        new BigDecimal("30.00"),
        invoice.getTotalAsDecimal());
  }
Exemple #13
0
  public void testCreateInvoice() {
    try {
      final Integer USER_ID = 10730; // user has no orders
      JbillingAPI api = JbillingAPIFactory.getAPI();

      // setup order
      OrderWS order = new OrderWS();
      order.setUserId(USER_ID);
      order.setBillingTypeId(Constants.ORDER_BILLING_PRE_PAID);
      order.setPeriod(1); // once
      order.setCurrencyId(1);
      order.setActiveSince(new Date());

      OrderLineWS line = new OrderLineWS();
      line.setTypeId(Constants.ORDER_LINE_TYPE_ITEM);
      line.setDescription("Order line");
      line.setItemId(1);
      line.setQuantity(1);
      line.setPrice(new BigDecimal("10.00"));
      line.setAmount(new BigDecimal("10.00"));

      order.setOrderLines(new OrderLineWS[] {line});

      /*
       * Test invoicing of one-time and recurring orders
       */

      // create 1st order
      Integer orderId1 = api.createOrder(order);

      // create 2nd order
      line.setPrice(new BigDecimal("20.00"));
      line.setAmount(new BigDecimal("20.00"));
      Integer orderId2 = api.createOrder(order);

      // create invoice
      Integer[] invoices = api.createInvoice(USER_ID, false);

      assertEquals("Number of invoices returned", 1, invoices.length);
      InvoiceWS invoice = api.getInvoiceWS(invoices[0]);

      assertNull("Invoice is not delegated.", invoice.getDelegatedInvoiceId());
      assertEquals(
          "Invoice does not have a carried balance.",
          BigDecimal.ZERO,
          invoice.getCarriedBalanceAsDecimal());

      Integer[] invoicedOrderIds = invoice.getOrders();
      assertEquals("Number of orders invoiced", 2, invoicedOrderIds.length);
      Arrays.sort(invoicedOrderIds);
      assertEquals("Order 1 invoiced", orderId1, invoicedOrderIds[0]);
      assertEquals("Order 2 invoiced", orderId2, invoicedOrderIds[1]);
      assertEquals("Total is 30.0", new BigDecimal("30.00"), invoice.getTotalAsDecimal());

      // clean up
      api.deleteInvoice(invoices[0]);
      api.deleteOrder(orderId1);
      api.deleteOrder(orderId2);

      /*
       * Test only recurring order can generate invoice.
       */

      // one-time order
      line.setPrice(new BigDecimal("2.00"));
      line.setAmount(new BigDecimal("2.00"));
      orderId1 = api.createOrder(order);

      // try to create invoice, but none should be returned
      invoices = api.createInvoice(USER_ID, true);

      // Note: CXF returns null for empty array
      if (invoices != null) {
        assertEquals("Number of invoices returned", 0, invoices.length);
      }

      // recurring order
      order.setPeriod(2); // monthly
      line.setPrice(new BigDecimal("3.00"));
      line.setAmount(new BigDecimal("3.00"));
      orderId2 = api.createOrder(order);

      // create invoice
      invoices = api.createInvoice(USER_ID, true);

      assertEquals("Number of invoices returned", 1, invoices.length);
      invoice = api.getInvoiceWS(invoices[0]);
      invoicedOrderIds = invoice.getOrders();
      assertEquals("Number of orders invoiced", 2, invoicedOrderIds.length);
      Arrays.sort(invoicedOrderIds);
      assertEquals("Order 1 invoiced", orderId1, invoicedOrderIds[0]);
      assertEquals("Order 2 invoiced", orderId2, invoicedOrderIds[1]);
      assertEquals("Total is 5.0", new BigDecimal("5.00"), invoice.getTotalAsDecimal());

      // clean up
      api.deleteInvoice(invoices[0]);
      api.deleteOrder(orderId1);
      api.deleteOrder(orderId2);

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    }
  }
  public static UserWS createUser(
      boolean goodCC, Integer parentId, Integer currencyId, boolean doCreate)
      throws JbillingAPIException, IOException {
    JbillingAPI api = JbillingAPIFactory.getAPI();

    /*
     * Create - This passes the password validation routine.
     */
    UserWS newUser = new UserWS();
    newUser.setUserId(0); // it is validated
    newUser.setUserName("testUserName-" + Calendar.getInstance().getTimeInMillis());
    newUser.setPassword("As$fasdf1");
    newUser.setLanguageId(Integer.valueOf(1));
    newUser.setMainRoleId(Integer.valueOf(5));
    newUser.setAccountTypeId(Integer.valueOf(1));
    newUser.setParentId(parentId); // this parent exists
    newUser.setStatusId(UserDTOEx.STATUS_ACTIVE);
    newUser.setCurrencyId(currencyId);
    newUser.setCreditLimit("1");
    newUser.setInvoiceChild(new Boolean(false));

    MetaFieldValueWS metaField1 = new MetaFieldValueWS();
    metaField1.setFieldName("partner.prompt.fee");
    metaField1.setValue("serial-from-ws");

    MetaFieldValueWS metaField2 = new MetaFieldValueWS();
    metaField2.setFieldName("ccf.payment_processor");
    metaField2.setValue("FAKE_2"); // the plug-in parameter of the processor

    MetaFieldValueWS metaField3 = new MetaFieldValueWS();
    metaField3.setFieldName("contact.email");
    metaField3.setValue(newUser.getUserName() + "@shire.com");
    metaField3.setGroupId(1);

    MetaFieldValueWS metaField4 = new MetaFieldValueWS();
    metaField4.setFieldName("contact.first.name");
    metaField4.setValue("FrodoRecharge");
    metaField4.setGroupId(1);

    MetaFieldValueWS metaField5 = new MetaFieldValueWS();
    metaField5.setFieldName("contact.last.name");
    metaField5.setValue("BagginsRecharge");
    metaField5.setGroupId(1);

    newUser.setMetaFields(
        new MetaFieldValueWS[] {metaField1, metaField2, metaField3, metaField4, metaField5});

    // valid credit card must have a future expiry date to be valid for payment processing
    Calendar expiry = Calendar.getInstance();
    expiry.set(Calendar.YEAR, expiry.get(Calendar.YEAR) + 1);

    // add a credit card
    PaymentInformationWS cc =
        createCreditCard(
            "Frodo Rech Baggins",
            goodCC ? "4929974024420784" : "4111111111111111",
            expiry.getTime());

    newUser.getPaymentInstruments().add(cc);

    if (doCreate) {
      System.out.println("Creating user ...");
      Integer userId = api.createUser(newUser);
      newUser = api.getUserWS(userId);
    }

    return newUser;
  }
  @Test
  public void test001CreateCustomerWithAitMetaFields_DefaultDate() throws Exception {
    System.out.println("#test001CreateCustomerWithAitMetaFields_DefaultDate");
    JbillingAPI api = JbillingAPIFactory.getAPI();
    Integer userId = null;
    try {
      UserWS newUser = createUser();

      System.out.println("Setting Ait fields values for date:" + CommonConstants.EPOCH_DATE);
      MetaFieldValueWS metaField1 = new MetaFieldValueWS();
      metaField1.setFieldName("partner.prompt.fee");
      metaField1.setValue("serial-from-ws");

      MetaFieldValueWS metaField2 = new MetaFieldValueWS();
      metaField2.setFieldName("ccf.payment_processor");
      metaField2.setValue("FAKE_2"); // the plug-in parameter of the processor

      String email = newUser.getUserName() + "@shire.com";
      String firstName = "Frodo";
      String lastName = "Baggins";

      MetaFieldValueWS metaField3 = new MetaFieldValueWS();
      metaField3.setFieldName("contact.email");
      metaField3.setValue(email);
      metaField3.setGroupId(1);

      MetaFieldValueWS metaField4 = new MetaFieldValueWS();
      metaField4.setFieldName("contact.first.name");
      metaField4.setValue(firstName);
      metaField4.setGroupId(1);

      MetaFieldValueWS metaField5 = new MetaFieldValueWS();
      metaField5.setFieldName("contact.last.name");
      metaField5.setValue(lastName);
      metaField5.setGroupId(1);

      newUser.setMetaFields(
          new MetaFieldValueWS[] {metaField1, metaField2, metaField3, metaField4, metaField5});

      System.out.println("Setting default date as the only date of timeline");
      ArrayList<Date> timelineDates = new ArrayList<Date>(0);
      timelineDates.add(CommonConstants.EPOCH_DATE);
      newUser.getTimelineDatesMap().put(new Integer(1), timelineDates);

      System.out.println("Creating user ...");
      userId = api.createUser(newUser);
      newUser.setUserId(userId);

      System.out.println("Getting created user");
      UserWS ret = api.getUserWS(newUser.getUserId());

      ArrayList<MetaFieldValueWS> aitMetaFields =
          ret.getAccountInfoTypeFieldsMap().get(new Integer(1)).get(CommonConstants.EPOCH_DATE);

      // check that timeline contains default date
      if (!ret.getAccountInfoTypeFieldsMap()
          .get(new Integer(1))
          .containsKey(CommonConstants.EPOCH_DATE)) {
        fail("Default date: " + CommonConstants.EPOCH_DATE + " should be present in timeline");
      }

      // Total no of ait meta fields returned should be 18, no of meta fields for ait = 1, only 3
      // has values
      assertEquals(3, aitMetaFields.size());

      // ait meta fields should be 11. Customer Specific: 8 (2 has value). Ait meta field for
      // effective date: 18 (3 has values)
      assertEquals(5, ret.getMetaFields().length);

      // assert that email, first name and last name has same values
      for (MetaFieldValueWS ws : aitMetaFields) {
        if (ws.getFieldName().equals("contact.email")) {
          assertEquals("Email should be same", email, ws.getValue());
        } else if (ws.getFieldName().equals("contact.first.name")) {
          assertEquals("First name should be same", firstName, ws.getValue());
        } else if (ws.getFieldName().equals("contact.last.name")) {
          assertEquals("Last name should be same", lastName, ws.getValue());
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    } finally {
      System.out.println("Deleting created user");
      if (userId != null) api.deleteUser(userId);
    }
  }
  @Test
  public void test003CreateCustomerWithAitMetaFields_UpdateTodaysFields() throws Exception {
    System.out.println("#test003CreateCustomerWithAitMetaFields_UpdateTodaysFields");
    JbillingAPI api = JbillingAPIFactory.getAPI();
    Integer userId = null;
    try {

      UserWS newUser = createUser();
      System.out.println("Setting Ait fields values for date:" + CommonConstants.EPOCH_DATE);
      MetaFieldValueWS metaField1 = new MetaFieldValueWS();
      metaField1.setFieldName("partner.prompt.fee");
      metaField1.setValue("serial-from-ws");

      MetaFieldValueWS metaField2 = new MetaFieldValueWS();
      metaField2.setFieldName("ccf.payment_processor");
      metaField2.setValue("FAKE_2"); // the plug-in parameter of the processor

      MetaFieldValueWS metaField3 = new MetaFieldValueWS();
      metaField3.setFieldName("contact.email");
      metaField3.setValue("*****@*****.**");
      metaField3.setGroupId(1);

      newUser.setMetaFields(new MetaFieldValueWS[] {metaField1, metaField2, metaField3});

      Date today = new DateTime().toDateMidnight().toDate();
      System.out.println("Setting default date and todays date on timeline");
      ArrayList<Date> timelineDates = new ArrayList<Date>(0);
      timelineDates.add(CommonConstants.EPOCH_DATE);
      timelineDates.add(today);
      newUser.getTimelineDatesMap().put(new Integer(1), timelineDates);

      System.out.println("Creating user ...");
      userId = api.createUser(newUser);
      newUser.setUserId(userId);

      System.out.println("Getting created user");
      UserWS ret = api.getUserWS(newUser.getUserId());

      // Update todays ait meta field value for the created users
      metaField3 = new MetaFieldValueWS();
      metaField3.setFieldName("contact.email");
      metaField3.setValue("*****@*****.**");
      metaField3.setGroupId(1);

      ret.setMetaFields(new MetaFieldValueWS[] {metaField1, metaField2, metaField3});

      ret.getEffectiveDateMap().put(1, today);
      api.updateUser(ret);

      // get updated user
      ret = api.getUserWS(newUser.getUserId());

      // check that timeline contains default date and today's date
      if (!ret.getAccountInfoTypeFieldsMap()
          .get(new Integer(1))
          .containsKey(CommonConstants.EPOCH_DATE)) {
        fail("Default date: " + CommonConstants.EPOCH_DATE + " should be present in timeline");
      }

      if (!ret.getAccountInfoTypeFieldsMap().get(new Integer(1)).containsKey(today)) {
        fail("Default date: " + today + " should be present in timeline");
      }

      // verify meta fields for default date
      ArrayList<MetaFieldValueWS> aitMetaFields =
          ret.getAccountInfoTypeFieldsMap().get(new Integer(1)).get(CommonConstants.EPOCH_DATE);

      // Total no of ait meta fields returned should be 1, no of meta fields for ait 1 is 18, but
      // only
      // one has a value
      assertEquals(1, aitMetaFields.size());

      // assert that email, first name and last name has same values
      for (MetaFieldValueWS ws : aitMetaFields) {
        if (ws.getFieldName().equals("contact.email")) {
          assertEquals("Email should be same", "*****@*****.**", ws.getValue());
        }
      }

      // verify meta fields for todays date
      aitMetaFields = ret.getAccountInfoTypeFieldsMap().get(new Integer(1)).get(today);

      // Total no of ait meta fields returned should be 1, no of meta fields for ait 1 is 18, but
      // only
      // one has a value
      assertEquals(1, aitMetaFields.size());

      // assert that email, first name and last name has same values
      for (MetaFieldValueWS ws : aitMetaFields) {
        if (ws.getFieldName().equals("contact.email")) {
          assertEquals("Email should be same", "*****@*****.**", ws.getValue());
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
      fail("Exception caught:" + e);
    } finally {
      // Change
      System.out.println("Deleting created user");
      if (userId != null) api.deleteUser(userId);
    }
  }