Saturday, 24 March 2018

Hamcrest: hasItems: Check for the existence of multiple items

By using ‘hasItems’ method, you can create a matcher that is used to check existence of multiple items in the collection.

‘hasItems’ method is available in two overloaded forms.

public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(T... items)
Above method is used to check existence of multiple items in the collection.

Ex
a. Check the existence ot 45 and 24 in employeeAges
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("employee ages must have 45 and 24", employeeAges, hasItems(45, 24));

b. Check the existence of ‘melt’ and ‘men’ in strs.
List<String> strs = Arrays.asList("men", "met", "melt");
assertThat("strs must have 'melt' and 'men'", strs, hasItems("melt", "men"));

Find the below working application.
TestApp.java

package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItems;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("employee ages must have 45 and 24", employeeAges, hasItems(45, 24));

  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("strs must have 'melt' and 'men'", strs, hasItems("melt", "men"));
 }
}

public static <T> org.hamcrest.Matcher<java.lang.Iterable<T>> hasItems(org.hamcrest.Matcher<? super T>... itemMatchers)
By using this method, you can create a matcher for that matches at least one item that is matched by the corresponding matcher from the specified itemMatchers.

Ex
a. Make sure that the collection has an element that is equal to 32 and one element that is > 40.
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("Age must be > 20", employeeAges, hasItems(equalTo(32), greaterThan(40)));

b. Make sure that the collection has an element that is equal to ‘melt’ and element that ends with ‘et’.
List<String> strs = Arrays.asList("men", "met", "melt");
assertThat("elements shoudl start with me", strs, hasItems(equalTo("melt"), endsWith("et")));

Find the below working application.


TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItems;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @SuppressWarnings("unchecked")
 @Test
 public void testmethod() {

  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("Age must be > 20", employeeAges, hasItems(equalTo(32), greaterThan(40)));

  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, hasItems(equalTo("melt"), endsWith("et")));
 }
}





Previous                                                 Next                                                 Home

Friday, 23 March 2018

Working with RandomAccessFile in Java

In this post, you are going to learn
a.   What is RandomAccessFile
b.   How to create an instance of RandomAccessFile?
c.   Important methods used while working with RandomAccessFile
d.   How can you read the data from file at random position?
e.   How can you write data to file from specific position?
f.    File tail implementation using RanddomAccessFile

What is RandomAccessFile?
You can read data from any position, write data at any position using RandomAccessFile.

RandomAccessFile treats the file data as an array of bytes, you can write the data at any position of the array and read the data from any position of the array.

How to create an instance of RandomAccessFile?
RandomAccessFile class provides below constructors, to create an instance of RandomAccessFile.

RandomAccessFile(File file, String mode)
RandomAccessFile(String filePath, String mode)

'mode' represents the accessMode to be used while opening the file.

Below table summarizes the possible values of the argument 'mode'.

Mode
Description
"r"
Opens the file in read only mode. If you try to perform any write operation, it results in IOException to be thrown
"rw"
Opens the file in read-write mode. You can perform both read and write operations here. If file is not exist already, it creates it.
"rws"
Opens the file in read-write mode. Opens the file in read-write mode. every update to the file's content or metadata be written synchronously to the underlying storage device.
"rwd"
Opens the file in read-write mode. Opens the file in read-write mode. Every update to the file's content be written synchronously to the underlying storage device.

Important methods used while working with RandomAccessFile
Below table summarizes the methods that you use frequently while working with RandomAccessFile.

Method
Description
public long getFilePointer()
Get the current position of the file pointer.
public void seek(long position)
Set the file pointer address. Position measured from the beginning of the file.
public long length()
Get the length of the file in bytes.
public void setLength(long newLength)
Set the length of the file in bytes.

If the present length of the file as returned by the length method is greater than the newLength argument then the file will be truncated. In this case, if the file offset as returned by the getFilePointer method is greater than newLength then after this method returns the offset will be equal to newLength.

If the present length of the file as returned by the length method is smaller than the newLength argument then the file will be extended. In this case, the contents of the extended portion of the file are not defined.
public int read(byte[] b)
Reads up to b.length bytes of data from this file into an array of bytes.

