Tuesday, October 10, 2017

Spring Boot - Hello World Standalone Application



Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run". We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
Features
  • Create stand-alone Spring applications
  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
  • Provide opinionated 'starter' POMs to simplify your Maven configuration
  • Automatically configure Spring whenever possible
  • Provide production-ready features such as metrics, health checks and externalized configuration
  • Absolutely no code generation and 
  • no requirement for XML configuration

For this project, we are going to use:
  • Eclipse IDE
  • Java 8
  • Maven
Open your Eclipse IDE and create a NEW Java Project. 
Once your Java project is created, right click on it -> Configure -> Convert to Maven..

This will "MAVENize" our newly created Java project.

Next steps:

Under 'src' folder create a package for our source files: 'com.rolandoFebrero.SpringBootQuickStart'

Now copy the next code snippet in the POM.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.javainterviewpoint</groupId>
 <artifactId>SpringBootTutorial</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <parent>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-parent</artifactId>
   <version>1.5.1.RELEASE</version>
 </parent>
 
 <dependencies>
   <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
   </dependency>
 </dependencies>
 
 <build>
  <pluginManagement>
   <plugins>
     <plugin>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-maven-plugin</artifactId>
     </plugin>
   </plugins>
    </pluginManagement>
 </build>  
 
 </project>


If we pay attention to the POM.xml, we can see spring-boot-starter-parent and spring-boot-starter-web. 

spring-boot-starter-parent: It provides useful Maven defaults.
spring-boot-starter-web: This will add additional dependencies such Tomcat, Jackson, Spring boot etc which are required for our application.
Now let's proceed to create a Java class 'HelloWorld.java' under 'com.rolandoFebrero.SpringBootQuickStart' package.

Paste the next code snippet in 'HelloWorld.java'



package com.rolandoFebrero.SpringBootQuickStart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 
 * @author Rolando 'rOLo' Febrero
 * @Project Spring Boot Quick Start by rOlo
 */

@RestController
@EnableAutoConfiguration
public class HelloWorld {

    @RequestMapping("/")
    String hello() {
        return "Hello World! Congratulations, you just created your Spring Boot application";
    }
    
    @RequestMapping("/hello/{name}")
    String helloThere(@PathVariable String name) {
        return "Hello, " + name + "!";
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(HelloWorld.class, args);
    }
}


In 'HelloWorld.java' we are using some annotations needed to tell spring what to do with receiving the request and how to do some configuration. These are:
  • @RestController:  Tells spring to render the result back to the caller.
  • @RequestMapping:  HTTP request with the path “/” should be mapped to the hello() method
  • @EnableAutoConfiguration:  This annotation tells the Spring Boot to configure the application based on the dependencies added. Since spring-boot-starter-web has added Tomcat and Spring MVC, auto-configuration will setup a web based application.

Our main method in 'HelloWorld.java' contains 'SpringApplication.run(HelloWorld.class, args)' . This is needed because Application.run() starts the whole Spring Framework and starts the tomcat server. As you can see we are passing 'HelloWorld.class' as parameter.

If you follow the steps above, your project should lool like this:




At this point we are pretty much done with the code. Now we can run our app. 
Since we are using Maven in our project, let's add the configuration to it. 

Right click on POM.xml -> Run as -> Run Configurations... (Since this is the first time running it, we need to configure how we want to run our project)

In 'Goals' type: spring-boot:run





Click on 'Run'.. you should see something similar in your console: 





 .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2017-09-10 12:04:04.212  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : Starting HelloWorld on ROLO-PC with PID 13016 (D:\EclipseWorkspace\JAVA_PROJECTS\SpringBoot-Example\Spring-Boot-Example\target\classes started by rOLo in D:\EclipseWorkspace\JAVA_PROJECTS\SpringBoot-Example\Spring-Boot-Example)
