Thursday, 12 July 2018

How to check whether given character is part of Java identifier variable name or not?

'java.lang.Character' class provides 'isJavaIdentifierPart' method to check whether given character is part of a valid java identifier (other than first character of the identifier name) or not.

A character can be part of java identifier, if any of the following conditions are true.

a.   it is a letter
b.   it is a currency symbol (such as '$')
c.   it is a connecting punctuation character (such as '_')
d.   it is a digit
e.   it is a numeric letter (such as a Roman numeral character)
f.    it is a combining mark
g.   it is a non-spacing mark
h.   isIdentifierIgnorable returns true for the character

'isJavaIdentifierPart' method is available in below overloaded forms.

public static boolean isJavaIdentifierPart(char ch)
public static boolean isJavaIdentifierPart(int codePoint)
First version of the 'isJavaIdentifierPart' method do not support supplementary characters. Characters whose code points are greater than U+FFFF are called supplementary characters.


Find the below working application.

Test.java

package com.sample.app;

public class Test {

 public static void main(String args[]) {

  System.out.println("Is '@' valid identifier ?" + Character.isJavaIdentifierPart('@'));
  System.out.println("Is '_' valid identifier ?" + Character.isJavaIdentifierPart('_'));
  System.out.println("Is '9' valid identifier ?" + Character.isJavaIdentifierPart('9'));

 }
}

Output

Is '@' valid identifier ?false
Is '_' valid identifier ?true
Is '9' valid identifier ?true

Note:
If you want to check whether an identifier can start with given character or not by using below methods provided by 'java.lang.Character' class.

public static boolean isJavaIdentifierStart(char ch)
public static boolean isJavaIdentifierStart(int codePoint)

You may like



Wednesday, 11 July 2018

Java: Dynamic proxies

Proxies are used to achieve below things.
a.   Control access to the object
b.   Remove the overhead of cross cutting concerns.

In any typical enterprise application authentication, logging, database connection etc., are compulsory and these are implemented or used by almost all the service classes. By using dynamic proxies, we can get rid of the duplication of cross cutting concerns.

What is Dynamic Proxy?
A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

For example, as you see below image, the calls to actual object are done via InvocationHandler.




Let me explain with an example.

How to create a proxy object?
'java.lang.reflect.Procy' class is used to create a proxy of an object.

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)
Returns an instance of a proxy class for the specified interfaces

Example
ArithmeticServiceImpl arthObj = new ArithmeticServiceImpl();

ArithmeticService arhServiceProxy = (ArithmeticService) Proxy.newProxyInstance(ArithmeticServiceImpl.class.getClassLoader(), new Class[] { ArithmeticService.class }, new MyInvocationHandler(arthObj));

After running this code, the proxy variable 'arhServiceProxy' contains a dynamic implementation of the ArithmeticService interface. All calls to the arhServiceProxy will be forwarded to the handler implementation of the general InvocationHandler interface.

MyInvocationHandler : Implementation of InvocationHandler interface
All calls to the arhServiceProxy will be forwarded to the invoke() method of MyInvocationHandler class.

Find the below working application.

ArithmeticService.java
package com.sample.app.interfaces;

public interface ArithmeticService {
 public int add(int a, int b);
}

ArithmeticServiceImpl.java

package com.sample.app.interfaces.impl;

import com.sample.app.interfaces.ArithmeticService;

public class ArithmeticServiceImpl implements ArithmeticService {

 @Override
 public int add(int a, int b) {
  System.out.println("Calculating sum of " + a + " and " + b);
  return a + b;
 }

}

MyInvocationHandler.java

package com.sample.app.invocationhandlers;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

public class MyInvocationHandler implements InvocationHandler {

 private Object obj;

 public MyInvocationHandler(Object obj) {
  this.obj = obj;
 }

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  System.out.println(method.getName() + " of " + method.getDeclaringClass() + " is getting executed"
    + " with arguments : " + Arrays.toString(args));

  Object result = method.invoke(obj, args);

  System.out.println(method.getName() + " of " + method.getDeclaringClass() + " execution finished");
  return result;
 }

}

Test.java

package com.sample.app;

import java.lang.reflect.Proxy;

import com.sample.app.interfaces.ArithmeticService;
import com.sample.app.interfaces.impl.ArithmeticServiceImpl;
import com.sample.app.invocationhandlers.MyInvocationHandler;

public class Test {

 public static void main(String args[]) {
  ArithmeticServiceImpl arthObj = new ArithmeticServiceImpl();

  ArithmeticService arhServiceProxy = (ArithmeticService) Proxy.newProxyInstance(ArithmeticServiceImpl.class.getClassLoader(),
    new Class[] { ArithmeticService.class }, new MyInvocationHandler(arthObj));

  int result = arhServiceProxy.add(10, 20);
  System.out.println(result);
 }
}