How can you read the data from file at random position?
By using below snippet, you can read the contents of the file.

RandomAccessFile randFile = new RandomAccessFile(filePath, "r")
randFile.seek(position);

byte b[] = new byte[BUFFER_SIZE];

while (randFile.read(b) != -1) {
         String s = new String(b);
         System.out.println(s);
}

testData.txt
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

Find the below working application.


FileUtil.java
package com.sample.util;

import java.io.IOException;
import java.io.RandomAccessFile;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 public static void prinFileContentFrom(String filePath, int position) throws IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "r")) {
   long length = randFile.length();

   if (position > length) {
    throw new IllegalArgumentException("position : " + position + " must be less than " + length);
   }

   randFile.seek(position);

   byte b[] = new byte[BUFFER_SIZE];

   while (randFile.read(b) != -1) {
    String s = new String(b);
    System.out.println(s);
   }
  }

 }
}


Test.java
package com.sample.test;

import com.sample.util.FileUtil;

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\testData.txt";

 public static void main(String args[]) throws Exception {
  System.out.println("Reading the content from starting of the file");
  FileUtil.prinFileContentFrom(FILE_PATH, 0);

  System.out.println("\n*************************");
  System.out.println("Reading the content from the offset 50\n");
  FileUtil.prinFileContentFrom(FILE_PATH, 50);
 }
}

Output
Reading the content from starting of the file
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

*************************
Reading the content from the offset 50

   Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;

How can you write data to file from specific position?
Below snippet is used to write data to file from given position.

try (RandomAccessFile randFile = new RandomAccessFile(filePath, "rw")) {
         randFile.seek(position);
         randFile.write(data.getBytes());
}

Find the below working application.


FileUtil.java
package com.sample.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 public static void writeContentsToFile(String filePath, String data, int position)
   throws FileNotFoundException, IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "rw")) {
   randFile.seek(position);
   randFile.write(data.getBytes());
  }
 }

 public static void printFileContent(String filePath) throws IOException{
  printFileContentFrom(filePath, 0);
 }
 
 public static void printFileContentFrom(String filePath, int position) throws IOException {
  try (RandomAccessFile randFile = new RandomAccessFile(filePath, "r")) {
   long length = randFile.length();

   if (position > length) {
    throw new IllegalArgumentException("position : " + position + " must be less than " + length);
   }

   randFile.seek(position);

   byte b[] = new byte[BUFFER_SIZE];

   while (randFile.read(b) != -1) {
    String s = new String(b);
    System.out.println(s);
   }
  }

 }
}


Test.java
package com.sample.test;

import com.sample.util.FileUtil;

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\testData.txt";

 public static void main(String args[]) throws Exception {
  System.out.println("Reading the content from starting of the file");
  FileUtil.printFileContent(FILE_PATH);

  String data = "line1\nline2\nline3\nline4";

  System.out.println("\nDATA AFTER ADDING\n");

  FileUtil.writeContentsToFile(FILE_PATH, data, 50);
  
  FileUtil.printFileContent(FILE_PATH);

 }
}

Output
Reading the content from starting of the file
If you can keep your head when all about you   
    Are losing theirs and blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;
 
DATA AFTER ADDING

If you can keep your head when all about you   
 line1
line2
line3
line4d blaming it on you,   
If you can trust yourself when all men doubt you,
    But make allowance for their doubting too;








Hamcrest: hasItem: Check for the existence of at least one item

By using 'hasItem' method, you can create a matcher, for Iterables (Collections that implements Iterable interface) that is used to check whether given collection has at least one item that matches to the specific matcher or not.

a. Check the collection, whether it has atleast one element that is > 40.
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("Age must be > 20", employeeAges, hasItem(greaterThan(40)));

b. Check whether collection of strings has atleast one element that ends with "et" ot not.
List<String> strs = Arrays.asList("men", "met", "melt");
assertThat("elements should start with me", strs, hasItem(endsWith("et")));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasItem;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("Age must be > 20", employeeAges, hasItem(greaterThan(40)));

  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, hasItem(endsWith("et")));
 }
}




Previous                                                 Next                                                 Home

