Monday, 24 July 2017

Working with Whitebox class

WhiteBox is a simplified reflection utility class used to access various internals of a class.


You can perform following actions by using WhiteBox class.


Previous                                                 Next                                                 Home

Saturday, 22 July 2017

Mock instance non-void private methods

In this post, I am going to explain how to mock instance non-void methods. PowerMock class provides 'expectPrivate' method to mock instance private methods.
Following snippet is used to mock the instance non-void private method.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);
String trueStr = "true";
/* Set expectations */
PowerMock.expectPrivate(stringUtil, methodToMock, trueStr).andReturn(true).times(1);

Following is the complete working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = str.toUpperCase();
  boolean isLoggingSuccess = sendStringToLogger(str);

  if (isLoggingSuccess) {
   return upperCase + upperCase;
  }

  return null;

 }

 private boolean sendStringToLogger(String str) {
  throw new MethodNotImplementedException();
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice_sendStringToLogger_trueCheck() throws Exception {
  String methodToMock = "sendStringToLogger";

  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);

  String trueStr = "true";

  /* Set expectations */
  PowerMock.expectPrivate(stringUtil, methodToMock, trueStr).andReturn(true).times(1);

  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice(trueStr);
  assertEquals(result, "TRUETRUE");

  PowerMock.verifyAll();

 }

 @Test
 public void toUpperAndRepeatStringTwice_sendStringToLogger_falseCheck() throws Exception {
  String methodToMock = "sendStringToLogger";

  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);

  String falseStr = "false";

  /* Set expectations */
  PowerMock.expectPrivate(stringUtil, methodToMock, falseStr).andReturn(false).times(1);

  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice(falseStr);
  assertNull(result);

  PowerMock.verifyAll();

 }
}




Previous                                                 Next                                                 Home

Thursday, 20 July 2017

Mock instance void private method

In this post, I am going to explain how to mock instance private void methods. PowerMock class provides 'expectPrivate' method, by using this we can mock private methods of an object. Following snippet mocks the private instance method 'sendStringToLogger'.

String methodToMock = "sendStringToLogger";
StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);
String input = "hello ptr";
PowerMock.expectPrivate(stringUtil, methodToMock, input).times(1);

Following is the complete working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = str.toUpperCase();
  sendStringToLogger(str);
  return upperCase + upperCase;
 }
 
 private void sendStringToLogger(String str){
  throw new MethodNotImplementedException();
 }
}


StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() throws Exception {
  String methodToMock = "sendStringToLogger";
  
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, methodToMock);

  String input = "hello ptr";

  PowerMock.expectPrivate(stringUtil, methodToMock, input).times(1);
  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice(input);

  assertEquals(result, "HELLO PTRHELLO PTR");
  
  PowerMock.verifyAll();

 }
}




Previous                                                 Next                                                 Home

Wednesday, 19 July 2017

Quartz: StdSchedulerFactory example

StdSchedulerFactory class is used to create QuartzScheduler instances.

How to get an instance of StdSchedulerFactory?
StdSchedulerFactory class provides below constructors to get an instance of StdSchedulerFactory.

public StdSchedulerFactory()
public StdSchedulerFactory(Properties props)throws SchedulerException
public StdSchedulerFactory(String fileName) throws SchedulerException

What is the fileName in StdSchedulerFactory constructor?
It is the property file, that specifies the properties used by quartz while running the jobs.

Ex:
org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

By default a properties file named "quartz.properties" is loaded from the 'current working directory'. If that fails, then the "quartz.properties" file located (as a resource) in the org/quartz package is loaded.

How to specify custom quartz property file?
There are three ways.
a.   By passing the custom quartz property file path as an argument to StdSchedulerFactory constructor
b.   By defining system property 'org.quartz.properties' to point to the file you want.
c.   By explicitly initializing the factory by calling one of the initialize(xx) methods before calling getScheduler()

myQuartzConfig.properties
org.quartz.scheduler.instanceName: DefaultQuartzScheduler
org.quartz.scheduler.rmi.export: false
org.quartz.scheduler.rmi.proxy: false
org.quartz.scheduler.wrapJobExecutionInUserTransaction: false

org.quartz.threadPool.class: org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount: 10
org.quartz.threadPool.threadPriority: 5
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread: true

org.quartz.jobStore.misfireThreshold: 60000

org.quartz.jobStore.class: org.quartz.simpl.RAMJobStore

HelloWorldJob.java
package com.sample.test;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class HelloWorldJob implements Job{
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        System.out.println("Hello World");
    }
}

Test.java
package com.sample.test;

import java.util.Date;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.JobDetailImpl;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.SimpleTriggerImpl;

public class Test {
 private static String quartzConfigFileName = "C:\\Users\\Krishna\\quartz_tutorial\\myQuartzConfig.properties";

