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:com.ning.billing.account.AccountTestUtils.java

License:Apache License

private static AccountData createAccountData(final int billCycleDayUTC, final int billCycleDayLocal,
        final String phone) {
    final String externalKey = UUID.randomUUID().toString();
    final String email = UUID.randomUUID().toString().substring(0, 4) + '@'
            + UUID.randomUUID().toString().substring(0, 4);
    final String name = UUID.randomUUID().toString();
    final String locale = Locale.GERMANY.toString();
    final DateTimeZone timeZone = DateTimeZone.forID("America/Los_Angeles");
    final int firstNameLength = name.length();
    final Currency currency = Currency.MXN;
    final UUID paymentMethodId = UUID.randomUUID();
    final String address1 = UUID.randomUUID().toString();
    final String address2 = UUID.randomUUID().toString();
    final String companyName = UUID.randomUUID().toString();
    final String city = UUID.randomUUID().toString();
    final String stateOrProvince = UUID.randomUUID().toString();
    final String country = Locale.GERMANY.getCountry();
    final String postalCode = UUID.randomUUID().toString().substring(0, 4);

    return new DefaultMutableAccountData(externalKey, email, name, firstNameLength, currency, billCycleDayLocal,
            paymentMethodId, timeZone, locale, address1, address2, companyName, city, stateOrProvince, country,
            postalCode, phone, false, true);
}

From source file:com.ning.billing.entitlement.DefaultEntitlementTestInitializer.java

License:Apache License

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

    assertNotNull(accountData);/*from   www .  j av a 2 s .c om*/
    return accountData;
}

From source file:com.ning.billing.jaxrs.json.AccountJson.java

License:Apache License

