Category Archives: Java

Springboot MongoDB Repository – Code Example

This blog represents code required to create a Spring boot application that uses Spring Data MongoRepository interface to connect with MongoDB database. Step 1: Create a Springboot Maven project Create a new Spring Starter Project using Eclipse IDE. This would create a class annotated with @SpringBootAnnotation. Step 2: Include Spring Data Mongo support in pom.xml Step 3: Configure Mongoclient for database connectivity Create a Configuration class which is used to instantiate a MongoClient for connecting with MongoDB database. Step 3: Define MongoDB details in application.properties Step 4: Invoke MongoRepository instance Place following code in SpringBootAnnotation class for invoking MongoRepository instance (UserDAO in the code given below). In ideal scenario, you would want …

Continue reading

Posted in Java, MongoDB, NoSQL. Tagged with , , .

Spring Boot Web Application with Eclipse in 5 Clicks

This article represents tips and code samples to get you started quickly with Spring web application within few clicks. Please feel free to comment/suggest if I missed mentioning one or more important points. Also, sorry for the typos. Steps to get started with Spring Boot Web Application Go to Help > Eclipse Marketplace… and search type “spring sts” in Find text field under Search tab. Install the entry with the title such as “Spring Tool Suite (STS) for Eclipse Release”. Once installed, you would be asked to restart the Eclipse. Go ahead and restart the eclipse. Open the new Project selector window using shortcut, CTRL + N. Type “Spring Starter” …

Continue reading

Posted in Java, Web. Tagged with .

Java – How to Fix java.lang.NoClassDefFoundError?

This article represents tips on How to Fix java.lang.NoClassDefFoundError when compiling a particular Java file. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Following are the key points described later in this article: How to reproduce java.lang.NoClassDefFoundError? Why does the java.lang.NoClassDefFoundError occur in the first place? How to Fix the Error? How to reproduce java.lang.NoClassDefFoundError? Take a look at following Class file. package com.test; public class HelloWorld { public static void main(String[] args) { System.out.println(“Hello World! How are you?”); } } Following are steps to reproduce the java.lang.NoClassDefFoundError. Save the above file as HelloWorld.java within any folder. Compile …

Continue reading

Posted in Java. Tagged with .

Java – How to Fix java.lang.UnsupportedClassVersionError Error?

This article represents tips on how to fix Java error such as UnsupportedClassVersionError. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. How to Reproduce the Error? Set the JAVA_HOME with one version of Java. And, include “bin” of different Java version in PATH variable. Compile the class, say, HelloWorld.java with “javac” command Start the JVM with following class: “java HelloWorld” With above, you could see error such as following: java.lang.UnsupportedClassVersionError: HelloWorld : Unsupported major.minor ver sion 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(Unknown Source) at java.security.SecureClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.defineClass(Unknown Source) at java.net.URLClassLoader.access$100(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) …

Continue reading

Posted in Java. Tagged with , .

Java – How to Calculate Size of Objects & Arrays

This article represents a list of web pages which can help one understand the memory usage of Java objects and arrays along with examples. Please feel free to comment/suggest any other cool pages. Also, sorry for the typos. The in-memory size of the object depends on the architecture, mainly on whether the VM is 32 or 64-bit. The actual VM implementation also matters. How to calculate memory usage of a Java object?: Very simplified explanation of how one could calculate a memory of any Java object. For example, lets say, you want to calculate the memory of a Java object which holds two int variables, one boolean variable, one Long object, …

Continue reading

Posted in Java, Web. Tagged with .

How to Dockerize Springboot Web App

This blog represents instructions and code samples on how to Dockerize a Springboot Web app. The source code be found from this git repository. Following are key aspects of this blog: Dockerfile & image Install the image Run the container and access the app Dockerfile & Image Download the code from this page and put them all in a folder. Before we go one to create the image, lets know a little more about the Dockerfile. Following points need to be noted in the Dockerfile: The image created is a Centos6 image The Java is installed in a predefined path “/opt/jdk” Then, Maven is installed and JAVA_HOME is set. The source …

Continue reading

Posted in Dockers, Java. Tagged with , .

Java Code Sample to Access Firebase Data