When you ran Test.java, you can able to see below messages in console.

add of interface com.sample.app.interfaces.ArithmeticService is getting executed with arguments : [10, 20]
Calculating sum of 10 and 20
add of interface com.sample.app.interfaces.ArithmeticService execution finished
30

Let’s enhance above application further like below.

LoggingFilter : Log the information about the method execution
PerformanceFilter: Log the execution time of the method execution


Find the below working application.

Filter.java

package com.sample.app.filters;

public interface Filter {
 
 /**
  * Called before execution of the actual method
  */
 public void beforeExecution();
 
 /**
  * Called after execution of the actual method
  */
 public void afterExecution();

}

LoggingFilter.java

package com.sample.app.filters;

import java.lang.reflect.Method;
import java.util.Arrays;

public class LoggingFilter implements Filter {

 private Method method;
 private Object[] args;

 public LoggingFilter(Method method, Object[] args) {
  this.method = method;
  this.args = args;
 }

 @Override
 public void beforeExecution() {
  System.out.println("Method " + method.getName() + " of " + method.getDeclaringClass() + " is getting executed"
    + " with arguments : " + Arrays.toString(args));
 }

 @Override
 public void afterExecution() {
  System.out.println("Method " + method.getName() + " of " + method.getDeclaringClass() + " execution finished");
 }

}

PerformanceFilter.java

package com.sample.app.filters;

import java.lang.reflect.Method;

public class PerformanceFilter implements Filter {
 private Method method;

 private long startTime;

 public PerformanceFilter(Method method) {
  this.method = method;
 }

 @Override
 public void beforeExecution() {
  startTime = System.nanoTime();
 }

 @Override
 public void afterExecution() {
  System.out.println("Method " + method.getName() + " takes " + (System.nanoTime() - startTime) + " nanoSeconds");
 }

}


ArithmeticService.java

package com.sample.app.interfaces;

public interface ArithmeticService {
 public int add(int a, int b);
}

ArithmeticServiceImpl.java

package com.sample.app.interfaces.impl;

import com.sample.app.interfaces.ArithmeticService;

public class ArithmeticServiceImpl implements ArithmeticService {

 @Override
 public int add(int a, int b) {
  System.out.println("Calculating sum of " + a + " and " + b);
  return a + b;
 }

}

MyInvocationHandler.java

package com.sample.app.invocationhandlers;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.*;

import com.sample.app.filters.Filter;
import com.sample.app.filters.LoggingFilter;
import com.sample.app.filters.PerformanceFilter;

public class MyInvocationHandler implements InvocationHandler {

 private Object obj;
 private boolean loggingFilter = false;
 private boolean perfFilter = false;

 private List<Filter> filters = new ArrayList<>();
 private Method method;
 private Object[] args;

 public MyInvocationHandler(Object obj) {
  this.obj = obj;
 }

 public void addLoggingFilter() {
  loggingFilter = true;
 }

 public void addPerformanceFilter() {
  perfFilter = true;
 }

 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  this.method = method;
  this.args = args;

  addFilters();
  execBeforeFilters();

  Object result = method.invoke(obj, args);
  execAfterFilters();

  return result;
 }

 private void addFilters() {
  if (loggingFilter) {
   filters.add(new LoggingFilter(method, args));
  }

  if (perfFilter) {
   filters.add(new PerformanceFilter(method));
  }

 }

 private void execBeforeFilters() {
  for (int i = 0; i < filters.size(); i++) {
   Filter filter = filters.get(i);
   filter.beforeExecution();
  }
 }

 private void execAfterFilters() {
  for (int i = filters.size() - 1; i > -1; i--) {
   Filter filter = filters.get(i);
   filter.afterExecution();
  }
 }

}


Test.java

package com.sample.app;

import java.lang.reflect.Proxy;

import com.sample.app.interfaces.ArithmeticService;
import com.sample.app.interfaces.impl.ArithmeticServiceImpl;
import com.sample.app.invocationhandlers.MyInvocationHandler;

public class Test {

 public static void main(String args[]) {
  ArithmeticServiceImpl arthObj = new ArithmeticServiceImpl();

  MyInvocationHandler invocationhandler = new MyInvocationHandler(arthObj);
  invocationhandler.addLoggingFilter();
  invocationhandler.addPerformanceFilter();

  ArithmeticService arhServiceProxy = (ArithmeticService) Proxy.newProxyInstance(
    ArithmeticServiceImpl.class.getClassLoader(), new Class[] { ArithmeticService.class },
    invocationhandler);

  int result = arhServiceProxy.add(987654, 201801810);
  System.out.println("Result is : " + result);
 }
}

When you ran Test.java, you can able to see below messages in console.

Method add of interface com.sample.app.interfaces.ArithmeticService is getting executed with arguments : [987654, 201801810]
Calculating sum of 987654 and 201801810
Method add takes 327546 nanoSeconds
Method add of interface com.sample.app.interfaces.ArithmeticService execution finished
Result is : 202789464