public AccountData toAccountData() {
    return new AccountData() {
        @Override//from   ww w  . ja v a 2  s.  co m
        public DateTimeZone getTimeZone() {
            return (timeZone != null) ? DateTimeZone.forID(timeZone) : null;
        }

        @Override
        public String getStateOrProvince() {
            return state;
        }

        @Override
        public String getPostalCode() {
            return postalCode;
        }

        @Override
        public String getPhone() {
            return phone;
        }

        @Override
        public Boolean isMigrated() {
            return Objects.firstNonNull(isMigrated, false);
        }

        @Override
        public Boolean isNotifiedForInvoices() {
            return Objects.firstNonNull(isNotifiedForInvoices, false);
        }

        @Override
        public UUID getPaymentMethodId() {
            return paymentMethodId != null ? UUID.fromString(paymentMethodId) : null;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public String getLocale() {
            return locale;
        }

        @Override
        public Integer getFirstNameLength() {
            if (length == null && name == null) {
                return 0;
            } else if (length == null) {
                return name.length();
            } else {
                return length;
            }
        }

        @Override
        public String getExternalKey() {
            return externalKey;
        }

        @Override
        public String getEmail() {
            return email;
        }

        @Override
        public Currency getCurrency() {
            if (currency == null) {
                return null;
            } else {
                return Currency.valueOf(currency);
            }
        }

        @Override
        public String getCountry() {
            return country;
        }

        @Override
        public String getCompanyName() {
            return company;
        }

        @Override
        public String getCity() {
            return city;
        }

        @Override
        public Integer getBillCycleDayLocal() {
            return billCycleDayLocal;
        }

        @Override
        public String getAddress2() {
            return address2;
        }

        @Override
        public String getAddress1() {
            return address1;
        }
    };
}

From source file:com.ning.billing.osgi.bundles.analytics.AnalyticsTestSuiteNoDB.java

License:Apache License

@BeforeMethod(groups = "fast")
public void setUp() throws Exception {
    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.isRetired()).thenReturn(true);
    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.isRetired()).thenReturn(true);
    Mockito.when(plan.getBillingPeriod()).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);
    Mockito.when(phase.getBillingPeriod()).thenReturn(BillingPeriod.QUARTERLY);
    Mockito.when(phase.getName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(phase.getPlan()).thenReturn(plan);
    Mockito.when(phase.getPhaseType()).thenReturn(PhaseType.DISCOUNT);
    final String phaseName = phase.getName();

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

    subscriptionTransition = Mockito.mock(SubscriptionTransition.class);
    Mockito.when(subscriptionTransition.getSubscriptionId()).thenReturn(UUID.randomUUID());
    Mockito.when(subscriptionTransition.getBundleId()).thenReturn(bundleId);
    Mockito.when(subscriptionTransition.getNextState()).thenReturn(SubscriptionState.ACTIVE);
    Mockito.when(subscriptionTransition.getNextPlan()).thenReturn(plan);
    Mockito.when(subscriptionTransition.getNextPhase()).thenReturn(phase);
    Mockito.when(subscriptionTransition.getNextPriceList()).thenReturn(priceList);
    Mockito.when(subscriptionTransition.getRequestedTransitionTime())
            .thenReturn(new DateTime(2010, 1, 2, 3, 4, 5, DateTimeZone.UTC));
    Mockito.when(subscriptionTransition.getEffectiveTransitionTime())
            .thenReturn(new DateTime(2011, 2, 3, 4, 5, 6, DateTimeZone.UTC));
    Mockito.when(subscriptionTransition.getTransitionType()).thenReturn(SubscriptionTransitionType.CREATE);
    Mockito.when(subscriptionTransition.getNextEventCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 49, DateTimeZone.UTC));
    Mockito.when(subscriptionTransition.getNextEventId()).thenReturn(UUID.randomUUID());
    final UUID subscriptionId = subscriptionTransition.getSubscriptionId();
    final UUID nextEventId = subscriptionTransition.getNextEventId();

    blockingState = Mockito.mock(BlockingState.class);
    Mockito.when(blockingState.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(blockingState.getBlockedId()).thenReturn(bundleId);
    Mockito.when(blockingState.getStateName()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(blockingState.getType()).thenReturn(Type.SUBSCRIPTION_BUNDLE);
    Mockito.when(blockingState.getTimestamp())
            .thenReturn(new DateTime(2010, 2, 2, 4, 22, 22, DateTimeZone.UTC));
    Mockito.when(blockingState.isBlockBilling()).thenReturn(true);
    Mockito.when(blockingState.isBlockChange()).thenReturn(false);
    Mockito.when(blockingState.isBlockEntitlement()).thenReturn(true);
    Mockito.when(blockingState.getDescription()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(blockingState.getService()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(blockingState.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 0, DateTimeZone.UTC));
    final UUID blockingStateId = blockingState.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());
    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);

    paymentAttempt = Mockito.mock(PaymentAttempt.class);
    Mockito.when(paymentAttempt.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(paymentAttempt.getEffectiveDate())
            .thenReturn(new DateTime(2019, 12, 30, 10, 10, 10, DateTimeZone.UTC));
    Mockito.when(paymentAttempt.getGatewayErrorCode()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(paymentAttempt.getGatewayErrorMsg()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(paymentAttempt.getPaymentStatus()).thenReturn(PaymentStatus.SUCCESS);
    Mockito.when(paymentAttempt.getCreatedDate())
            .thenReturn(new DateTime(2016, 1, 22, 10, 56, 54, DateTimeZone.UTC));

    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();

    payment = Mockito.mock(Payment.class);
    Mockito.when(payment.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(payment.getAccountId()).thenReturn(accountId);
    Mockito.when(payment.getInvoiceId()).thenReturn(invoiceId);
    Mockito.when(payment.getPaymentMethodId()).thenReturn(paymentMethodId);
    Mockito.when(payment.getPaymentNumber()).thenReturn(1);
    Mockito.when(payment.getAmount()).thenReturn(new BigDecimal("199999"));
    Mockito.when(payment.getPaidAmount()).thenReturn(new BigDecimal("199998"));
    Mockito.when(payment.getEffectiveDate()).thenReturn(new DateTime(2019, 2, 3, 12, 12, 12, DateTimeZone.UTC));
    Mockito.when(payment.getCurrency()).thenReturn(Currency.USD);
    Mockito.when(payment.getPaymentStatus()).thenReturn(PaymentStatus.AUTO_PAY_OFF);
    Mockito.when(payment.getAttempts()).thenReturn(ImmutableList.<PaymentAttempt>of(paymentAttempt));
    Mockito.when(payment.getExtFirstPaymentIdRef()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(payment.getExtSecondPaymentIdRef()).thenReturn(UUID.randomUUID().toString());
    Mockito.when(payment.getCreatedDate()).thenReturn(new DateTime(2016, 1, 22, 10, 56, 56, DateTimeZone.UTC));

    refund = Mockito.mock(Refund.class);
    Mockito.when(refund.getId()).thenReturn(UUID.randomUUID());
    Mockito.when(refund.getPaymentId()).thenReturn(UUID.randomUUID());
    Mockito.when(refund.isAdjusted()).thenReturn(true);
    Mockito.when(refund.getRefundAmount()).thenReturn(BigDecimal.TEN);
    Mockito.when(refund.getCurrency()).thenReturn(Currency.BRL);
    Mockito.when(refund.getEffectiveDate()).thenReturn(new DateTime(2015, 2, 2, 10, 56, 5, 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.TENANT);
    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());

    // 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(accountId, ObjectType.ACCOUNT, callContext))
            .thenReturn(accountRecordId);
    Mockito.when(recordIdApi.getRecordId(nextEventId, ObjectType.SUBSCRIPTION_EVENT, callContext))
            .thenReturn(subscriptionEventRecordId);
    Mockito.when(recordIdApi.getRecordId(invoiceId, ObjectType.INVOICE, callContext))
            .thenReturn(invoiceRecordId);
    Mockito.when(recordIdApi.getRecordId(invoiceItemId, ObjectType.INVOICE_ITEM, callContext))
            .thenReturn(invoiceItemRecordId);
    Mockito.when(recordIdApi.getRecordId(invoicePaymentId, ObjectType.INVOICE_PAYMENT, callContext))
            .thenReturn(invoicePaymentRecordId);
    Mockito.when(recordIdApi.getRecordId(blockingStateId, ObjectType.BLOCKING_STATES, callContext))
            .thenReturn(blockingStateRecordId);
    Mockito.when(recordIdApi.getRecordId(fieldId, ObjectType.CUSTOM_FIELD, callContext))
            .thenReturn(fieldRecordId);//from   w w w.  ja v a 2s  .  com
    Mockito.when(recordIdApi.getRecordId(tagId, ObjectType.TAG, callContext)).thenReturn(tagRecordId);
    Mockito.when(recordIdApi.getRecordId(tenantId, ObjectType.TENANT, callContext)).thenReturn(tenantRecordId);

    killbillAPI = Mockito.mock(OSGIKillbillAPI.class);
    Mockito.when(killbillAPI.getRecordIdApi()).thenReturn(recordIdApi);

    killbillDataSource = Mockito.mock(OSGIKillbillDataSource.class);
}

From source file:com.ning.billing.util.dao.LowerToCamelBeanMapper.java

License:Apache License

public T map(final int row, final ResultSet rs, final StatementContext ctx) throws SQLException {
    final T bean;
    try {/*www  .  j  a v a 2s .  c  om*/
        bean = type.newInstance();
    } catch (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)) {
                final Date date = rs.getDate(i);
                value = date == null ? null : new LocalDate(date, 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 {
                value = rs.getObject(i);
            }

            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 (NoSuchFieldException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to find field for " + "property, %s", name), e);
            } catch (IllegalAccessException e) {
                throw new IllegalArgumentException(
                        String.format("Unable to access setter for " + "property, %s", name), e);
            } catch (InvocationTargetException e) {
                throw new IllegalArgumentException(String.format(
                        "Invocation target exception trying to " + "invoker setter for the %s property", name),
                        e);
            } catch (NullPointerException e) {
                throw new IllegalArgumentException(
                        String.format("No appropriate method to " + "write value %s ", value.toString()), e);
            }
        }
    }

    return bean;
}

From source file:com.ning.killbill.zuora.zuora.ZuoraApi.java

License:Apache License

public Either<ZuoraError, List<Invoice>> getInvoicesForAccount(final ZuoraConnection connection,
        final Account account, @Nullable final DateTime from, @Nullable final DateTime to) {
    // We need to round down the to, invoice date in Zuora is in the form 2011-09-29T00:00:00.000-08:00
    final String toDate = to == null ? ""
            : to.toLocalDate().toDateTimeAtStartOfDay(DateTimeZone.forID("Pacific/Pitcairn")).toString();

    final String query;
    if (from == null && to != null) {
        query = stringTemplateLoader.load("getPostedInvoicesForAccountTo").define("accountId", account.getId())
                .define("invoiceDateTo", toDate).build();
    } else if (from != null && to != null) {
        query = stringTemplateLoader.load("getPostedInvoicesForAccountFromTo")
                .define("accountId", account.getId()).define("invoiceDateTo", toDate)
                .define("invoiceDateFrom", from.toString()).build();
    } else {/*from   www.ja  v a  2s . c o m*/
        throw new UnsupportedOperationException();
    }

    final Either<ZuoraError, List<Invoice>> invoicesOrError = connection.query(query);
    if (invoicesOrError.isLeft()) {
        return Either.left(invoicesOrError.getLeft());
    } else {
        return Either.right(invoicesOrError.getRight());
    }
}

From source file:com.ning.metrics.meteo.subscribers.FileSubscriber.java

License:Apache License

private ImmutableList<LinkedHashMap<String, Object>> getDataPoints() {
    ImmutableList.Builder<LinkedHashMap<String, Object>> builder = new ImmutableList.Builder<LinkedHashMap<String, Object>>();

    try {/*w  ww. j  a  va 2  s .  co m*/
        for (String line : (List<String>) IOUtils.readLines(new FileReader(subscriberConfig.getFilePath()))) {
            if (line.trim().length() > 0) {
                map.clear();
                String[] items = line.split(subscriberConfig.getSeparator());
                long dateTime = new DateTime(items[0], DateTimeZone.forID("UTC")).getMillis();
                map.put("timestamp", dateTime);
                for (int j = 1; j < items.length; j++) {
                    double value = Double.valueOf(items[j]);
                    map.put(subscriberConfig.getAttributes()[j - 1], value);
                }
                builder.add(new LinkedHashMap(map));
            }
        }

        return builder.build();
    } catch (IOException e) {
        log.error("Unable to read file: " + subscriberConfig.getFilePath());
        return null;
    }
}

From source file:com.nominanuda.lang.CronExpr.java

License:Apache License

/**
 * @see org.joda.time.DateTimeZone#forID(String)
 *//*  w w w  .  j a v a2  s .c  o m*/
public CronExpr(String cronExpression, String timeZone) throws IllegalArgumentException {
    this(cronExpression, DateTimeZone.forID(timeZone));
}

From source file:com.orion.bot.Orion.java

License:Open Source License

/**
 * Object constructor//from   w  ww .j  a  v a  2  s  .c om
 * 
 * @author Daniele Pantaleone
 * @param  path The Orion configuration file path
 **/
public Orion(String path) {

    try {

        // Loading the main XML configuration file
        this.config = new XmlConfiguration(path);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////// LOGGER SETUP /////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        Logger.getRootLogger().setLevel(Level.OFF);
        Logger logger = Logger.getLogger("Orion");

        FileAppender fa = new FileAppender();

        fa.setLayout(new PatternLayout("%-20d{yyyy-MM-dd hh:mm:ss} %-6p %m%n"));
        fa.setFile(this.config.getString("logfile", "basepath") + this.config.getString("logfile", "filename"));
        fa.setAppend(this.config.getBoolean("logfile", "append"));
        fa.setName("FILE");
        fa.activateOptions();

        logger.addAppender(fa);

        if (this.config.getBoolean("logfile", "console")) {

            ConsoleAppender ca = new ConsoleAppender();
            ca.setLayout(new PatternLayout("%-20d{yyyy-MM-dd hh:mm:ss} %-6p %m%n"));
            ca.setWriter(new OutputStreamWriter(System.out));
            ca.setName("CONSOLE");
            ca.activateOptions();

            logger.addAppender(ca);

        }

        // Setting the log level for both the log appenders
        logger.setLevel(Level.toLevel(this.config.getString("logfile", "level")));

        // Creating the main Log object
        this.log = new Log4JLogger(logger);

        // We got a fully initialized logger utility now: printing some info messages
        this.log.info(
                "Starting " + BOTNAME + " " + VERSION + " [" + CODENAME + "] [ " + AUTHOR + " ] - " + WEBSITE);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////// LOADING PREFERENCES ///////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.timeformat = this.config.getString("orion", "timeformat", "EEE, d MMM yyyy HH:mm:ss");
        this.timezone = DateTimeZone.forID(this.config.getString("orion", "timezone", "CET"));
        this.locale = new Locale(this.config.getString("orion", "locale", "EN"),
                this.config.getString("orion", "locale", "EN"));
        this.startuptime = new DateTime(this.timezone);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////// PRE INITIALIZED OBJECTS ////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.eventBus = new EventBus("events");
        this.schedule = new LinkedHashMap<String, Timer>();
        this.game = new Game();

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////// STORAGE SETUP /////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.storage = new MySqlDataSourceManager(this.config.getString("storage", "username"),
                this.config.getString("storage", "password"), this.config.getString("storage", "connection"),
                this.log);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////// BUFFERS SETUP ////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.commandqueue = new ArrayBlockingQueue<Command>(this.config.getInt("orion", "commandqueue", 100));
        this.regcommands = new MultiKeyHashMap<String, String, RegisteredCommand>();

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////// CONSOLE SETUP ////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.console = (Console) Class
                .forName("com.orion.console." + this.config.getString("orion", "game") + "Console")
                .getConstructor(String.class, int.class, String.class, Orion.class)
                .newInstance(this.config.getString("server", "rconaddress"),
                        this.config.getInt("server", "rconport"),
                        this.config.getString("server", "rconpassword"), this);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////// CONTROLLERS SETUP /////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.groups = new GroupC(this);
        this.clients = new ClientC(this);
        this.aliases = new AliasC(this);
        this.callvotes = new CallvoteC(this);
        this.ipaliases = new IpAliasC(this);
        this.penalties = new PenaltyC(this);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////// PARSER SETUP/////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.parser = (Parser) Class
                .forName("com.orion.parser." + this.config.getString("orion", "game") + "Parser")
                .getConstructor(Orion.class).newInstance(this);

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////// LOADING PLUGINS //////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.plugins = new LinkedHashMap<String, Plugin>();
        Map<String, String> pluginsList = this.config.getMap("plugins");

        for (Map.Entry<String, String> entry : pluginsList.entrySet()) {

            try {

                this.log.debug("Loading plugin [ " + Character.toUpperCase(entry.getKey().charAt(0))
                        + entry.getKey().substring(1).toLowerCase() + " ]");
                Plugin plugin = Plugin.getPlugin(entry.getKey(),
                        new XmlConfiguration(entry.getValue(), this.log), this);
                this.plugins.put(entry.getKey(), plugin);

            } catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
                    | IllegalAccessException | IllegalArgumentException | InvocationTargetException
                    | ParserException e) {

                // Logging the Exception and keep processing other plugins. This will not stop Orion execution
                this.log.error("Unable to load plugin [ " + Character.toUpperCase(entry.getKey().charAt(0))
                        + entry.getKey().substring(1).toLowerCase() + " ]", e);

            }

        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////// PLUGINS SETUP //////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        for (Map.Entry<String, Plugin> entry : this.plugins.entrySet()) {
            Plugin plugin = entry.getValue();
            plugin.onLoadConfig();
        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////// PLUGINS STARTUP /////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        for (Map.Entry<String, Plugin> entry : this.plugins.entrySet()) {

            Plugin plugin = entry.getValue();

            // Check for the plugin to be enabled. onLoadConfig may have disabled
            // such plugin in case the plugin config file is non well formed
            if (plugin.isEnabled())
                plugin.onStartup();

        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////// GAME SERVER SYNC ////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        List<List<String>> status = this.console.getStatus();

        if (status == null) {
            this.log.warn("Unable to synchronize current server status: RCON response is NULL");
            return;
        }

        for (List<String> line : status) {

            // Dumping current user to build an infostring for the onClientConnect parser method
            Map<String, String> userinfo = this.console.dumpuser(Integer.parseInt(line.get(0)));

            // Not a valid client
            if (userinfo == null)
                continue;

            String infostring = new String();

            for (Map.Entry<String, String> entry : userinfo.entrySet()) {
                // Appending <key|value> using infostring format
                infostring += "\\" + entry.getKey() + "\\" + entry.getValue();
            }

            // Generating an EVT_CLIENT_CONNECT event for the connected client
            this.parser.parseLine("0:00 ClientUserinfo: " + line.get(0) + " " + infostring);

        }

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        /////////////////////////////////////////////////////// THREADS SETUP /////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.reader = new Thread(new Reader(this.config.getString("server", "logfile"),
                this.config.getInt("server", "logdelay"), this));
        this.commandproc = new Thread(new CommandProcessor(this));
        this.reader.setName("READER");
        this.commandproc.setName("COMMAND");

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////// THREADS STARTUP ////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.commandproc.start();
        this.reader.start();

        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////// NOTICE BOT RUNNING ///////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        this.console.say(
                BOTNAME + " " + VERSION + " [" + CODENAME + "] - " + WEBSITE + " >> " + Color.GREEN + "ONLINE");

    } catch (Exception e) {

        // Stopping Threads if they are alive
        if ((this.commandproc != null) && (this.commandproc.isAlive()))
            this.commandproc.interrupt();
        if ((this.reader != null) && (this.reader.isAlive()))
            this.reader.interrupt();

        // Logging the Exception. Orion is not going to work if an Exception is catched at startup time
        this.log.fatal("Unable to start " + BOTNAME + " " + VERSION + " [" + CODENAME + "] [ " + AUTHOR
                + " ] - " + WEBSITE, e);

    }

}

From source file:com.payintech.smoney.entity.BankTransferEntity.java

License:Open Source License

/**
 * Get the payment date on a specific timezone.
 *
 * @param timeZone The timezone to use/*from   w  w w.ja va2 s. c  om*/
 * @return The datetime converted to the specific timezone
 * @since 15.12
 */
public DateTime getPaymentDate(final String timeZone) {
    return this.PaymentDate.toDateTime(DateTimeZone.forID(timeZone));
}