JsonParser : Parse json file using gson library

In this post, I am going to explain, how can you parse a json file using gson library.

For example, consider below json file.

testApp.json
{
 "login" : {
  "userName" : "krishna",
  "password" : "krishna"
 },

 "homePage" : {
  "welcomeMessage" : "Hello Krishna",
  "buttonId" : "saveYourChanges"
 }
}

Below step-by-step procedure explains, how to parse login element from testApp.json file.

Step 1: Create the instance of JsonParser.
JsonParser jsonParser = new JsonParser();

Step 2: Read the json data from given file.
String jsonData = new String(Files.readAllBytes(Paths.get(jsonFilePath)));

Step 3: Get the root element by parsing the data.
JsonObject rootElement = (JsonObject)jsonParser.parse(jsonData);

Step 4: Now you can parse the element by using element name.
For example, below statement retrieves the json element with name 'login'.

JsonObject loginElement =  (JsonObject)jsonParser.parse(rootElement.get("login").toString());

Find the below working application.

Test.java
package com.sample.files;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.Set;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class Test {

 private static String jsonFilePath = "C:\\Users\\krishna\\testApp.json";
 
 public static void main(String args[]) throws Exception {
 
  JsonParser jsonParser = new JsonParser();
  
  String jsonData = new String(Files.readAllBytes(Paths.get(jsonFilePath)));
  
  JsonObject rootElement = (JsonObject)jsonParser.parse(jsonData);
  
  JsonObject loginElement =  (JsonObject)jsonParser.parse(rootElement.get("login").toString());
  
  Set<Map.Entry<String, JsonElement>> entrySet = loginElement.entrySet();
  
  for(Map.Entry<String, JsonElement> entry : entrySet){
   String key = entry.getKey();
   String value = entry.getValue().getAsString();
   System.out.println("key : " + key + ", value : " + value);
  }

 }
}


Output
key : userName, value : krishna
key : password, value : krishna






Previous                                                 Next                                                 Home

Hamcrest: everyItem: All elements must match to given matcher

By using ‘everyItem’ method, we can create a matcher that checks whether all the elements are matched to given matcher or not.

Ex
a. Employee age must be > 20
List<Integer> employeeAges = Arrays.asList(24, 45, 32);
assertThat("Age must be > 20", employeeAges, everyItem(greaterThan(20)));

b. All the strings must start with word ‘me’.
List<String> strs = Arrays.asList("men", "met", "melt");
assertThat("elements shoudl start with me", strs, everyItem(startsWith("me")));

Find the below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.startsWith;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  List<Integer> employeeAges = Arrays.asList(24, 45, 32);
  assertThat("Age must be > 20", employeeAges, everyItem(greaterThan(20)));

  List<String> strs = Arrays.asList("men", "met", "melt");
  assertThat("elements shoudl start with me", strs, everyItem(startsWith("me")));
 }
}




Previous                                                 Next                                                 Home

Hamcrest: Matchers to work with collections

HamCrest provides below matchers to work with collections.



Previous                                                 Next                                                 Home

Hamcrest: equalTo: objects equality using equals method

By using equalTo method, you can create a matcher that check whether this object is logically equal to another object. It uses equals method to check equality of object.

Employee.java
package com.sample.model;

public class Employee {
 private int id;
 private String name;
 private Double experience;

 public Employee(int id, String name, Double experience) {
  this.id = id;
  this.name = name;
  this.experience = experience;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public double getExperience() {
  return experience;
 }

 public void setExperience(double experience) {
  this.experience = experience;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + id;
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Employee other = (Employee) obj;
  if (id != other.id)
   return false;
  return true;
 }

}

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

import com.sample.model.Employee;

public class TestApp {

 @Test
 public void testmethod() {
  Employee emp1 = new Employee(1, "Hari", 5.6);
  Employee emp2 = new Employee(1, "Hari", 5.6);
  Employee emp3 = emp1;

  assertThat("emp1 and emp2 are equal", emp1, equalTo(emp2));
  assertThat("emp1 and emp3 are equal", emp1, equalTo(emp3));

 }
}





Previous                                                 Next                                                 Home