This article represents Java code sample which can be used to access Firebase database. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Pre-requisite for Firebase Database Access It is recommended to not allow anyone to access Firebase database without any kind of authentication. The minimum that could be done is enable “Anonymous Authentication” by logging in Firebase console. Java Code Sample for Firebase Database Access In the code below, note some of the following: Code for anonymous authentication Code for accessing a user object based on a given userId Firebase firebase = new Firebase(“https://dbname.firebaseio.com/”); firebase.authAnonymously(new Firebase.AuthResultHandler() { @Override …

Continue reading

Posted in Java, Web. Tagged with , .

Liskov Substitution Principle with Java Code Examples

This article describes what is Liskov Substitution Principle along with code examples in Java. Please feel free to comment/suggest if I missed mentioning one or more important points. Also, sorry for the typos. In this post, you will learn some of the following: What is Liskov Substitution Principle (LSP)? Code Samples to Illustrate LSP What is code quality characteristic that represents by LSP? You may also want to check another code quality principle such as Single Responsibility Principle explained with Java Examples. What is Liskov Substitution Principle (LSP)? Take a look at this paper on Liskov Substitution Principle which provides great details on Liskov Substitution Principle. As per LSP, functions …

Continue reading

Posted in Java, Programming, Software Quality. Tagged with , .

Springboot Web Hello World with a Java & Pom.xml file

This blog presents instructions on how to quickly get started with Springboot Hello World with just one Java file and a Pom.xml. Before getting set up with files, make sure you have installed and configured following Java; Setup Java_Home as it is required by maven Maven; Maven would be used to package our app.   Java Code Sample Following is the code for Java file. Make sure to create hello/HelloController.java file within src/main/java. This is required for maven to package it correctly. package hello; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.*; import org.springframework.web.bind.annotation.*; @RestController @SpringBootApplication public class HelloController { @RequestMapping(“/”) String home() { return “Hello World!”; } public static …

Continue reading

Posted in Java, Web. Tagged with .

How to Upload CSV Files using Apache FileUpload/CSV

This article represents code samples on how to use Apache Commons FileUpload and Apache Commons CSV libraries to upload CSV file using Java Servlet. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.   Code Samples – Java Code Following is the code for Java Servlet. package com.vitalflux.core; import java.io.IOException; import java.io.StringReader; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVRecord; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class FileIOController extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (ServletFileUpload.isMultipartContent(request)) …

Continue reading

Posted in Java. Tagged with .

Java – How to Download Existing Google App Engine Project

This article represents tips on how to download existing google app engine project including its source code (HTML/JSP files).. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Following are steps that need to be taken: Make sure you have JDK installed. Access this page for downloading Java Download Google App Engine SDK for Java. The download file could be found on this page. Unzip the App engine SDK and go to the bin folder using command prompt. Go to your http://appengine.google.com account and get the information such as your app_name and your_app_version. On Windows, execute the command as …

Continue reading

Posted in Java, Web. Tagged with .

Docker – Quick Java 8 or Java 7 Dev Environment with Dockers

This article represents code samples which could be used to build and start Java 7 or Java 8 Docker containers appropriately based on the needs with a single script and command such as “./startJava.sh -v 7 Java7” for Java 7 and “./startJava.sh -v 8 java8” for Java 8. This would be useful to try and test your Java code against Java 7 and Java 8 versions very easily based on the fact that you could start both Java7 and Java8 containers simultaneously and, run your code in these containers at the same time for testing. Please feel free to comment/suggest if I missed to mention one or more important points. …

Continue reading

Posted in DevOps, Dockers, Java, Web. Tagged with , , .

Dockers – How to Get Started with Java8 Dev Environment

This article represents take away code samples and tips on how to setup Java8 container using Dockers and get started. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Following are the key points described later in this article: Java 8 Image Dockerfile Install Scripts to Install and Start Java8 Env   Java 8 Image Dockerfile Following is Dockerfile for creating Java8 image. Name the file as java8_base.df. # Base is the Centos environment FROM centos:centos6 # Make the directories under which Java 8 will get installed RUN mkdir /opt/jdk RUN cd /opt # Install wget and tar which …

Continue reading

Posted in DevOps, Dockers, Java. Tagged with , , .

Java – How to Migrate from JRockit to HotSpot JVM

This article represents information on migration from JRockit to HotSpot JVM. Recently, the migration guide from JRockit JVM to HotSpot JVM has been published. The information about the same can be found on this page. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. The detailed information could be found on this page. Following are top 5 areas where changes need to be made for migrating from JRockit JVM to HotSpot JVM. Tuning garbage collection. One could also access HotSpot GC tuning guide on following page. Java runtime options Java compilation optimization Logging: There are parameters related to verbose …

Continue reading

Posted in Java. Tagged with .

Java – How to Get Users Tweets using Twitter HBC Http Client

This article represents code samples which could be used to retrieve users tweets for one or more Twitter users, using Twitter HBC Java client. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Following are the key points described later in this article: Key Steps in Retrieving the Users Tweets Code Sample – Get User Tweets Key Steps in Retrieving the Users Tweets Following are key steps required to be taken to retrieve users tweets: Get consumer key and access tokens details Determine userId for users for whom you want to get the tweets as they appear. For test …

Continue reading

Posted in Java, Web. Tagged with .

Java – How to Get Started with Twitter HBC Streaming API

This article represents instructions on how to get started with HBC, A Java HTTP client, for consuming Twitter’s Streaming API. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos. Following are the key points described later in this article: How to get Twitter Consumer/Access Token Keys Instructions to Get Started with HBC How to get Twitter Consumer/Access Token Keys Before getting started with HBC API for integrating with Twitter API, make sure that you have acquired following four details from Twitter: Consumer Key Consumer Secret Access Token Access Secret Token All of the above keys could be started from …

Continue reading

Posted in Java, Web. Tagged with , .