Search in sources :

Example 41 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestRetryablePayment method testRetryLogicFromRetriedStateWithPaymentApiException.

@Test(groups = "fast")
public void testRetryLogicFromRetriedStateWithPaymentApiException() {
    mockRetryProviderPlugin.setAborted(false).setNextRetryDate(null);
    mockRetryAuthorizeOperationCallback.setResult(null).setException(new PaymentApiException(ErrorCode.__UNKNOWN_ERROR_CODE, "foo"));
    runner.setOperationCallback(mockRetryAuthorizeOperationCallback).setContext(paymentStateContext);
    final State state = retrySMHelper.getRetriedState();
    final UUID transactionId = UUID.randomUUID();
    final UUID paymentId = UUID.randomUUID();
    final PaymentAttemptModelDao attempt = new PaymentAttemptModelDao(account.getId(), paymentMethodId, utcNow, utcNow, paymentExternalKey, transactionId, paymentTransactionExternalKey, TransactionType.AUTHORIZE, state.getName(), amount, currency, null, EMPTY_PROPERTIES);
    paymentDao.insertPaymentAttemptWithProperties(attempt, internalCallContext);
    paymentDao.insertPaymentWithFirstTransaction(new PaymentModelDao(paymentId, utcNow, utcNow, account.getId(), paymentMethodId, -1, paymentExternalKey), new PaymentTransactionModelDao(transactionId, attempt.getId(), paymentTransactionExternalKey, utcNow, utcNow, paymentId, TransactionType.AUTHORIZE, utcNow, TransactionStatus.PAYMENT_FAILURE, amount, currency, "bla", "foo"), internalCallContext);
    processor.retryPaymentTransaction(attempt.getId(), ImmutableList.<String>of(MockPaymentControlProviderPlugin.PLUGIN_NAME), internalCallContext);
    final List<PaymentAttemptModelDao> pas = paymentDao.getPaymentAttemptByTransactionExternalKey(paymentTransactionExternalKey, internalCallContext);
    assertEquals(pas.size(), 2);
    final PaymentAttemptModelDao failedAttempt = Iterables.tryFind(pas, new Predicate<PaymentAttemptModelDao>() {

        @Override
        public boolean apply(final PaymentAttemptModelDao input) {
            return input.getTransactionType() == TransactionType.AUTHORIZE && input.getStateName().equals("ABORTED");
        }
    }).orNull();
    assertNotNull(failedAttempt);
}
Also used : PaymentAttemptModelDao(org.killbill.billing.payment.dao.PaymentAttemptModelDao) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) PaymentModelDao(org.killbill.billing.payment.dao.PaymentModelDao) State(org.killbill.automaton.State) PaymentApiException(org.killbill.billing.payment.api.PaymentApiException) UUID(java.util.UUID) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 42 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestDefaultPriceOverride method testGetOverriddenPlan.

