Today I had to implement a functionality related to sending Outlook Calendar invite. The app backend was written in Java. As it turns out the simple task of sending a calendar invite is much more complicated than I expected. You have to construct the message with all the right parameters set else your calendar invite will not behave as you expect. I wasted an hour or two figuring out why RSVP buttons are not coming in the invite. As it turned out it was one of the missing parameters that caused the issue. Also, I wanted to send calendar invite to both outlook and Google calendar.
Continue reading “Sending Outlook Calendar Invite using Java Mail API”Tag: java
Markov chains in Java: Suggest what Narendra Modi will say using Markov chains
Recently, I read an article[1] on Markov chains. In the post, author showed how we can build autocomplete functionality using them. The article piqued my interest to learn more about Markov chain and I started looking for an example application that I can build using it. I decided to build a web application that will suggest me what Indian prime minister Narendra Modi[2] will say after a word/pair of words/triplet for words.
I am not a supporter of Narendra Modi style of leadership. The reason I chose him is because I could easily find text of all his speeches on the web [3].
This post is divided into three sections:
- What is Markov chain?
- Create dataset for the application
- Build the application that uses Markov chain
Continue reading “Markov chains in Java: Suggest what Narendra Modi will say using Markov chains”
Enabling Https for local Spring Boot development with mkcert
Today, I discovered mkcert – a tool that generates valid TLS certificate. It works for any hostname or IP, including localhost. In this post, I will show you how to generate a valid PKCS12 format certificate using mkcert. Then, we will use that certificate in a Spring boot application.
We will start by installing mkcert on our local machine. If you are using Mac then we can use brew
package manager. For installation instructions specific to your OS you can refer to the documentation.
brew install mkcert
Once mkcert
is installed, you can use its CLI to create and install a CA. To do that, run the following command.
mkcert -install
Continue reading “Enabling Https for local Spring Boot development with mkcert”
Running Tests and Building React applications with Gradle Build Tool
In this short post, I will show you how you can integrate React applications created using create-react-app
with Gradle build tool. We will cover how to build and run the tests as part of the Gradle build.
Continue reading “Running Tests and Building React applications with Gradle Build Tool”
Introduction to Micronaut – A new JVM framework
Recently, I discovered a new framework in Java land called Micronaut. Being a Java developer for last fourteen years, I have seen many Java frameworks come and go. Apart from Spring, there are very few frameworks that made a mark. After a long time, I discovered a framework that is challenging the status quo of web development in Java.
Micronaut is an open-source modern JVM framework for building modular, easily testable microservice and serverless applications. It is a truly polyglot framework. You can build applications in Java, Kotlin, and Groovy.
Continue reading “Introduction to Micronaut – A new JVM framework”
Taking Java heap dump programmatically
The following code snippet can be used to take heap dump of Java program programmatically.
import java.io.File; import java.io.IOException; import java.lang.management.ManagementFactory; import javax.management.MBeanServer; import com.sun.management.HotSpotDiagnosticMXBean; public abstract class HeapDumper { private static final HotSpotDiagnosticMXBean HOT_SPOT_DIAGNOSTIC_MX_BEAN = getHotspotDiagnosticMxBean(); private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; private static HotSpotDiagnosticMXBean getHotspotDiagnosticMxBean() { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { return ManagementFactory.newPlatformMXBeanProxy( server, HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class); } catch (IOException error) { throw new RuntimeException("failed getting Hotspot Diagnostic MX bean", error); } } public static void createHeapDump(File file, boolean live) { try { HOT_SPOT_DIAGNOSTIC_MX_BEAN.dumpHeap(file.getAbsolutePath(), live); } catch (IOException e) { throw new RuntimeException(e); } } }
TIL #7: Java Lambda Puzzler
Today, a colleague asked me how they can pass a java.util.Stream
to a function that accept an java.lang.Iterable
.
Let’s suppose we have a following function that accepts an Iterable
.
public static void doSth(Iterable<String> iterable){ iterable.forEach(System.out::println); }
The calling function has a Stream that it want to pass to the doSth
function.
public static void main(String[] args) throws IOException { Stream<String> lines = Files.lines(Paths.get("src", "main", "resources", "names.txt")); }
One way we could easily achieve this is by collecting the Stream into a Collection like List. As List is an Iterable so we can pass it. This is should below
Stream<String> lines = Files.lines(Paths.get("src", "main", "resources", "names.txt")); doSth(lines.collect(Collectors.toList()));
This works but what if Stream is big and collecting into an in-memory data structure like List leads to java.lang.OutOfMemoryError: Java heap space
.
I googled around and found a nice Lambda hack.
Stream<String> lines = Files.lines(Paths.get("src", "main", "resources", "names.txt")); doSth(lines::iterator);
I have worked a lot on Java 8 but first time I looked at it I couldn’t figure out how it works. If you know Java 8, give it a shot.
The magic here is that Iterable interface has a single abstract method iterator
.
public interface Iterable<T> { Iterator<T> iterator(); }
This means we can write it as following Lambda function.
Iterable<T> iterable = () -> iterator();
In our case, Stream has an iterator method. So, we can convert Stream to Iterable by defining a lambda function as shown below.
Stream<String> lines = Files.lines(Paths.get("src", "main", "resources", "names.txt")); doSth(() -> lines.iterator());
You can refactor the Lambda to a method reference.
Stream<String> lines = Files.lines(Paths.get("src", "main", "resources", "names.txt")); doSth(lines::iterator);
Can we use () -> iterator() in the for-each loop
I wondered if we can use the lambda expression in the for-each loop
for (String str : () -> lines.iterator()) { System.out.println(str); }
This looks like a valid use case. As for-each loop works with types that implement Iterable
interface. But, it turns out the code does not compile. It gives Lambda expression not implemented here
error.
The answer for this is mentioned in the JSR335
Deciding what contexts are allowed to support poly expressions is driven in large part by the practical need for such features: The expression in an enhanced for loop is not in a poly context because, as the construct is currently defined, it is as if the expression were a receiver: exp.iterator() (or, in the array case, exp[i]). It is plausible that an Iterator could be wrapped as an Iterable in a for loop via a lambda expression (for (String s : () -> stringIterator)), but this doesn't mesh very well with the semantics of Iterable.
Another Interesting thing to note is that Iterable is not marked as @FunctionalInterface
. I don’t know the exact reason why Iterable is not marked as @FunctionalInterface
. My guess is that because Iterable has special semantics in Java so they didn’t explicitly marked it @FunctionalInterface
.
Programmatically Generating Database Schema with Hibernate 5
Today, I was working with a code base that was using Hibernate‘s schema generation facilities to create the database schema for a customer on the fly. The application creates separate database schema for each customer. Then, depending on the client specific identifier it connects to the correct database. This blog will not talk about how you should design your application with multi tenant database. I will cover that in a future post. In this post, I will share the code snippet that helped me generate database schema with Hibernate 5. In this post, I am using MySQL database as an example. The same code snippet should also work with other RDBMS as well.
Continue reading “Programmatically Generating Database Schema with Hibernate 5”
Realtime People Counter with Google’s Cloud Vision API and RxJava
Welcome to the ninth blog of 52 Technologies in 2016 blog series. Recently, Google released Cloud Vision API that enables developers to incorporate image recognition in their applications. Image Recognition allow developers to build applications that can understand content of images. Google’s Cloud Vision API is very powerful and support following features:
- Image categorization: The API can help classify images into categories. You can build powerful applications like Google Photos that do automatic categorization.
- Inappropriate content detection: The API can detect inappropriate content in an image like nudity, violence, etc. It uses Google Safe search capabilities underneath.
- Emotion detection: This allows you to detect happy, sad or moderate emotions in an image.
- Retrieve text from the image: This allows you to extract text in multiple languages from the images.
- Logo detection: It can help you identify product logos within an image.
There are many possible applications that you can build using this powerful API. In this tutorial, we will learn how to build a realtime people counter. The application will subscribe to a twitter stream for a topic and would return number of people found in each image. We can then use this data to get advanced statistic like number of people in a time frame using RxJava buffer capabilities.
You can read full blog https://github.com/shekhargulati/52-technologies-in-2016/blob/master/09-cloudvision/README.md
Day 5 — Default and static interface methods in Java 8
We all understand that we should code to interfaces. Interfaces give client a contract which they should use without relying on the implementation details(i.e. classes). Hence, promoting loose coupling. Designing clean interfaces is one of the most important aspect of API design. One of the SOLID principle Interface segregation talks about designing smaller client-specific interfaces instead of designing one general purpose interface. Interface design is the key to clean and effective API’s for your libraries and applications. Continue reading “Day 5 — Default and static interface methods in Java 8”