2017-09-10 12:04:04.212  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : No active profile set, falling back to default profiles: default
2017-09-10 12:04:04.243  INFO 13016 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2b93019c: startup date [Sun Sep 10 12:04:04 EDT 2017]; root of context hierarchy
2017-09-10 12:04:04.727  INFO 13016 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-09-10 12:04:04.773  INFO 13016 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-09-10 12:04:05.145  INFO 13016 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-10 12:04:05.146  INFO 13016 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2017-09-10 12:04:05.146  INFO 13016 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
2017-09-10 12:04:05.228  INFO 13016 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-10 12:04:05.228  INFO 13016 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 985 ms
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-10 12:04:05.350  INFO 13016 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-10 12:04:05.547  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2b93019c: startup date [Sun Sep 10 12:04:04 EDT 2017]; root of context hierarchy
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto java.lang.String com.rolandoFebrero.SpringBootQuickStart.HelloWorld.hello()
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/hello/{name}]}" onto java.lang.String com.rolandoFebrero.SpringBootQuickStart.HelloWorld.helloThere(java.lang.String)
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-10 12:04:05.580  INFO 13016 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-10 12:04:05.611  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.611  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.642  INFO 13016 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-10 12:04:05.722  INFO 13016 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-10 12:04:05.770  INFO 13016 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-10 12:04:05.770  INFO 13016 --- [           main] c.r.SpringBootQuickStart.HelloWorld      : Started HelloWorld in 1.946 seconds (JVM running for 5.474)


Open you browser go to : “http://localhost:8080”

You shoud see: 'Hello World! Congratulations, you just created your Spring Boot application'




Also, if you hit: http://localhost:8080/hello/Rolando (with your name as parameter) you should see :

Hello, Rolando!





You can download the complete project from my GitHub account:

https://github.com/rolando-febrero/Spring-Boot-QuickStart





*NOTE: In case you are trying to start your app and get the next error:


***************************
APPLICATION FAILED TO START
***************************

Description:

The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured.

Action:

Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

it is because the server is still running in the background and doesn't let your app start again using the same port. Basically you just need to stop it and run it again. Using command line :

C:\> netstat -ano | find "8080"

it returns with:
TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       1896

Now just let's kill the process:
C:\> taskkill /F /PID 1896





Programming thought of the day:


  • Moses had the first tablet that could connect to the cloud


Monday, October 2, 2017

Java Garbage Collection, Finalize() and Memory Leaks


Can there be memory leaks in Java?

As a Java-lover, I can say this is the "Million Dollar Question"...

The answer is that it depends on what kind of memory leak you are talking about.
Classic C / C++ memory leaks occur when an application neglects to free or dispose an object when they are done with it, and it leaks. Cyclic references are a sub-case of this where the application has difficulty knowing when to free / dispose, and neglects to do it as a result. Related problems are where the application uses an object after it has been freed, or attempts to free it twice. (You could call the latter problems memory leaks, or just bugs. Either way ... )
Java and other (fully1) managed languages mostly don't suffer from these problems because the GC takes care of freeing objects that are no longer reachable. (Certainly, dangling pointer and double-free problems don't exist, and cycles are not problematic as the are for C / C++ "smart pointers".)
But in some cases GC in Java will miss objects that (from the perspective of the programmer) should be garbage collected. This happens when the GC cannot figure out that an object cannot be reached:
  • The logic / state of the program might be such that the execution paths that would use some variable cannot occur. The developer can see this as obvious, but the GC cannot be sure, and errs on the side of caution (as it is required to).
  • The programmer could be wrong about it, and the GC is avoiding what might otherwise result in a dangling reference.
Well, considering that java uses a garbage collector to collect unused objects, you can't have a dangling pointer. However, you could keep an object in scope for longer than it needs to be, which could be considered a memory leak....


Now let's, be more practical and perform a real test to see how the Java Garbage Collection works.

As we know (hope you do), the Finalize() is invoked right before an object is garbage collected, so, to demonstrate how this works we might need to create objects and wait for them to be 'garbage collected'.


On your favorite IDE, copy / paste the next code snippet: 



package com.rolandoFebreroo.GarbageCollection;

public class GarbageCollection {
    public static void main(String args[]) {
        for (int i = 0; i < 10; i ++) {
            new MyObject();
        }
    }
}
class MyObject {
 MyObject() {
        super();
        System.out.println("Object reference is located on the heap at: " + this);
    }
    protected void finalize() { 
        System.out.println("!!!You have been Finalized, baby...!!! " + this );
    }
}


