Tuesday, 6 March 2018

Hamcrest: array: Match every element of array with specific matcher

By using 'array' matcher, you can create a matcher that matches array whose elements are satisfied by the specified matchers.

For ex
Integer[] primes = { 2, 3, 5, 7 };
assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

Make sure that the number of matchers are equal to number of elements in the array.

Find the below working applicaiton.

TestApp.java

package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @SuppressWarnings("unchecked")
 @Test
 public void testmethod() {
  String[] empIds = { "I312", "I768", "I456" };
  assertThat("Checking empIds details", empIds, array(equalTo("I312"), equalTo("I768"), equalTo("I456")));

  Integer[] primes = { 2, 3, 5, 7 };
  assertThat("Checking first 4 primes", primes, array(equalTo(2), equalTo(3), equalTo(5), equalTo(7)));

 }
}




Previous                                                 Next                                                 Home

Monday, 5 March 2018

How to write multiple input streams to a file

In this post, I am going to show you how to read the data from multiple input streams and write to a file. Let me explain an example with plain java code and later I am going to show you how can we simplify the same code using SequenceInputStream class provided by Java.

Below snippet reads the data from multiple input streams and write to the file.

byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead;

try (OutputStream outputStream = new FileOutputStream(file)) {
         for (InputStream inputStream : inputStreams) {
                  if (inputStream == null) {
                           continue;
                  }
                  while ((bytesRead = inputStream.read(buffer)) != -1) {
                           outputStream.write(buffer, 0, bytesRead);
                  }
         }

}

Find the below working application.

FileUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 /**
  * Reads the data from multiple input streams and write to the file.
  * 
  * @param file
  * @param inputStreams
  * @throws IOException
  * @throws FileNotFoundException
  */
 public static void writeToFile(File file, InputStream... inputStreams) throws FileNotFoundException, IOException {
  if (file == null) {
   throw new IllegalArgumentException("file should not be null");
  }

  if (inputStreams == null) {
   throw new IllegalArgumentException("inputStreams can't be null");
  }

  byte[] buffer = new byte[BUFFER_SIZE];
  int noOfBytesRead;

  try (OutputStream outputStream = new FileOutputStream(file)) {
   for (InputStream inputStream : inputStreams) {
    if (inputStream == null) {
     continue;
    }
    while ((noOfBytesRead = inputStream.read(buffer)) != -1) {
     outputStream.write(buffer, 0, noOfBytesRead);
    }
   }

  } finally {
   for (InputStream inputStream : inputStreams) {
    if (inputStream == null) {
     continue;
    }

    inputStream.close();
   }
  }
 }

 public static void writeToFile(String filePath, InputStream... inputStreams)
   throws FileNotFoundException, IOException {
  writeToFile(new File(filePath), inputStreams);
 }
}

Test.java
package com.sample.test;

import java.io.FileInputStream;
import java.io.InputStream;

import com.sample.util.FileUtil;

public class Test {
 public static void main(String args[]) throws Exception {
  String destinationPath = "C:\\Users\\krishna\\dest.log";
  
  String logFile1 = "C:\\Users\\krishna\\app1.log";
  String logFile2 = "C:\\Users\\krishna\\app2.log";
  String logFile3 = "C:\\Users\\krishna\\app3.log";
  
  InputStream inputStream1 = new FileInputStream(logFile1);
  InputStream inputStream2 = new FileInputStream(logFile2);
  InputStream inputStream3 = new FileInputStream(logFile3);
  
  FileUtil.writeToFile(destinationPath, inputStream1, inputStream2, inputStream3);
  
 }
}

Java provides 'SequenceInputStream' class, this is used to process collection of input stream in one shot.

'SequenceInputStream' provides below constructors.
SequenceInputStream(Enumeration<? extends InputStream> e)
SequenceInputStream(InputStream s1, InputStream s2)

Step 1: Create a SequenceInputStream from enumeration of input streams
InputStream inputStream1 = new FileInputStream(logFile1);
InputStream inputStream2 = new FileInputStream(logFile2);
InputStream inputStream3 = new FileInputStream(logFile3);

List<InputStream> inputStreams = Arrays.asList(inputStream1, inputStream2, inputStream3);

Enumeration<InputStream> e = Collections.enumeration(inputStreams);

Step 2: Now write the content to the file using SequenceInputStream.

try (OutputStream outputStream = new FileOutputStream(file)) {
         while ((noOfBytesRead = sequenceInputStream.read(buffer)) != -1) {
                  outputStream.write(buffer, 0, noOfBytesRead);
         }
}

Find the below working example.


FileUtil.java
package com.sample.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.SequenceInputStream;

public class FileUtil {

 private static final int BUFFER_SIZE = 4096;