Previous                                                 Next                                                 Home

Spring boot: Create an executable jar using maven

In this post, you are going to learn.
a.   How to create a java project using maven
b.   Update pom.xml with spring boot dependencies
c.   Update pom.xml with spring-boot-maven-plugin
d.   Update App.java file
e.   Generate the jar file
f.    Run the jar file

Create a java project using maven
Maven provides number of archetypes to create project skeltons.

For example,
maven-archetype-quickstart : Generate simple maven project.
maven-archetype-j2ee-simple : Generate simple j2ee application.

Open command prompt and execute the command "mvn archetype:generate -DarchetypeArtifactId=maven-archetype-quickstart"

When you execute above command, maven asks groupId, artifactId, version, and package information and create a simple project.

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< org.apache.maven:standalone-pom >-------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] --------------------------------[ pom ]---------------------------------
[INFO]
[INFO] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>>
[INFO]
[INFO] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<<
[INFO]
[INFO]
[INFO] --- maven-archetype-plugin:3.0.1:generate (default-cli) @ standalone-pom ---
[INFO] Generating project in Interactive mode
Define value for property 'groupId': com.selflearningjava
Define value for property 'artifactId': HelloWorld
Define value for property 'version' 1.0-SNAPSHOT: : 1
Define value for property 'package' com.selflearningjava: : com.sample.app
Confirm properties configuration:
groupId: com.selflearningjava
artifactId: HelloWorld
version: 1
package: com.sample.app
 Y: : Y
[INFO] ----------------------------------------------------------------------------
[INFO] Using following parameters for creating project from Old (1.x) Archetype: maven-archetype-quickstart:1.0
[INFO] ----------------------------------------------------------------------------
[INFO] Parameter: basedir, Value: C:\Users\krishna\Documents\Study\Spring Boot\examples\projects
[INFO] Parameter: package, Value: com.sample.app
[INFO] Parameter: groupId, Value: com.selflearningjava
[INFO] Parameter: artifactId, Value: HelloWorld
[INFO] Parameter: packageName, Value: com.sample.app
[INFO] Parameter: version, Value: 1
[INFO] project created from Old (1.x) Archetype in dir: C:\Users\krishna\Documents\Study\Spring Boot\examples\projects\HelloWorld
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:32 min
[INFO] Finished at: 2018-04-20T15:15:53+05:30
[INFO] ------------------------------------------------------------------------
[0m[0m

It creates below project structure.


Maven creates ‘App.java’ file like below.

package com.sample.app;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
    }
}

Step 2: Update pom.xml with spring boot dependencies
Add below dependencies to pom.xml file.

         <parent>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-parent</artifactId>
                  <version>2.0.1.RELEASE</version>
         </parent>

         <dependencies>

                  <dependency>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-starter-web</artifactId>
                  </dependency>

         </dependencies>

Step 3: Update pom.xml with spring-boot-maven-plugin

To create an executable jar, we need to add the spring-boot-maven-plugin to our pom.xml.

<build>
         <plugins>
                  <plugin>
                           <groupId>org.springframework.boot</groupId>
                           <artifactId>spring-boot-maven-plugin</artifactId>
                  </plugin>
         </plugins>
</build>

Final pom.xml looks like below.


pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.selflearningjava</groupId>
  <artifactId>HelloWorld</artifactId>
  <packaging>jar</packaging>
  <version>1</version>
  <name>HelloWorld</name>
  <url>http://maven.apache.org</url>
  
  <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.0.1.RELEASE</version>
  </parent>
 
  <dependencies>
  
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
 
 <dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
 </dependency>

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


Step 4: Update App.java file

App.java

package com.sample.app;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class App 
{
 @RequestMapping("/")
 @ResponseBody
 String home() {
  return "Hello World!";
 }

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

Step 5: Generate the jar file.
Go to the directory where the pom.xml file is located and run the command 'mvn package'.

[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.sample.app.AppTest
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.007 s - in com.sample.app.AppTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- maven-jar-plugin:3.0.2:jar (default-jar) @ HelloWorld ---
[INFO] Building jar: C:\Users\krishna\Documents\Study\Spring Boot\examples\projects\HelloWorld\target\HelloWorld-1.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.0.1.RELEASE:repackage (default) @ HelloWorld ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 14.817 s
[INFO] Finished at: 2018-04-20T15:32:41+05:30
[INFO] ------------------------------------------------------------------------

‘mvn package’ command generates the jar file and place it in target folder.

Step 6: Execute the jar file.
Run the command ‘java -jar HelloWorld-1.jar’.


Once the application started, open the url ‘http://localhost:8080/’ in browser, you can able to see ‘Hello World’ message.




Previous                                                 Next                                                 Home