 public static void main(String args[]) throws SchedulerException {
  SchedulerFactory schedulerFactory = new StdSchedulerFactory(quartzConfigFileName);

  // Retrieve a scheduler from schedule factory
  Scheduler scheduler = schedulerFactory.getScheduler();

  // Creating JobDetailImpl and link to our Job class
  JobDetailImpl jobDetail = new JobDetailImpl();
  jobDetail.setName("First Job");
  jobDetail.setJobClass(HelloWorldJob.class);

  // Creating schedule time with trigger
  SimpleTriggerImpl simpleTrigger = new SimpleTriggerImpl();
  simpleTrigger.setStartTime(new Date(System.currentTimeMillis() + 1000));
  simpleTrigger.setRepeatCount(SimpleTrigger.REPEAT_INDEFINITELY);
  simpleTrigger.setRepeatInterval(3000);
  simpleTrigger.setName("FirstTrigger");

  // Start scheduler
  scheduler.start();
  scheduler.scheduleJob(jobDetail, simpleTrigger);

 }
}

Comments in the program are self-explanatory. When you run above program "Hello World" message is printed to the console for every 3 seconds.



Previous                                                 Next                                                 Home

Tuesday, 18 July 2017

Load a resource from WEB-INF directory

Typical web application structure looks like below.

What is WEB-INF directory?
We can place the resources like jsp file, property files, images etc., in WEB-INF directory. The resources placed in WEB-INF directory are not public, they can be accessed via servlets.

How can I access the contents of WEB-INF directory?
By using getResource and getResourceAsStream method calls on the ServletContext, you can access the contents of WEB-INF directory.

Ex:
                 String filePath = "/WEB-INF/app.properties";

                 String appName, version, author;

                 try (InputStream is = request.getServletContext().getResourceAsStream(filePath)) {
                          Properties properties = new Properties();
                          properties.load(is);

                          appName = properties.getProperty("appName");
                          version = properties.getProperty("version");
                          author = properties.getProperty("author");
                 }

Above statements load the property file located in WEB-INF directory, and read the contents.

Let’s see how to load a property file from WEB-INF directory.

Step 1: Create new dynamic web project 'WebAppDemo' in Eclipse. You can refer below link to create dynamic web project.


Project structure looks like below.

Step 2: Create a file ‘app.properties’ under ‘WEB-INF’ directory.
app.properties
appName=Demo Application to read resources in 'WEB-INF' directory
version=1.0
author=Krishna

Step 3: Define a servlet ‘HelloWorld’ like below.

HelloWorld.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
 private static final long serialVersionUID = 1L;

 public HelloWorld() {
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String filePath = "/WEB-INF/app.properties";

  String appName, version, author;

  try (InputStream is = request.getServletContext().getResourceAsStream(filePath)) {
   Properties properties = new Properties();
   properties.load(is);

   appName = properties.getProperty("appName");
   version = properties.getProperty("version");
   author = properties.getProperty("author");
  }

  response.getWriter().append("Application name : ").append(appName).append("<br />version : ").append(version)
    .append("<br />author : ").append(author);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doGet(request, response);
 }

}

Run the application on server and hit below url.



You can able to see below output.

My final project structure looks like below.




Previous                                                 Next                                                 Home

Increase tomcat server time out in Eclipse

Whenever you face below error, always increase the timeout.

Server Tomcat v9.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.

Follow below steps to increase the time out.
Open the Servers view -> double click tomcat ->

Go to ‘Timeouts’ section and increase the timeout.
You may like
Previous                                                    Next                                                    Home

Saturday, 15 July 2017

Mock instance void parameterized method

In this post, I am going to show how to mock instance void methods. Sometimes you don’t want to call void methods, while testing a function (which in turn calling this void method). By using ‘expectLastCall’ method of EasyMock class, you can mock instance void methods.

Following statements are used to mock the instance void method 'sendStringToLogger'.

StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");
String str = "HELLO PTR";
stringUtil.sendStringToLogger(str);
PowerMock.expectLastCall().times(1);

Following is the complete working application.

MethodNotImplementedException.java
package com.sample.model;

public class MethodNotImplementedException extends RuntimeException {
 private static final long serialVersionUID = 1L;

 public MethodNotImplementedException() {
  super();
 }

 public MethodNotImplementedException(String message) {
  super(message);
 }

}

StringUtil.java
package com.sample.util;

import com.sample.model.MethodNotImplementedException;

public class StringUtil {
 public String toUpperAndRepeatStringTwice(String str) {
  String upperCase = str.toUpperCase();
  sendStringToLogger(upperCase);
  return upperCase + upperCase;
 }
 
 public void sendStringToLogger(String str){
  throw new MethodNotImplementedException();
 }
}

StringUtilTest.java
package com.sample.util;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ StringUtil.class })
public class StringUtilTest {

 @Test
 public void toUpperAndRepeatStringTwice() {
  StringUtil stringUtil = PowerMock.createPartialMock(StringUtil.class, "sendStringToLogger");

  String str = "HELLO PTR";

  stringUtil.sendStringToLogger(str);
  PowerMock.expectLastCall().times(1);
  
  PowerMock.replayAll();

  String result = stringUtil.toUpperAndRepeatStringTwice("hello ptr");

  assertEquals(result, "HELLO PTRHELLO PTR");

 }
}



Previous                                                 Next                                                 Home