 /**
  * Reads the data from multiple input streams and write to the file.
  * 
  * @param file
  * @param inputStreams
  * @throws IOException
  * @throws FileNotFoundException
  */
 public static void writeToFile(File file, SequenceInputStream sequenceInputStream)
   throws FileNotFoundException, IOException {
  if (file == null) {
   throw new IllegalArgumentException("file should not be null");
  }

  if (sequenceInputStream == null) {
   throw new IllegalArgumentException("sequenceInputStream can't be null");
  }

  byte[] buffer = new byte[BUFFER_SIZE];
  int noOfBytesRead;

  try (OutputStream outputStream = new FileOutputStream(file)) {
   while ((noOfBytesRead = sequenceInputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, noOfBytesRead);
   }
  } finally {
   sequenceInputStream.close();
  }
 }

 public static void writeToFile(String filePath, SequenceInputStream sequenceInputStream)
   throws FileNotFoundException, IOException {
  writeToFile(new File(filePath), sequenceInputStream);
 }
}

Test.java
package com.sample.test;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

import com.sample.util.FileUtil;

public class Test {
 public static void main(String args[]) throws Exception {
  String destinationPath = "C:\\Users\\krishna\\dest.log";

  String logFile1 = "C:\\Users\\krishna\\app1.log";
  String logFile2 = "C:\\Users\\krishna\\app2.log";
  String logFile3 = "C:\\Users\\krishna\\app3.log";

  InputStream inputStream1 = new FileInputStream(logFile1);
  InputStream inputStream2 = new FileInputStream(logFile2);
  InputStream inputStream3 = new FileInputStream(logFile3);

  List<InputStream> inputStreams = Arrays.asList(inputStream1, inputStream2, inputStream3);

  Enumeration<InputStream> e = Collections.enumeration(inputStreams);
  SequenceInputStream sequenceInputStream = new SequenceInputStream(e);

  FileUtil.writeToFile(destinationPath, sequenceInputStream);

 }
}

Hamcrest: Matchers to work with arrays

Hamcrest library provides below methods to work with arrays.


Previous                                                 Next                                                 Home

Hamcrest: stringContainsInOrder: Matches a string against all the substrings

By using stringContainsInOrder, you can create a matcher that checks whether the actual result contains the specified Strings in this sequence

Ex
List<String> subStrs1 = Arrays.asList("How", "are", "you");
assertThat("sentence must contain subStrs in order :", sentence, stringContainsInOrder(subStrs1));

Find the below working application.

TestApp.java

package com.sample.tests;

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

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String sentence = "Hello Shiney, How are you";
  List<String> subStrs1 = Arrays.asList("How", "are", "you");
  List<String> subStrs2 = Arrays.asList("Hello", "you");
  List<String> subStrs3 = Arrays.asList("Shiney", "are", "you");

  /* Checks that the actual result contains the specified Strings in this sequence */
  assertThat("sentence must contain subStrs in order :", sentence, stringContainsInOrder(subStrs1));
  assertThat("sentence must contain subStrs in order :", sentence, stringContainsInOrder(subStrs2));
  assertThat("sentence must contain subStrs in order :", sentence, stringContainsInOrder(subStrs3));

 }
}




Previous                                                 Next                                                 Home

Friday, 2 March 2018

HamCrest: isEmptyOrNullString: Match if the string is empty or null

By using isEmptyOrNullString, you can create a matcher that matches when the examined string is null, or has zero length.

Ex
String str1 = "";
String str2 = null;
                 
assertThat("str1 should be empty", str1, isEmptyOrNullString());
assertThat("str2 should be null", str2, isEmptyOrNullString());

Find the below working application.

TestApp.java
package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String str1 = "";
  String str2 = null;
  
  assertThat("str1 should be empty", str1, isEmptyOrNullString());
  assertThat("str2 should be null", str2, isEmptyOrNullString());
 }
}




Previous                                                 Next                                                 Home

Hamcrest: isEmptyString: Match if the string is empty

By using isEmptyString method, you can create a matcher that matches when the examined string has zero length.

Ex
String str = "";
assertThat("str should be empty", str, isEmptyString());

Find the below working application.

TestApp.java
package com.sample.model;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String str = "";

  assertThat("str should be empty", str, isEmptyString());
 }
}




Previous                                                 Next                                                 Home

Hamcrest: equalToIgnoringWhiteSpace: check equality of strings by ignoring case and white spaces

By using 'equalToIgnoringWhiteSpace' method, you can create a matcher of string that matches when the examined string is equal to the specified expected string, by ignoring case and whitespaces.

While matching the strings, below rules are applied.

         1. All leading and trailing whitespace of both the expectedString and the examined string are ignored
         2. Any remaining whitespace, appearing within either string, is collapsed to a single space before comparison
        
Ex
String str = "Hello World";
assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("Hello       World"));

Find the below working application.

TestApp.java
package com.sample.model;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String str = "Hello World";

  assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("Hello       World"));
  assertThat("comparing strings by ignoring case ", str, equalToIgnoringWhiteSpace("  Hello World "));
 }
}




Previous                                                 Next                                                 Home