@Test(groups = "slow")
public void testGetOverriddenPlan() throws Exception {
    final StandaloneCatalog catalog = XMLLoader.getObjectFromString(Resources.getResource("SpyCarAdvanced.xml").toExternalForm(), StandaloneCatalog.class);
    catalog.initialize(catalog, null);
    final Plan plan = catalog.findCurrentPlan("discount-standard-monthly");
    final List<PlanPhasePriceOverride> overrides = new ArrayList<PlanPhasePriceOverride>();
    final PlanPhasePriceOverride phase1 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[0].getName(), Currency.USD, BigDecimal.ONE, null);
    overrides.add(phase1);
    final PlanPhasePriceOverride phase3 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[2].getName(), Currency.USD, null, new BigDecimal("142.41"));
    overrides.add(phase3);
    final DefaultPlan overriddenPlanCreated = priceOverride.getOrCreateOverriddenPlan(catalog, plan, new DateTime(catalog.getEffectiveDate()), overrides, internalCallContext);
    System.out.println("overriddenPlanCreated = " + overriddenPlanCreated.getName());
    final DefaultPlan overriddenPlan = priceOverride.getOverriddenPlan(overriddenPlanCreated.getName(), catalog, internalCallContext);
    assertEquals(overriddenPlan.getProduct().getName(), plan.getProduct().getName());
    assertEquals(overriddenPlan.getRecurringBillingPeriod(), plan.getRecurringBillingPeriod());
    if (plan.getEffectiveDateForExistingSubscriptions() != null) {
        assertEquals(overriddenPlan.getEffectiveDateForExistingSubscriptions().compareTo(plan.getEffectiveDateForExistingSubscriptions()), 0);
    }
    assertNotEquals(overriddenPlan.getFinalPhase().getName(), plan.getFinalPhase().getName());
    assertEquals(overriddenPlan.getPlansAllowedInBundle(), plan.getPlansAllowedInBundle());
    assertEquals(overriddenPlan.getAllPhases().length, overriddenPlan.getAllPhases().length);
    for (int i = 0; i < overriddenPlan.getAllPhases().length; i++) {
        final DefaultPlanPhase initialPhase = (DefaultPlanPhase) plan.getAllPhases()[i];
        final DefaultPlanPhase newPhase = (DefaultPlanPhase) overriddenPlan.getAllPhases()[i];
        final PlanPhasePriceOverride override = Iterables.tryFind(overrides, new Predicate<PlanPhasePriceOverride>() {

            @Override
            public boolean apply(final PlanPhasePriceOverride input) {
                return input.getPhaseName().equals(initialPhase.getName());
            }
        }).orNull();
        assertNotEquals(newPhase.getName(), initialPhase.getName());
        assertEquals(newPhase.getName(), overriddenPlan.getName() + "-" + initialPhase.getName().split("-")[initialPhase.getName().split("-").length - 1]);
        assertEquals(newPhase.getDuration(), initialPhase.getDuration());
        assertEquals(newPhase.getPhaseType(), initialPhase.getPhaseType());
        assertEquals(newPhase.getUsages().length, initialPhase.getUsages().length);
        if (initialPhase.getFixed() != null) {
            assertEquals(newPhase.getFixed().getType(), initialPhase.getFixed().getType());
            assertInternationalPrice(newPhase.getFixed().getPrice(), initialPhase.getFixed().getPrice(), override, true);
        }
        if (initialPhase.getRecurring() != null) {
            assertInternationalPrice(newPhase.getRecurring().getRecurringPrice(), initialPhase.getRecurring().getRecurringPrice(), override, false);
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Plan(org.killbill.billing.catalog.api.Plan) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride) Predicate(com.google.common.base.Predicate) Test(org.testng.annotations.Test)

Example 43 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class TestDefaultPriceOverride method testBasic.

@Test(groups = "slow")
public void testBasic() throws Exception {
    final StandaloneCatalog catalog = XMLLoader.getObjectFromString(Resources.getResource("SpyCarAdvanced.xml").toExternalForm(), StandaloneCatalog.class);
    catalog.initialize(catalog, null);
    final Plan plan = catalog.findCurrentPlan("discount-standard-monthly");
    final List<PlanPhasePriceOverride> overrides = new ArrayList<PlanPhasePriceOverride>();
    final PlanPhasePriceOverride phase1 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[0].getName(), Currency.USD, BigDecimal.ONE, null);
    overrides.add(phase1);
    final PlanPhasePriceOverride phase3 = new DefaultPlanPhasePriceOverride(plan.getAllPhases()[2].getName(), Currency.USD, null, new BigDecimal("142.41"));
    overrides.add(phase3);
    final DefaultPlan overriddenPlan = priceOverride.getOrCreateOverriddenPlan(catalog, plan, new DateTime(catalog.getEffectiveDate()), overrides, internalCallContext);
    final Matcher m = DefaultPriceOverride.CUSTOM_PLAN_NAME_PATTERN.matcher(overriddenPlan.getName());
    assertTrue(m.matches());
    assertEquals(m.group(1), plan.getName());
    assertEquals(overriddenPlan.getProduct().getName(), plan.getProduct().getName());
    assertEquals(overriddenPlan.getRecurringBillingPeriod(), plan.getRecurringBillingPeriod());
    if (plan.getEffectiveDateForExistingSubscriptions() != null) {
        assertEquals(overriddenPlan.getEffectiveDateForExistingSubscriptions().compareTo(plan.getEffectiveDateForExistingSubscriptions()), 0);
    }
    assertNotEquals(overriddenPlan.getFinalPhase().getName(), plan.getFinalPhase().getName());
    assertEquals(overriddenPlan.getPlansAllowedInBundle(), plan.getPlansAllowedInBundle());
    assertEquals(overriddenPlan.getAllPhases().length, overriddenPlan.getAllPhases().length);
    for (int i = 0; i < overriddenPlan.getAllPhases().length; i++) {
        final DefaultPlanPhase initialPhase = (DefaultPlanPhase) plan.getAllPhases()[i];
        final DefaultPlanPhase newPhase = (DefaultPlanPhase) overriddenPlan.getAllPhases()[i];
        final PlanPhasePriceOverride override = Iterables.tryFind(overrides, new Predicate<PlanPhasePriceOverride>() {

            @Override
            public boolean apply(final PlanPhasePriceOverride input) {
                return input.getPhaseName().equals(initialPhase.getName());
            }
        }).orNull();
        assertNotEquals(newPhase.getName(), initialPhase.getName());
        assertEquals(newPhase.getDuration(), initialPhase.getDuration());
        assertEquals(newPhase.getPhaseType(), initialPhase.getPhaseType());
        assertEquals(newPhase.getUsages().length, initialPhase.getUsages().length);
        if (initialPhase.getFixed() != null) {
            assertEquals(newPhase.getFixed().getType(), initialPhase.getFixed().getType());
            assertInternationalPrice(newPhase.getFixed().getPrice(), initialPhase.getFixed().getPrice(), override, true);
        }
        if (initialPhase.getRecurring() != null) {
            assertInternationalPrice(newPhase.getRecurring().getRecurringPrice(), initialPhase.getRecurring().getRecurringPrice(), override, false);
        }
    }
}
Also used : Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Plan(org.killbill.billing.catalog.api.Plan) BigDecimal(java.math.BigDecimal) DateTime(org.joda.time.DateTime) Predicate(com.google.common.base.Predicate) PlanPhasePriceOverride(org.killbill.billing.catalog.api.PlanPhasePriceOverride) Test(org.testng.annotations.Test)

