Example usage for org.joda.time DateTimeZone forID

List of usage examples for org.joda.time DateTimeZone forID

Introduction

In this page you can find the example usage for org.joda.time DateTimeZone forID.

Prototype

@FromString
public static DateTimeZone forID(String id) 

Source Link

Document

Gets a time zone instance for the specified time zone id.

Usage

From source file:org.killbill.billing.plugin.analytics.AnalyticsTestSuiteNoDB.java

License:Apache License

@BeforeMethod(groups = "fast")
public void setUp() throws Exception {
    logService = Mockito.mock(OSGIKillbillLogService.class);
    Mockito.doAnswer(new Answer() {
        @Override//from ww  w.jav  a 2s  .c o m
        public Object answer(final InvocationOnMock invocation) throws Throwable {
            //logger.info(Arrays.toString(invocation.getArguments()));
            return null;
        }
    }).when(logService).log(Mockito.anyInt(), Mockito.anyString());

    Mockito.when(currencyConverter.getConvertedCurrency()).thenReturn("USD");
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<BigDecimal>any(), Mockito.anyString(),
            Mockito.<LocalDate>any())).thenReturn(BigDecimal.TEN);
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<BigDecimal>any(), Mockito.<Account>any()))
            .thenReturn(BigDecimal.TEN);
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<Invoice>any())).thenReturn(BigDecimal.TEN);
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<BigDecimal>any(), Mockito.<Invoice>any()))
            .thenReturn(BigDecimal.TEN);
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<InvoiceItem>any(), Mockito.<Invoice>any()))
            .thenReturn(BigDecimal.TEN);
    Mockito.when(currencyConverter.getConvertedValue(Mockito.<InvoicePayment>any(),
            Mockito.<PaymentTransaction>any(), Mockito.<Invoice>any())).thenReturn(BigDecimal.TEN);

    account = Mockito.mock(Account.class);
    Mockito.when(account.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(account.getExternalKey()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getFirstNameLength()).thenReturn(4);
    Mockito.when(account.getEmail()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getBillCycleDayLocal()).thenReturn(2);
    Mockito.when(account.getCurrency()).thenReturn(Currency.BRL);
    Mockito.when(account.getPaymentMethodId()).thenReturn(UUID.randomUUID());
    Mockito.when(account.getTimeZone()).thenReturn(DateTimeZone.forID("Europe/London"));
    Mockito.when(account.getLocale()).thenReturn(UUID.randomUUID().toString().substring(0, 5));
    Mockito.when(account.getAddress1()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getAddress2()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getCompanyName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getCity()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getStateOrProvince()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getPostalCode()).thenReturn(UUID.randomUUID().toString().substring(0, 16));
    Mockito.when(account.getCountry()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(account.getPhone()).thenReturn(UUID.randomUUID().toString().substring(0, 25));
    Mockito.when(account.isMigrated()).thenReturn(true);
    Mockito.when(account.isNotifiedForInvoices()).thenReturn(true);
    Mockito.when(account.getCreatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 47, DateTimeZone.UTC));
    Mockito.when(account.getUpdatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 48, DateTimeZone.UTC));
    final UUID accountId = account.getId();

    bundle = Mockito.mock(SubscriptionBundle.class);
    Mockito.when(bundle.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(bundle.getAccountId()).thenReturn(accountId);
    Mockito.when(bundle.getExternalKey()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(bundle.getCreatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 48, DateTimeZone.UTC));
    final UUID bundleId = bundle.getId();

    final Product product = Mockito.mock(Product.class);
    Mockito.when(product.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(product.getCategory()).thenReturn(ProductCategory.STANDALONE);
    Mockito.when(product.getCatalogName()).thenReturn(UUID.randomUUID().toString());

    plan = Mockito.mock(Plan.class);
    Mockito.when(plan.getProduct()).thenReturn(product);
    Mockito.when(plan.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(plan.getRecurringBillingPeriod()).thenReturn(BillingPeriod.QUARTERLY);
    Mockito.when(plan.getEffectiveDateForExistingSubscriptons())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 59, DateTimeZone.UTC).toDate());
    final String planName = plan.getName();

    phase = Mockito.mock(PlanPhase.class);
    Recurring recurring = Mockito.mock(Recurring.class);
    Mockito.when(recurring.getBillingPeriod()).thenReturn(BillingPeriod.QUARTERLY);
    Mockito.when(phase.getRecurring()).thenReturn(recurring);
    Mockito.when(phase.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(phase.getPhaseType()).thenReturn(PhaseType.DISCOUNT);

    final InternationalPrice internationalPrice = Mockito.mock(InternationalPrice.class);
    Mockito.when(recurring.getRecurringPrice()).thenReturn(internationalPrice);
    Mockito.when(internationalPrice.getPrice(Mockito.<Currency>any())).thenReturn(BigDecimal.TEN);
    final String phaseName = phase.getName();

    priceList = Mockito.mock(PriceList.class);
    Mockito.when(priceList.getName()).thenReturn(UUID.randomUUID().toString());

    subscriptionTransition = Mockito.mock(SubscriptionEvent.class);
    Mockito.when(subscriptionTransition.getEntitlementId()).thenReturn(UUID.randomUUID());
    Mockito.when(subscriptionTransition.getServiceName()).thenReturn(serviceName);
    Mockito.when(subscriptionTransition.getServiceStateName()).thenReturn(stateName);
    Mockito.when(subscriptionTransition.getNextPlan()).thenReturn(plan);
    Mockito.when(subscriptionTransition.getNextPhase()).thenReturn(phase);
    Mockito.when(subscriptionTransition.getNextPriceList()).thenReturn(priceList);
    Mockito.when(subscriptionTransition.getRequestedDate()).thenReturn(new LocalDate(2010, 1, 2));
    Mockito.when(subscriptionTransition.getEffectiveDate()).thenReturn(new LocalDate(2011, 2, 3));
    Mockito.when(subscriptionTransition.getSubscriptionEventType())
            .thenReturn(SubscriptionEventType.START_ENTITLEMENT);
    Mockito.when(subscriptionTransition.getId()).thenReturn(UUID.randomUUID());
    final UUID subscriptionId = subscriptionTransition.getEntitlementId();
    final UUID nextEventId = subscriptionTransition.getId();

    invoiceItem = Mockito.mock(InvoiceItem.class);
    Mockito.when(invoiceItem.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoiceItem.getInvoiceItemType()).thenReturn(InvoiceItemType.EXTERNAL_CHARGE);
    Mockito.when(invoiceItem.getInvoiceId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoiceItem.getAccountId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoiceItem.getStartDate()).thenReturn(new LocalDate(1999, 9, 9));
    Mockito.when(invoiceItem.getEndDate()).thenReturn(new LocalDate(2048, 1, 1));
    Mockito.when(invoiceItem.getAmount()).thenReturn(new BigDecimal("12000"));
    Mockito.when(invoiceItem.getCurrency()).thenReturn(Currency.EUR);
    Mockito.when(invoiceItem.getDescription()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(invoiceItem.getBundleId()).thenReturn(bundleId);
    Mockito.when(invoiceItem.getSubscriptionId()).thenReturn(subscriptionId);
    Mockito.when(invoiceItem.getPlanName()).thenReturn(planName);
    Mockito.when(invoiceItem.getPhaseName()).thenReturn(phaseName);
    Mockito.when(invoiceItem.getRate()).thenReturn(new BigDecimal("1203"));
    Mockito.when(invoiceItem.getLinkedItemId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoiceItem.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 51, DateTimeZone.UTC));
    final UUID invoiceItemId = invoiceItem.getId();

    final UUID invoiceId = UUID.randomUUID();

    invoicePayment = Mockito.mock(InvoicePayment.class);
    Mockito.when(invoicePayment.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoicePayment.getPaymentId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoicePayment.getType()).thenReturn(InvoicePaymentType.ATTEMPT);
    Mockito.when(invoicePayment.getInvoiceId()).thenReturn(invoiceId);
    Mockito.when(invoicePayment.getPaymentDate())
            .thenReturn(new DateTime(2003, 4, 12, 3, 34, 52, DateTimeZone.UTC));
    Mockito.when(invoicePayment.getAmount()).thenReturn(BigDecimal.ONE);
    Mockito.when(invoicePayment.getCurrency()).thenReturn(Currency.MXN);
    Mockito.when(invoicePayment.getLinkedInvoicePaymentId()).thenReturn(UUID.randomUUID());
    Mockito.when(invoicePayment.getPaymentCookieId()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(invoicePayment.getCreatedDate()).thenReturn(INVOICE_CREATED_DATE);
    final UUID invoicePaymentId = invoicePayment.getId();

    invoice = Mockito.mock(Invoice.class);
    Mockito.when(invoice.getId()).thenReturn(invoiceId);
    Mockito.when(invoice.getInvoiceItems()).thenReturn(ImmutableList.<InvoiceItem>of(invoiceItem));
    Mockito.when(invoice.getNumberOfItems()).thenReturn(1);
    Mockito.when(invoice.getPayments()).thenReturn(ImmutableList.<InvoicePayment>of(invoicePayment));
    Mockito.when(invoice.getNumberOfPayments()).thenReturn(1);
    Mockito.when(invoice.getAccountId()).thenReturn(accountId);
    Mockito.when(invoice.getInvoiceNumber()).thenReturn(42);
    Mockito.when(invoice.getInvoiceDate()).thenReturn(new LocalDate(1954, 12, 1));
    Mockito.when(invoice.getTargetDate()).thenReturn(new LocalDate(2017, 3, 4));
    Mockito.when(invoice.getCurrency()).thenReturn(Currency.AUD);
    Mockito.when(invoice.getPaidAmount()).thenReturn(BigDecimal.ZERO);
    Mockito.when(invoice.getOriginalChargedAmount()).thenReturn(new BigDecimal("1922"));
    Mockito.when(invoice.getChargedAmount()).thenReturn(new BigDecimal("100293"));
    Mockito.when(invoice.getCreditedAmount()).thenReturn(new BigDecimal("283"));
    Mockito.when(invoice.getRefundedAmount()).thenReturn(new BigDecimal("384"));
    Mockito.when(invoice.getBalance()).thenReturn(new BigDecimal("18376"));
    Mockito.when(invoice.isMigrationInvoice()).thenReturn(false);
    Mockito.when(invoice.getCreatedDate()).thenReturn(INVOICE_CREATED_DATE);

    final PaymentMethodPlugin paymentMethodPlugin = Mockito.mock(PaymentMethodPlugin.class);
    Mockito.when(paymentMethodPlugin.getExternalPaymentMethodId()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(paymentMethodPlugin.isDefaultPaymentMethod()).thenReturn(true);

    paymentMethod = Mockito.mock(PaymentMethod.class);
    Mockito.when(paymentMethod.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(paymentMethod.getAccountId()).thenReturn(accountId);
    Mockito.when(paymentMethod.isActive()).thenReturn(true);
    Mockito.when(paymentMethod.getPluginName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(paymentMethod.getPluginDetail()).thenReturn(paymentMethodPlugin);
    Mockito.when(paymentMethod.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 55, DateTimeZone.UTC));
    final UUID paymentMethodId = paymentMethod.getId();

    paymentTransaction = Mockito.mock(PaymentTransaction.class);
    Mockito.when(paymentTransaction.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(paymentTransaction.getTransactionType()).thenReturn(TransactionType.CAPTURE);
    Mockito.when(paymentTransaction.getAmount()).thenReturn(new BigDecimal("199999"));
    Mockito.when(paymentTransaction.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(paymentTransaction.getEffectiveDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 56, DateTimeZone.UTC));
    Mockito.when(paymentTransaction.getExternalKey()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(paymentTransaction.getTransactionStatus()).thenReturn(TransactionStatus.SUCCESS);

    purchaseTransaction = Mockito.mock(PaymentTransaction.class);
    Mockito.when(purchaseTransaction.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(purchaseTransaction.getTransactionType()).thenReturn(TransactionType.PURCHASE);
    Mockito.when(purchaseTransaction.getAmount()).thenReturn(new BigDecimal("199999"));
    Mockito.when(purchaseTransaction.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(purchaseTransaction.getEffectiveDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 56, DateTimeZone.UTC));
    Mockito.when(purchaseTransaction.getExternalKey()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(purchaseTransaction.getTransactionStatus()).thenReturn(TransactionStatus.SUCCESS);

    refundTransaction = Mockito.mock(PaymentTransaction.class);
    Mockito.when(refundTransaction.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(refundTransaction.getTransactionType()).thenReturn(TransactionType.REFUND);
    Mockito.when(refundTransaction.getAmount()).thenReturn(new BigDecimal("199998"));
    Mockito.when(refundTransaction.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(refundTransaction.getEffectiveDate())
            .thenReturn(new DateTime(2016, 1, 23, 10, 56, 56, DateTimeZone.UTC));
    Mockito.when(refundTransaction.getExternalKey()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(refundTransaction.getTransactionStatus()).thenReturn(TransactionStatus.PENDING);

    payment = Mockito.mock(Payment.class);
    Mockito.when(payment.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(payment.getAccountId()).thenReturn(accountId);
    Mockito.when(payment.getPaymentMethodId()).thenReturn(paymentMethodId);
    Mockito.when(payment.getPaymentNumber()).thenReturn(1);
    Mockito.when(payment.getCapturedAmount()).thenReturn(new BigDecimal("199999"));
    Mockito.when(payment.getRefundedAmount()).thenReturn(new BigDecimal("199998"));
    Mockito.when(payment.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(payment.getTransactions())
            .thenReturn(ImmutableList.<PaymentTransaction>of(paymentTransaction, refundTransaction));
    Mockito.when(payment.getCreatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 56, DateTimeZone.UTC));

    paymentNoRefund = Mockito.mock(Payment.class);
    Mockito.when(paymentNoRefund.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(paymentNoRefund.getAccountId()).thenReturn(accountId);
    Mockito.when(paymentNoRefund.getPaymentMethodId()).thenReturn(paymentMethodId);
    Mockito.when(paymentNoRefund.getPaymentNumber()).thenReturn(1);
    Mockito.when(paymentNoRefund.getCapturedAmount()).thenReturn(new BigDecimal("199999"));
    Mockito.when(paymentNoRefund.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(paymentNoRefund.getTransactions())
            .thenReturn(ImmutableList.<PaymentTransaction>of(paymentTransaction));
    Mockito.when(paymentNoRefund.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 56, DateTimeZone.UTC));

    customField = Mockito.mock(CustomField.class);
    Mockito.when(customField.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(customField.getObjectId()).thenReturn(UUID.randomUUID());
    Mockito.when(customField.getObjectType()).thenReturn(ObjectType.ACCOUNT);
    Mockito.when(customField.getFieldName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(customField.getFieldValue()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(customField.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 57, DateTimeZone.UTC));
    final UUID fieldId = customField.getId();

    tag = Mockito.mock(Tag.class);
    Mockito.when(tag.getObjectId()).thenReturn(UUID.randomUUID());
    Mockito.when(tag.getObjectType()).thenReturn(ObjectType.ACCOUNT);
    Mockito.when(tag.getTagDefinitionId()).thenReturn(UUID.randomUUID());
    Mockito.when(tag.getCreatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 58, DateTimeZone.UTC));
    final UUID tagId = tag.getId();

    tagDefinition = Mockito.mock(TagDefinition.class);
    Mockito.when(tagDefinition.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(tagDefinition.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(tagDefinition.getDescription()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(tagDefinition.isControlTag()).thenReturn(false);
    Mockito.when(tagDefinition.getApplicableObjectTypes())
            .thenReturn(ImmutableList.<ObjectType>of(ObjectType.INVOICE));
    Mockito.when(tagDefinition.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 59, DateTimeZone.UTC));

    auditLog = Mockito.mock(AuditLog.class);
    Mockito.when(auditLog.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(auditLog.getChangeType()).thenReturn(ChangeType.INSERT);
    Mockito.when(auditLog.getUserName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(auditLog.getCreatedDate())
            .thenReturn(new DateTime(2012, 12, 31, 23, 59, 59, DateTimeZone.UTC));
    Mockito.when(auditLog.getReasonCode()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(auditLog.getUserToken()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(auditLog.getComment()).thenReturn(UUID.randomUUID().toString());

    accountAuditLogs = Mockito.mock(AccountAuditLogs.class);
    Mockito.when(accountAuditLogs.getAuditLogsForAccount()).thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForBundle(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForSubscription(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForSubscriptionEvent(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForBlockingState(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForInvoice(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForInvoiceItem(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForInvoicePayment(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForPayment(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForTag(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogsForCustomField(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    final AccountAuditLogsForObjectType accountAuditLogsForObjectType = Mockito
            .mock(AccountAuditLogsForObjectType.class);
    Mockito.when(accountAuditLogsForObjectType.getAuditLogs(Mockito.<UUID>any()))
            .thenReturn(ImmutableList.<AuditLog>of(auditLog));
    Mockito.when(accountAuditLogs.getAuditLogs(Mockito.<ObjectType>any()))
            .thenReturn(accountAuditLogsForObjectType);

    // Real class for the binding to work with JDBI
    callContext = new TestCallContext();
    final UUID tenantId = callContext.getTenantId();

    final RecordIdApi recordIdApi = Mockito.mock(RecordIdApi.class);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(accountId), Mockito.eq(ObjectType.ACCOUNT),
            Mockito.<TenantContext>any())).thenReturn(accountRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(nextEventId), Mockito.eq(ObjectType.SUBSCRIPTION_EVENT),
            Mockito.<TenantContext>any())).thenReturn(subscriptionEventRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(invoiceId), Mockito.eq(ObjectType.INVOICE),
            Mockito.<TenantContext>any())).thenReturn(invoiceRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(invoiceItemId), Mockito.eq(ObjectType.INVOICE_ITEM),
            Mockito.<TenantContext>any())).thenReturn(invoiceItemRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(invoicePaymentId), Mockito.eq(ObjectType.INVOICE_PAYMENT),
            Mockito.<TenantContext>any())).thenReturn(invoicePaymentRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(fieldId), Mockito.eq(ObjectType.CUSTOM_FIELD),
            Mockito.<TenantContext>any())).thenReturn(fieldRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(tagId), Mockito.eq(ObjectType.TAG),
            Mockito.<TenantContext>any())).thenReturn(tagRecordId);
    Mockito.when(recordIdApi.getRecordId(Mockito.eq(tenantId), Mockito.eq(ObjectType.TENANT),
            Mockito.<TenantContext>any())).thenReturn(tenantRecordId);

    killbillAPI = Mockito.mock(OSGIKillbillAPI.class);
    final AccountUserApi accountUserApi = Mockito.mock(AccountUserApi.class);
    Mockito.when(accountUserApi.getAccountById(Mockito.<UUID>any(), Mockito.<TenantContext>any()))
            .thenReturn(account);
    final TagUserApi tagUserApi = Mockito.mock(TagUserApi.class);

    final CustomFieldUserApi customFieldUserApi = Mockito.mock(CustomFieldUserApi.class);
    Mockito.when(
            customFieldUserApi.getCustomFieldsForAccount(Mockito.<UUID>any(), Mockito.<TenantContext>any()))
            .thenReturn(ImmutableList.<CustomField>of(customField));

    final AuditUserApi auditUserApi = Mockito.mock(AuditUserApi.class);
    Mockito.when(auditUserApi.getAccountAuditLogs(Mockito.<UUID>any(), Mockito.<AuditLevel>any(),
            Mockito.<TenantContext>any())).thenReturn(accountAuditLogs);
    Mockito.when(auditUserApi.getAccountAuditLogs(Mockito.<UUID>any(), Mockito.<ObjectType>any(),
            Mockito.<AuditLevel>any(), Mockito.<TenantContext>any())).thenReturn(accountAuditLogsForObjectType);
    Mockito.when(auditUserApi.getAuditLogs(Mockito.<UUID>any(), Mockito.<ObjectType>any(),
            Mockito.<AuditLevel>any(), Mockito.<TenantContext>any())).thenReturn(ImmutableList.<AuditLog>of());

    final SubscriptionApi subscriptionApi = Mockito.mock(SubscriptionApi.class);
    Mockito.when(subscriptionApi.getSubscriptionBundlesForAccountId(Mockito.<UUID>any(),
            Mockito.<TenantContext>any())).thenReturn(ImmutableList.<SubscriptionBundle>of());

    Mockito.when(tagUserApi.getTagsForObject(Mockito.<UUID>any(), Mockito.<ObjectType>any(),
            Mockito.anyBoolean(), Mockito.<TenantContext>any())).thenReturn(ImmutableList.<Tag>of());
    Mockito.when(killbillAPI.getAccountUserApi()).thenReturn(accountUserApi);
    Mockito.when(killbillAPI.getSubscriptionApi()).thenReturn(subscriptionApi);
    Mockito.when(killbillAPI.getRecordIdApi()).thenReturn(recordIdApi);
    Mockito.when(killbillAPI.getTagUserApi()).thenReturn(tagUserApi);
    Mockito.when(killbillAPI.getCustomFieldUserApi()).thenReturn(customFieldUserApi);
    Mockito.when(killbillAPI.getAuditUserApi()).thenReturn(auditUserApi);

    killbillDataSource = Mockito.mock(OSGIKillbillDataSource.class);
    final DataSource dataSource = Mockito.mock(DataSource.class);
    Mockito.when(killbillDataSource.getDataSource()).thenReturn(dataSource);

    final Properties properties = System.getProperties();
    properties.setProperty(AnalyticsListener.ANALYTICS_ACCOUNTS_BLACKLIST_PROPERTY,
            String.format("%s,%s", UUID.randomUUID(), blackListedAccountId));
    properties.setProperty("org.killbill.notificationq.analytics.tableName", "analytics_notifications");
    properties.setProperty("org.killbill.notificationq.analytics.historyTableName",
            "analytics_notifications_history");

    osgiConfigPropertiesService = Mockito.mock(OSGIConfigPropertiesService.class);
    Mockito.when(osgiConfigPropertiesService.getProperties()).thenReturn(properties);
    Mockito.when(osgiConfigPropertiesService.getString(Mockito.<String>any())).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return properties.getProperty((String) invocation.getArguments()[0]);
        }
    });
}

From source file:org.killbill.billing.subscription.DefaultSubscriptionTestInitializer.java

License:Apache License

public AccountData initAccountData() {
    final AccountData accountData = new MockAccountBuilder().name(UUIDs.randomUUID().toString().substring(1, 8))
            .firstNameLength(6).email(UUIDs.randomUUID().toString().substring(1, 8))
            .phone(UUIDs.randomUUID().toString().substring(1, 8)).migrated(false).isNotifiedForInvoices(false)
            .externalKey(UUIDs.randomUUID().toString()).billingCycleDayLocal(1).currency(Currency.USD)
            .paymentMethodId(UUIDs.randomUUID()).timeZone(DateTimeZone.forID("Europe/Paris")).build();

    assertNotNull(accountData);/*  w w  w  .  j  av a2  s . c  o  m*/
    return accountData;
}

From source file:org.killbill.commons.jdbi.mapper.LowerToCamelBeanMapper.java

License:Apache License

public T map(final int row, final ResultSet rs, final StatementContext ctx) throws SQLException {
    final T bean;
    try {/*from  w w w.  j a  v a 2 s.  c  o  m*/
        bean = type.newInstance();
    } catch (final Exception e) {
        throw new IllegalArgumentException(
                String.format("A bean, %s, was mapped " + "which was not instantiable", type.getName()), e);
    }

    final Class beanClass = bean.getClass();
    final ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 1; i <= metadata.getColumnCount(); ++i) {
        final String name = metadata.getColumnLabel(i).toLowerCase();

        final PropertyDescriptor descriptor = properties.get(name);

        if (descriptor != null) {
            final Class<?> type = descriptor.getPropertyType();

            Object value;

            if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
                value = rs.getBoolean(i);
            } else if (type.isAssignableFrom(Byte.class) || type.isAssignableFrom(byte.class)) {
                value = rs.getByte(i);
            } else if (type.isAssignableFrom(Short.class) || type.isAssignableFrom(short.class)) {
                value = rs.getShort(i);
            } else if (type.isAssignableFrom(Integer.class) || type.isAssignableFrom(int.class)) {
                value = rs.getInt(i);
            } else if (type.isAssignableFrom(Long.class) || type.isAssignableFrom(long.class)) {
                value = rs.getLong(i);
            } else if (type.isAssignableFrom(Float.class) || type.isAssignableFrom(float.class)) {
                value = rs.getFloat(i);
            } else if (type.isAssignableFrom(Double.class) || type.isAssignableFrom(double.class)) {
                value = rs.getDouble(i);
            } else if (type.isAssignableFrom(BigDecimal.class)) {
                value = rs.getBigDecimal(i);
            } else if (type.isAssignableFrom(DateTime.class)) {
                final Timestamp timestamp = rs.getTimestamp(i);
                value = timestamp == null ? null : new DateTime(timestamp).toDateTime(DateTimeZone.UTC);
            } else if (type.isAssignableFrom(Time.class)) {
                value = rs.getTime(i);
            } else if (type.isAssignableFrom(LocalDate.class)) {
                //
                // We store the LocalDate into a mysql 'date' as a string
                // (See https://github.com/killbill/killbill-commons/blob/master/jdbi/src/main/java/org/killbill/commons/jdbi/argument/LocalDateArgumentFactory.java)
                // So we also read it as a String which avoids any kind of transformation
                //
                // Note that we used previously the getDate(index, Calendar) method, but this is not thread safe as we discovered
                // unless maybe -- untested --we pass a new instance of a Calendar each time
                //
                final String dateString = rs.getString(i);
                value = dateString == null ? null : new LocalDate(dateString, DateTimeZone.UTC);
            } else if (type.isAssignableFrom(DateTimeZone.class)) {
                final String dateTimeZoneString = rs.getString(i);
                value = dateTimeZoneString == null ? null : DateTimeZone.forID(dateTimeZoneString);
            } else if (type.isAssignableFrom(String.class)) {
                value = rs.getString(i);
            } else if (type.isAssignableFrom(UUID.class)) {
                final String uuidString = rs.getString(i);
                value = uuidString == null ? null : UUID.fromString(uuidString);
            } else if (type.isEnum()) {
                final String enumString = rs.getString(i);
                //noinspection unchecked
                value = enumString == null ? null : Enum.valueOf((Class<Enum>) type, enumString);
            } else if (type == byte[].class) {
                value = rs.getBytes(i);
            } else {
                value = rs.getObject(i);
            }

            // For h2, transform a JdbcBlob into a byte[]
            if (value instanceof Blob) {
                final Blob blob = (Blob) value;
                value = blob.getBytes(0, (int) blob.length());
            }
            if (rs.wasNull() && !type.isPrimitive()) {
                value = null;
            }

            try {
                final Method writeMethod = descriptor.getWriteMethod();
                if (writeMethod != null) {
                    writeMethod.invoke(bean, value);
                } else {
                    final String camelCasedName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, name);
                    final Field field = getField(beanClass, camelCasedName);
                    field.setAccessible(true); // Often private...
                    field.set(bean, value);
                }
            } catch (final NoSuchFieldException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to find field for " + "property, %s", name), e);
            } catch (final IllegalAccessException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to access setter for " + "property, %s", name), e);
            } catch (final InvocationTargetException e) {
                throw new IllegalArgumentException(String.format(
                        "Invocation target exception trying to " + "invoker setter for the %s property", name),
                        e);
            } catch (final NullPointerException e) {
                throw new IllegalArgumentException(
                        String.format("No appropriate method to " + "write value %s ", value.toString()), e);
            }
        }
    }

    return bean;
}

From source file:org.kuali.kpme.core.service.timezone.TimezoneServiceImpl.java

License:Educational Community License

@Override
public DateTimeZone getUserTimezoneWithFallback() {
    String tzid = getUserTimezone();
    if (StringUtils.isEmpty(tzid)) {
        return TKUtils.getSystemDateTimeZone();
    } else {/*from   www . ja v a  2  s  .  c  o  m*/
        return DateTimeZone.forID(tzid);
    }
}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

public static DateTimeZone getSystemDateTimeZone() {
    return DateTimeZone.forID(TKUtils.getSystemTimeZone());
}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

/**
 * Creates a Timestamp object using Jodatime as an intermediate data structure
 * from the provided date and time string. (From the form POST and javascript
 * formats)/* w  ww  .  j a  va 2  s .  c o m*/
 *
 * @param dateStr (the format is 01/01/2011)
 * @param timeStr (the format is 8:0)
 * @return Timestamp
 */
public static DateTime convertDateStringToDateTime(String dateStr, String timeStr) {
    // the date/time format is defined in tk.calendar.js. For now, the format is 11/17/2010 8:0
    String[] date = dateStr.split("/");
    String[] time = timeStr.split(":");

    DateTimeZone dtz = DateTimeZone.forID(HrServiceLocator.getTimezoneService().getUserTimezone());

    // this is from the jodattime javadoc:
    // DateTime(int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute, int millisOfSecond, DateTimeZone zone)
    // Noted that the month value is the actual month which is different than the java date object where the month value is the current month minus 1.
    // I tried to use the actual month in the code as much as I can to reduce the convertions.
    DateTime dateTime = new DateTime(Integer.parseInt(date[2]), Integer.parseInt(date[0]),
            Integer.parseInt(date[1]), Integer.parseInt(time[0]), Integer.parseInt(time[1]), 0, 0, dtz);

    return dateTime;
}

From source file:org.kuali.kpme.core.util.TKUtils.java

License:Educational Community License

public static DateTime formatDateTimeString(String dateTime) {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
    DateTimeZone dtz = DateTimeZone.forID(HrServiceLocator.getTimezoneService().getUserTimezone());
    try {/*  www .j av  a  2 s . c  o  m*/
        return new DateTime(sdf.parse(dateTime)).withZone(dtz);
    } catch (ParseException e) {
        return null;
    }
}

From source file:org.kuali.kpme.tklm.time.clock.web.ClockAction.java

License:Educational Community License

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionForward actionForward = super.execute(mapping, form, request, response);

    ClockActionForm clockActionForm = (ClockActionForm) form;

    TimesheetDocument timesheetDocument = clockActionForm.getTimesheetDocument();

    if (timesheetDocument != null) {
        if (!timesheetDocument.getDocumentHeader().getDocumentStatus().equals(HrConstants.ROUTE_STATUS.ENROUTE)
                && !timesheetDocument.getDocumentHeader().getDocumentStatus()
                        .equals(HrConstants.ROUTE_STATUS.FINAL)) {

            String targetPrincipalId = HrContext.getTargetPrincipalId();
            if (targetPrincipalId != null) {
                clockActionForm.setPrincipalId(targetPrincipalId);
            }/*from  w  w w.j a  va  2s . c  o  m*/
            clockActionForm.setAssignmentDescriptions(timesheetDocument.getAssignmentDescriptions(true));

            if (clockActionForm.getEditTimeBlockId() != null) {
                clockActionForm.setCurrentTimeBlock(TkServiceLocator.getTimeBlockService()
                        .getTimeBlock(clockActionForm.getEditTimeBlockId()));
            }

            ClockLog lastClockLog = TkServiceLocator.getClockLogService().getLastClockLog(targetPrincipalId);
            if (lastClockLog != null) {
                DateTime lastClockDateTime = lastClockLog.getClockDateTime();
                String lastClockZone = lastClockLog.getClockTimestampTimezone();
                if (StringUtils.isEmpty(lastClockZone)) {
                    lastClockZone = TKUtils.getSystemTimeZone();
                }
                // zone will not be null. At this point is Valid or Exception.
                // Exception would indicate bad data stored in the system. We can wrap this, but
                // for now, the thrown exception is probably more valuable.
                DateTimeZone zone = DateTimeZone.forID(lastClockZone);
                DateTime clockWithZone = lastClockDateTime.withZone(zone);
                clockActionForm.setLastClockTimeWithZone(clockWithZone.toDate());
                clockActionForm.setLastClockTimestamp(lastClockDateTime.toDate());
                clockActionForm.setLastClockAction(lastClockLog.getClockAction());
            }

            if (lastClockLog == null
                    || StringUtils.equals(lastClockLog.getClockAction(), TkConstants.CLOCK_OUT)) {
                clockActionForm.setCurrentClockAction(TkConstants.CLOCK_IN);
            } else {
                if (StringUtils.equals(lastClockLog.getClockAction(), TkConstants.LUNCH_OUT)
                        && TkServiceLocator.getSystemLunchRuleService().isShowLunchButton()) {
                    clockActionForm.setCurrentClockAction(TkConstants.LUNCH_IN);
                } else {
                    clockActionForm.setCurrentClockAction(TkConstants.CLOCK_OUT);
                }
                // if the current clock action is clock out, displays only the clocked-in assignment
                String selectedAssignment = new AssignmentDescriptionKey(lastClockLog.getJobNumber(),
                        lastClockLog.getWorkArea(), lastClockLog.getTask()).toAssignmentKeyString();
                clockActionForm.setSelectedAssignment(selectedAssignment);
                Assignment assignment = timesheetDocument
                        .getAssignment(AssignmentDescriptionKey.get(selectedAssignment));
                Map<String, String> assignmentDesc = HrServiceLocator.getAssignmentService()
                        .getAssignmentDescriptions(assignment);
                clockActionForm.setAssignmentDescriptions(assignmentDesc);
            }

            if (StringUtils.equals(GlobalVariables.getUserSession().getPrincipalId(),
                    HrContext.getTargetPrincipalId())) {
                clockActionForm.setClockButtonEnabled(true);
            } else {
                boolean isApproverOrReviewerForCurrentAssignment = false;
                String selectedAssignment = StringUtils.EMPTY;
                if (clockActionForm.getAssignmentDescriptions() != null) {
                    if (clockActionForm.getAssignmentDescriptions().size() == 1) {
                        for (String assignment : clockActionForm.getAssignmentDescriptions().keySet()) {
                            selectedAssignment = assignment;
                        }
                    } else {
                        selectedAssignment = clockActionForm.getSelectedAssignment();
                    }
                }

                Assignment assignment = HrServiceLocator.getAssignmentService()
                        .getAssignment(AssignmentDescriptionKey.get(selectedAssignment), LocalDate.now());
                if (assignment != null) {
                    String principalId = GlobalVariables.getUserSession().getPrincipalId();
                    Long workArea = assignment.getWorkArea();
                    isApproverOrReviewerForCurrentAssignment = HrServiceLocator.getKPMERoleService()
                            .principalHasRoleInWorkArea(principalId, KPMENamespace.KPME_HR.getNamespaceCode(),
                                    KPMERole.APPROVER.getRoleName(), workArea, new DateTime())
                            || HrServiceLocator.getKPMERoleService().principalHasRoleInWorkArea(principalId,
                                    KPMENamespace.KPME_HR.getNamespaceCode(),
                                    KPMERole.APPROVER_DELEGATE.getRoleName(), workArea, new DateTime())
                            || HrServiceLocator.getKPMERoleService().principalHasRoleInWorkArea(principalId,
                                    KPMENamespace.KPME_HR.getNamespaceCode(), KPMERole.REVIEWER.getRoleName(),
                                    workArea, new DateTime());
                }
                clockActionForm.setClockButtonEnabled(isApproverOrReviewerForCurrentAssignment);
            }

            clockActionForm
                    .setShowLunchButton(TkServiceLocator.getSystemLunchRuleService().isShowLunchButton());
            assignShowDistributeButton(clockActionForm);

            if (clockActionForm.isShowLunchButton()) {
                // We don't need to worry about the assignments and lunch rules
                // if the global lunch rule is turned off.

                // Check for presence of department lunch rule.
                Map<String, Boolean> assignmentDeptLunchRuleMap = new HashMap<String, Boolean>();
                for (Assignment a : timesheetDocument.getAssignments()) {
                    String key = AssignmentDescriptionKey.getAssignmentKeyString(a);
                    DeptLunchRule deptLunchRule = TkServiceLocator.getDepartmentLunchRuleService()
                            .getDepartmentLunchRule(a.getDept(), a.getWorkArea(),
                                    clockActionForm.getPrincipalId(), a.getJobNumber(), LocalDate.now());
                    assignmentDeptLunchRuleMap.put(key, deptLunchRule != null);
                }
                clockActionForm.setAssignmentLunchMap(assignmentDeptLunchRuleMap);
            }
        } else {
            clockActionForm.setErrorMessage(
                    "Your current timesheet is already submitted for Approval. Clock action is not allowed on this timesheet.");
        }
    }

    return actionForward;
}

From source file:org.kuali.kpme.tklm.time.clocklog.ClockLogBo.java

License:Educational Community License

public String getShortClockTimezone() {
    if (StringUtils.isEmpty(clockTimestampTimezone)) {
        return StringUtils.EMPTY;
    }//from w ww . j  a va 2 s .  c  om
    return DateTimeZone.forID(clockTimestampTimezone).getShortName(getTimestamp().getTime());
}

From source file:org.kuali.kpme.tklm.time.detail.validation.TimeDetailValidationUtil.java

License:Educational Community License

public static List<String> validateOverlap(Long startTime, Long endTime, boolean acrossDays, String startDateS,
        String endTimeS, DateTime startTemp, DateTime endTemp, TimesheetDocument timesheetDocument,
        String timeblockId, boolean isRegularEarnCode) {
    List<String> errors = new ArrayList<String>();
    Interval addedTimeblockInterval = new Interval(startTime, endTime);
    List<Interval> dayInt = new ArrayList<Interval>();

    //if the user is clocked in, check if this time block overlaps with the clock action
    ClockLog lastClockLog = TkServiceLocator.getClockLogService()
            .getLastClockLog(HrContext.getTargetPrincipalId());
    if (lastClockLog != null && (lastClockLog.getClockAction().equals(TkConstants.CLOCK_IN)
            || lastClockLog.getClockAction().equals(TkConstants.LUNCH_IN))) {
        DateTime lastClockDateTime = lastClockLog.getClockDateTime();
        String lastClockZone = lastClockLog.getClockTimestampTimezone();
        if (StringUtils.isEmpty(lastClockZone)) {
            lastClockZone = TKUtils.getSystemTimeZone();
        }/*from w  ww  . j  a v  a 2  s  .c om*/
        DateTimeZone zone = DateTimeZone.forID(lastClockZone);
        DateTime clockWithZone = lastClockDateTime.withZone(zone);
        DateTime currentTime = new DateTime(System.currentTimeMillis(), zone);
        Interval currentClockInInterval = new Interval(clockWithZone.getMillis(), currentTime.getMillis());

        if (isRegularEarnCode && addedTimeblockInterval.overlaps(currentClockInInterval)) {
            errors.add("The time block you are trying to add overlaps with the current clock action.");
            return errors;
        }
    }

    if (acrossDays) {
        DateTime start = new DateTime(startTime);
        DateTime end = TKUtils.convertDateStringToDateTime(startDateS, endTimeS);
        if (endTemp.getDayOfYear() - startTemp.getDayOfYear() < 1) {
            end = new DateTime(endTime);
        }
        DateTime groupEnd = new DateTime(endTime);
        Long startLong = start.getMillis();
        Long endLong = end.getMillis();
        //create interval span if start is before the end and the end is after the start except
        //for when the end is midnight ..that converts to midnight of next day
        DateMidnight midNight = new DateMidnight(endLong);
        while (start.isBefore(groupEnd.getMillis()) && ((endLong >= startLong) || end.isEqual(midNight))) {
            Interval tempInt = null;
            if (end.isEqual(midNight)) {
                tempInt = addedTimeblockInterval;
            } else {
                tempInt = new Interval(startLong, endLong);
            }
            dayInt.add(tempInt);
            start = start.plusDays(1);
            end = end.plusDays(1);
            startLong = start.getMillis();
            endLong = end.getMillis();
        }
    } else {
        dayInt.add(addedTimeblockInterval);
    }

    for (TimeBlock timeBlock : timesheetDocument.getTimeBlocks()) {
        if (errors.size() == 0 && StringUtils.equals(timeBlock.getEarnCodeType(), HrConstants.EARN_CODE_TIME)) {
            Interval timeBlockInterval = new Interval(timeBlock.getBeginTimestamp().getTime(),
                    timeBlock.getEndTimestamp().getTime());
            for (Interval intv : dayInt) {
                if (isRegularEarnCode && timeBlockInterval.overlaps(intv)
                        && (timeblockId == null || timeblockId.compareTo(timeBlock.getTkTimeBlockId()) != 0)) {
                    errors.add("The time block you are trying to add overlaps with an existing time block.");
                }
            }
        }
    }

    return errors;
}