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