Example 44 with Predicate

use of com.google.common.base.Predicate in project killbill by killbill.

the class InvoicePaymentControlPluginApi method checkForIncompleteInvoicePaymentAndRepair.

private boolean checkForIncompleteInvoicePaymentAndRepair(final Invoice invoice, final InternalCallContext internalContext) throws InvoiceApiException {
    final List<InvoicePayment> invoicePayments = invoice.getPayments();
    // Look for ATTEMPT matching that invoiceId that are not successful and extract matching paymentTransaction
    final InvoicePayment incompleteInvoicePayment = Iterables.tryFind(invoicePayments, new Predicate<InvoicePayment>() {

        @Override
        public boolean apply(final InvoicePayment input) {
            return input.getType() == InvoicePaymentType.ATTEMPT && !input.isSuccess();
        }
    }).orNull();
    // If such (incomplete) paymentTransaction exists, verify the state of the payment transaction
    if (incompleteInvoicePayment != null) {
        final String transactionExternalKey = incompleteInvoicePayment.getPaymentCookieId();
        final List<PaymentTransactionModelDao> transactions = paymentDao.getPaymentTransactionsByExternalKey(transactionExternalKey, internalContext);
        final PaymentTransactionModelDao successfulTransaction = Iterables.tryFind(transactions, new Predicate<PaymentTransactionModelDao>() {

            @Override
            public boolean apply(final PaymentTransactionModelDao input) {
                //
                return input.getTransactionStatus() == TransactionStatus.SUCCESS;
            }
        }).orNull();
        if (successfulTransaction != null) {
            log.info(String.format("Detected an incomplete invoicePayment row for invoiceId='%s' and transactionExternalKey='%s', will correct status", invoice.getId(), successfulTransaction.getTransactionExternalKey()));
            invoiceApi.recordPaymentAttemptCompletion(invoice.getId(), successfulTransaction.getAmount(), successfulTransaction.getCurrency(), successfulTransaction.getProcessedCurrency(), successfulTransaction.getPaymentId(), successfulTransaction.getTransactionExternalKey(), successfulTransaction.getCreatedDate(), true, internalContext);
            return true;
        }
    }
    return false;
}
Also used : InvoicePayment(org.killbill.billing.invoice.api.InvoicePayment) PaymentTransactionModelDao(org.killbill.billing.payment.dao.PaymentTransactionModelDao) Predicate(com.google.common.base.Predicate)

Example 45 with Predicate

use of com.google.common.base.Predicate in project legacy-jclouds-examples by jclouds.

the class WindowsInstanceStarter method run.