As we can see, there is a simple for loop used to create 10 MyObject objects. The output is:



Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@15db9742
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@6d06d69c
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@7852e922
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@4e25154f
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@70dea4e
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@5c647e05
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@33909752
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@55f96302
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3d4eac69
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@42a57993


Still we are not able to see how the Garbage Collector works, and if we run the same code again, we are going to get the exact same memory address for the newly created objects.
How come we didn't see the the finalize() method execute? Finalize() is not called when an object is no longer in scope, finalize is called just prior to garbage collection. Because of this, your program should utilize other methods of executing statements that need to be run before the object is destroyed. Things like closing file handles, freeing up resources, etc., should not depend on finalize() for normal program execution.

We have no way of knowing when the garbage collector is going to run. In this case, the garbage collector ran sometime after the completion of my main method, so the string literal "!!!!You have been Finalized, baby...!!!" could not be displayed to the console.

In order to demonstrate the finalize() method, I will make an infinite loop that creates an object on every iteration. Hopefully, we will see some "!!!You have been Finalized, baby...!!! " roll across the console.


For this purpose, just modify the for loop and increment the value from 'i<10' to 'i<100000'

for (int i = 0; i < 100000; i ++)



Now, Let's run the code again, but this time you should get an output similar to this:



!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@2314cd97
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@5af56240
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@2212e291
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@5d75f90e
!!!You have been Finalized, baby...!!! com.rolandoFebreroo.GarbageCollection.MyObject@31b91435
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@6ae9b2f0
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3f1870bc
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@3993c2be
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@55b0c0a6
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@726986d2
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@e0895b3
Object reference is located on the heap at: com.rolandoFebreroo.GarbageCollection.MyObject@29a920fe


What happened here is that when we incremented the For loop, we starting creating objects on the heap memory, and eventually the Garbage Collector would wake up and start doing its job, and that is when the Finalize() is invoked and we see it in the above output.

This was just a simple exercise to understand how Java Garbage Collection works. Just remember that since Finalize() is only called right before an object is garbage collected, and this might or might not happen during the execution of your program, you shouldn't place any code that NEEDS to be executed in the Finalize().






Programming thought of the day:
  • Wikipedia: I know everything! 
  •  Google: I have everything! 
  •  Facebook: I know everybody! 
  •  Internet: Without me you are nothing! 
  • Electricity: Keep talking bitches!


Wednesday, July 26, 2017

Using JDBC in our Java code


Creating JDBC Application


Today I'm going to explain a really basic example about using JDBC in our java code. 

First of all, we have to create the data we need to extract from our DB. 

Create the table Employee as follows:

mysql> use EMP;
mysql> create table Employees
    -> (
    -> id int not null,
    -> age int not null,
    -> first varchar (255),
    -> last varchar (255)
    -> );
Query OK, 0 rows affected (0.08 sec)
mysql>

Create Data Records

Finally you create few records in Employee table as follows:

mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
Query OK, 1 row affected (0.05 sec)

mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)

mysql>

There are following six steps involved in building a JDBC application −
  • Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.
  • Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.
  • Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.
  • Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database.
  • Extract data from result set: Requires that you use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.
  • Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

Sample Code

This sample example can serve as a template when you need to create your own JDBC application in the future.

Copy and paste the following example in FirstExample.java, compile and run as follows:

//STEP 1. Import required packages
import java.sql.*;

public class FirstExample {
   // JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/EMP";

   //  Database credentials
   static final String USER = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      String sql;
      sql = "SELECT id, first, last, age FROM Employees";
      ResultSet rs = stmt.executeQuery(sql);

      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      //STEP 6: Clean-up environment
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
}//end main
}//end FirstExample

Now let us compile the above example as follows:

C:\>javac FirstExample.java
C:\>

When you run FirstExample, it produces the following result:

C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>






Programming thought of the day:
  • Q: What do you call the security outside of a Samsung Store? 
  • A: Guardians of the Galaxy.