All About New Java 9

In September, Oracle released Java SE 9 with over 150 new features. The latest version of the widely used programming language comes with several new features and APIs to accelerate development of applications for both large and small devices. At the same time, the features provided by Java 9 help programmers to improve application’s performance, security, and maintainability. Hence, it becomes essential for programmers to understand some of the key features provided by Java 9.

What Programmers Need to Know about Java 9?

Module System

The developers can now use Better Support for HTML5 and JavaScript to divide JDK into multiple modules. Each modular JAR file contains a module descriptor. The developers can define interdependency of various modules through requires statements. The modularity makes it easier for programmers to run JVM modules smoothly on small devices that lack additional memory. At the same time, they can also run only the APIs and JVM modules required by the application.

Ahead-of-Time Compilation

Java 9 improves code compilation process significantly through ahead-of-time (AOT) compilation. The programmers can leverage AOT compilation compile Java classes into native code even before the virtual machine launches them. AOT compilation improves the performance of both large and small applications by overcoming major shortcomings of just-in-time (JIT) compilation. Unlike JIT compilation, AOT compilation ensures that no Java method remains uncompiled.

Real-Eval-Print-Loop Tool

Java 9 comes with a new real-eval-print-loop (REPL) command line tool – Shell. Shell is designed with features to evaluate declarative statements and expressions interactively. A programmer can use Shell to assess the quality of Java code before compilation. He can simply enter a piece of code and collect feedback. Shell even has the capability to complete tabs and add required terminal semicolons automatically. The new REPL tool makes Java compete with widely used programming languages like Python and Scala.

Better Support for HTML5 and JavaScript

The improved Javadoc documentation tool provided by Java 9 has the capability to generate HTML5 markup. Also, latest version of the programming language supports several new characters, blocks, and scripts as part of Unicode 8.0 encoding standard. At the same time, Java 9 comes with an improved and lightweight JavaScript engine that makes it easier for programmers to embed JavaScript code in Java applications. The developers can further enable ECMAScript code analysis in various IDEs and frameworks directly with the parser API for Nashorn’s ECMAScript syntax tree provided by JDK.

Improved Stream API

While writing Java code, programmers use strings to express calculations. Java 8 accelerated stream processing by providing the Streams API. Java 9 comes with an improved version of the Streams API that enables developers to take and drop items from Stream based on specific conditions by adding methods. Also, the improved Streams API is designed with features to create a stream for nullable value and iterate over Stream elements.

Multi-Resolution Image API

Java 9 introduces a new interface – MultiResolutionImage – to create a single multi-resolution image by encapsulating multiple images with varying resolutions. The developers can further use the Multi-Resolution Image API provided by Java 9 to get various variants of a single image. Also, they can use the API to select a particular image based on the required resolution. Hence, the Java programmers can now use a single API to create a unified multi-resolution image and get resolution-specific image variants.

http://2 client API

Java 9 completely changed the way applications make HTTP calls. It replaces the HttpURLConnection API with a new HTTP client API. The HTTP client API supports both http://2 and WebSockets. However, the API is currently not a part of Java SE. It is implemented as an incubator module which lives under the jdk.incubtor namespace. But the HTTP client API supports the latest communication standards, while overcoming the shortcomings of the HttpURLConnection API.

Stack-Walking API

While writing Java code, programmers explore ways to access and filter stack trances efficiently. The latest version of Java simplifies stack walking by providing the Stack-Walking API. The new API makes it easier for programmers to access and filter stack trace information. It further supports both short and long walks. Hence, it becomes easier for programmers to access and filter the entire stack without relying on the virtual machine to capture the stack information.

Datagram Transport Layer Security (DTLS) API

Java 9 helps developers to build secure applications by providing an API for Datagram Transport Layer Security (DTLS). The API keeps client and server communication secure by eliminating chances of data tampering, message forgery, and eavesdropping. Also, it provides communication privacy to a variety of applications that use Datagram Transport Protocol (DTP). Despite being developed based on Transport Layer Security (TLS), DTLS implements SSL protocol.

Improved Process API

Often Java programmers find it daunting to control and manage operating system processes. The Process API provided by earlier version of developers to access the native code and write additional code. But the improved Process API provided by Java 9 makes it easier for programmers to control and mange operating system processes. They can use the API to make a Java application interact with the operating system directly. Also, they can take advantage of the new methods to handle process names and states without writing additional code.

Deprecated Features

Despite providing several new features, Java 9 does not support some of the features provided by Java 8. For instance, it no longer supports Applet API. The Java web developers have to switch from Applet API to Java Web Start to launch applications from web browsers. Likewise, Java 8 speeds up development of garbage collectors in HotSpot virtual machine by deprecating Concurrent Mark Sweep (CMS) garbage collectors. While using the most recent version of Java, programmers also lack option to receive Java warnings on import statements and select JRE at launch time.