public void run() {
    final String region = arguments.getRegion();
    // Build a template
    Template template = computeService.templateBuilder().locationId(region).imageNameMatches(arguments.getImageNamePattern()).hardwareId(arguments.getInstanceType()).build();
    logger.info("Selected AMI is: %s", template.getImage().toString());
    template.getOptions().inboundPorts(3389);
    // Create the node
    logger.info("Creating node and waiting for it to become available");
    Set<? extends NodeMetadata> nodes = null;
    try {
        nodes = computeService.createNodesInGroup("basic-ami", 1, template);
    } catch (RunNodesException e) {
        logger.error(e, "Unable to start nodes; aborting");
        return;
    }
    NodeMetadata node = Iterables.getOnlyElement(nodes);
    // Wait for the administrator password
    logger.info("Waiting for administrator password to become available");
    // This predicate will call EC2's API to get the Windows Administrator
    // password, and returns true if there is password data available.
    Predicate<String> passwordReady = new Predicate<String>() {

        @Override
        public boolean apply(@Nullable String s) {
            if (Strings.isNullOrEmpty(s))
                return false;
            PasswordData data = ec2Client.getWindowsServices().getPasswordDataInRegion(region, s);
            if (data == null)
                return false;
            return !Strings.isNullOrEmpty(data.getPasswordData());
        }
    };
    // Now wait, using RetryablePredicate
    final int maxWait = 600;
    final int period = 10;
    final TimeUnit timeUnit = TimeUnit.SECONDS;
    RetryablePredicate<String> passwordReadyRetryable = new RetryablePredicate<String>(passwordReady, maxWait, period, timeUnit);
    boolean isPasswordReady = passwordReadyRetryable.apply(node.getProviderId());
    if (!isPasswordReady) {
        logger.error("Password is not ready after %s %s - aborting and shutting down node", maxWait, timeUnit.toString());
        computeService.destroyNode(node.getId());
        return;
    }
    // Now we can get the password data, decrypt it, and get a LoginCredentials instance
    PasswordDataAndPrivateKey dataAndKey = new PasswordDataAndPrivateKey(ec2Client.getWindowsServices().getPasswordDataInRegion(region, node.getProviderId()), node.getCredentials().getPrivateKey());
    WindowsLoginCredentialsFromEncryptedData f = context.getUtils().getInjector().getInstance(WindowsLoginCredentialsFromEncryptedData.class);
    LoginCredentials credentials = f.apply(dataAndKey);
    // Send to the log the details you need to log in to the instance with RDP
    String publicIp = Iterables.getFirst(node.getPublicAddresses(), null);
    logger.info("IP address: %s", publicIp);
    logger.info("Login name: %s", credentials.getUser());
    logger.info("Password:   %s", credentials.getPassword());
    // Wait for Enter on the console
    logger.info("Hit Enter to shut down the node.");
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);
    try {
        in.readLine();
    } catch (IOException e) {
        logger.error(e, "IOException while reading console input");
    }
    // Tidy up
    logger.info("Shutting down");
    computeService.destroyNode(node.getId());
}
Also used : RetryablePredicate(org.jclouds.predicates.RetryablePredicate) WindowsLoginCredentialsFromEncryptedData(org.jclouds.ec2.compute.functions.WindowsLoginCredentialsFromEncryptedData) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) Template(org.jclouds.compute.domain.Template) Predicate(com.google.common.base.Predicate) RetryablePredicate(org.jclouds.predicates.RetryablePredicate) NodeMetadata(org.jclouds.compute.domain.NodeMetadata) LoginCredentials(org.jclouds.domain.LoginCredentials) RunNodesException(org.jclouds.compute.RunNodesException) PasswordData(org.jclouds.ec2.domain.PasswordData) BufferedReader(java.io.BufferedReader) TimeUnit(java.util.concurrent.TimeUnit) PasswordDataAndPrivateKey(org.jclouds.ec2.compute.domain.PasswordDataAndPrivateKey) Nullable(javax.annotation.Nullable)

Aggregations

Predicate (com.google.common.base.Predicate)217 List (java.util.List)37 Test (org.junit.Test)37 ArrayList (java.util.ArrayList)34 Nullable (javax.annotation.Nullable)33 Map (java.util.Map)24 UUID (java.util.UUID)21 IOException (java.io.IOException)20 File (java.io.File)18 HashMap (java.util.HashMap)15 Set (java.util.Set)14 Test (org.testng.annotations.Test)14 ImmutableList (com.google.common.collect.ImmutableList)13 Collection (java.util.Collection)11 DateTime (org.joda.time.DateTime)9 BigDecimal (java.math.BigDecimal)8 Path (javax.ws.rs.Path)8 Expression (com.sri.ai.expresso.api.Expression)7 Util (com.sri.ai.util.Util)7 XtextResource (org.eclipse.xtext.resource.XtextResource)7