On the whole, Java 9 comes with several new features to simplify development of applications for both large and small devices. However, some of the binaries and source introduced by Java 9 are not compatible with earlier versions of the programming language. The programmers even have to make several changes to the code and upgrade libraries while migrating existing applications to Java 9. But the developers must consider upgrading their existing applications to Java 9 to take advantage of these new features and enhancements. Java developers also should use these highly recommended tools for better programming.

Things About Online Payment Solution

How to choose an Online Payment Solution and our choice

The payment provider is chosen based on many different criteria. Some of these are the service availability in the country where your bank account is, costs of a transaction, monthly fees, the costs of integration, and whether it resolves sales tax issues or allows for integration with some other well-known payment solutions. Many of these questions must be answered by You the client. Stripe is our preferred choice as it had excellent API capabilities. This article will use Stripe as its payment processor of choice.

Best Practices for payment providers

Retry if transaction did not succeeded
The transaction might fail not only due to technical reasons but sometimes insufficient funds might be the reason. You should retry processing the transaction between an hour to couple of days later.

Know when your CC will expire
Some of the card details will expire or their data will no longer be valid for various reasons. When you do not have valid CC data charging the customer will not be possible. The major card schemes offer a service that lets you check if there are any updates pending for the customer data that you store. Some of the online payment solutions will even update card information for you. Stripe will do this for the majority of MasterCard, Discover, and Visa cards. Not only CC.

Be aware that in some parts of the world people are not willing to pay with their Credit Card
The best example of this is China when Alipay is the main payment source. It is worth noting that not all clients are happy giving away their card details so using a well-known payment method helps to increase the completion rate of potential transactions. Stripe also supports Alipay for China and for Europe Giropay, iDEAL

We would like to have PayPal
Sometimes clients just want to use PayPal as they are familiar with the brand. Don’t be stubborn – Stripe will help to maximize your profit. Stripe and Paypal are direct competitors there is no integration between them.

Best practices while using the Stripe payment process

PCI compliance with Stripe

Most users become PCI compliant by filling in the Self-Assessment Questionnaire (SAQ) provided by the PCI Security Standards Council. The type of SAQ depends on how you collect card data. The simplest method of PCI validation is SAQ A. The fastest way to become PCI compliant with Stripe is to make sure you qualify for a prefilled SEQ A. If so Stripe will fill the SEQ A for you and will make it available for you to download to your account’s compliance settings after the first 20 or so transactions. The way to achieve this is as follows:

– Use the Embedded form called Checkout, Stripe.js and Elements (it offers better layout customization then Checkout). You can use react-stripe-elements which uses Stripe.js API or Stripe mobile SDK libraries. When you’re using react-native go with tipsi-stripe. ipsi-stripe bindings are not officially supported by Stripe so support will not officially tell you that they qualify for prefilled SEQ-A compliance – but they do.

– If you are using web serve your payments pages should use HTTPS.

In all those cases data is securely transmitted directly to Stripe without it passing through your servers. When you choose the fastest way you will not have to do anything more. It is as simple as this until you reach 6 million transactions per year then you will have to fill a Report on Compliance to validate your PCI compliance annually.

Prepare for technical failure – Idempotency key
If you are using API to take payments you must prepare for a technical failure as all networks are unreliable. If failure happens wit is not always possible to know if a charge was made or not. In the case of a network failure you should retry the transaction. The Idempotency key is a prevention mechanism against charging a customer twice. If for some reason you submitted the payment twice – which may occur due to retrying operations after a failure. In Stripes node lib you just add it to options parameter while charging. Each Idempotency key will time out after 24 hours so after that time if you make a payment with the same Idempotency key you will charge the client.

Stripe charges in cents not dollars
Online payment solutions like PayPal charge in dollars rather than cents. But that in Stripes all charges are made in smallest currency unit. This is not only the case regarding dollars, Stripes does it for all currencies.

Test

Stripe provides many card numbers for you to test different scenarios on the frontend and tokens so you could directly test your backend. For example you can not only test Visa, Mastercard, American Express, Discover, Diners Club and JCB Cards but also international cards and 3D Secure Cards. Stripe also provides you with tokens so you can test failure scenarios like a charge being declined, or a charge being blocked because its fraudulent, an expired card, or a processing error. So you will be prepared for everything that can happen when you go live.

Do not put JSON in description – Use metadata

Be descriptive as you can. Metadata is your friend. You can enrich your Stripe transaction with custom data so you can then view it in the dashboard. For example you can add things like customer_id or the shipping_id in metadata so there is no reason to pollute your transaction description.

Should I collect more data?

The bare minimum to collect from a CC is its number, CVV and expiry date but you can collect more. You can also collect the zip code / CC holder name / address for Address Verification System (AVS). If you collect them it will increase payment security because the fraud prevention algorithms will have more data and will be able to react more accurately. However, from the user perspective it’s more data to type – which is not always good. Customers are only human and sometimes make mistakes when entering data which can also cause some transactions to be rejected. So you must decide on how much data you need and what will work best for you and your income. Equally banks will sometimes reject payments with a ‘do not honor’ status and you will have to contact your customer so they can ask their bank about the reason (high level of recent activity on a card, a lack of matching AVS information, a card being over its limit, or a range of other reasons which only the bank will know).

A Stripe Payout Example

Collecting CC data – (tokenization explanation and an example)

For collecting CC data we can use Checkout, Stripe.js elements lib, react Stripe elements lib which utilizes Stripe js, mobile libs, and react native tipisi-stripe. Checkout offers a selection of forms to collect data with, while other methods require you to craft your own custom form. The process of safely collecting CC data using a payment provider is called tokenization as we are exchanging all the sensitive data for a short-lived data token. And that is all that tokenization is about. This token can later be used for making a one-time charge of a customer or for creating a customer (See section below). The following example will focus on the simplest method of tokenization called Checkout. When using checkout we have two options, either simple and custom. Let’s look into the code.

Checkout simple option
In checkout simple option everything is provided for you from a selection of options. All you need to do is to embed the following code into your webpage:

Now let’s see what we can do with the token on the backend

Charging the customer – an example
The token goes on the backend. Let’s use node to create a customer and then charge them based on a returned customer id for when the need arises.

import stripeModule from ‘stripe’;
import config from ‘../config/config’;
import logger from ‘../log’;

class StripeService {
constructor() {
const { stripe } = config();
this.stripe = stripeModule(stripe.secretKey);
}

createCustomer(stripeToken, email) {
logger.info(`creating customer ${email}`);
return this.stripe.customers.create({
email,
source: stripeToken,
});
}

This will return the token but remember to handle the errors that arise. If response succeeds just look for id that belongs to the customer and save it for later use. You will use the customer id to charge the user. Let’s see how to do this:

chargeCustomer(customerId, amount, desc, idempotencyKey) {
return this.stripe.charges.create({
amount,
currency: ‘usd’,
customer: customerId,
description: desc,
}, {
idempotency_key: idempotencyKey,
});
}

Is that all? Yes but please remember about being prepared for failures and retries when needed.

Signing up to events – an example

Stripe can update the client CC if it is expired and this works for most MasterCard, Discover, and Visa cards. How is that possible?- Stripe works with card networks and automatically tries to update card details whenever a customer receives a new card. When the card information is updated you will receive a webhook with an event as follows: “customer.source.updated.” You can also sign up to be informed before an expiration date with the event “customer.source.expiring.” Webhook is a general way to sign up to various events that will be produced by Stripe. You will be called by them in a push manner so you don’t have to pull for information and all you have to do is expose a webhook. If you are only interested in card payments when using Stripe webhooks are not required. Webhooks are configured in the webhooks settings section of the Dashboard, where you can add a new URL for receiving webhooks. Logic for webhook should be idempotent and the webhook signature should be verified.

import stripeModule from ‘stripe’;
import express from ‘express’;
import bodyParser from ‘body-parser’;

const STRIPE_SECRET_KEY = ‘sk_test_your_key_here’;
const WEBHOOK_SECRET = ‘whsec_your_key_here’

const stripe = stripeModule(STRIPE_SECRET_KEY);

const app = express();

app.use(require(“body-parser”).raw({type: “*/*”}));

// this will be called by stripe
app.post(‘/webhook/test’, (req, res) => {
const signature = req.headers[‘stripe-signature’];
const event = stripe.webhooks.constructEvent(req.body, signature, WEBHOOK_SECRET);

// Process the event – make sure your indempotent
if(eventWasNotProcessed(event)) {
handleEvent(event);
}

res.json({received: true});
});

app.listen(8000, () => console.log(“Running on port 8000”));

Other Stripe capabilities

Stripe services are not only limited to the Payments services that we have looked at this article. Stripe also offers:

– Subscriptions: To charge customers on a recurring basics. Stripe has several plans for each customer including discounts
– Connect: A solution to use when you serve as a platform between clients and sellers. With this solution you can transfer money from/to your clients and sellers.
– Sigma: A feature for writing custom reports that will be available in your dashboard. This is done by writing ANSI SQL queries against Stripe schema. You can also use scheduled queries to further automate things – results will be sent as webhook events or via email. Just be aware that using sigma is not free and it generates additional costs.
– Radar – A fraud protection machine learning system. You can use it when you have integrated with Checkout, Stripe.js, Elements, and mobile SDK integrations (tipisi-stripe will also work here).

Summing up

With this knowledge you can process your first payments. When choosing Stripe remember that you are responsible for your own PCI compliance after the first 6 million transactions.