Thursday, 8 March 2018

Hamcrest: arrayContaining: Match each item in the array

‘arrayContaining’ matcher is used to match each element in array. ‘arrayContaining’ matcher is available in 3 overloaded forms.

public static <E> org.hamcrest.Matcher<E[]> arrayContaining(E... items)
It creates a matcher for arrays that matches when each item in the examined array is logically equal to the corresponding item in the specified items. 

Ex
String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
assertThat("Checking names array", names, arrayContaining("krishna", "Chamu", "Sailu", "Gopi"));

Find the below working application.

TestApp.java
package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
  assertThat("Checking names array", names, arrayContaining("krishna", "Chamu", "Sailu", "Gopi"));

 }
}

public static <E> org.hamcrest.Matcher<E[]> arrayContaining(org.hamcrest.Matcher<? super E>... itemMatchers)
It creates a matcher for arrays that matches when each item in the examined array satisfies the corresponding matcher in the specified matchers.

Ex
String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
assertThat("Checking names array", names, arrayContaining(startsWith("kri"), endsWith("mu"), notNullValue(), notNullValue()));

Find the below working application.


TestApp.java

package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayContaining;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;

import org.junit.Test;

public class TestApp {

 @SuppressWarnings("unchecked")
 @Test
 public void testmethod() {
  String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
  assertThat("Checking names array", names, arrayContaining(startsWith("kri"), endsWith("mu"), notNullValue(), notNullValue()));

 }
}

public static <E> org.hamcrest.Matcher<E[]> arrayContaining(java.util.List<org.hamcrest.Matcher<? super E>> itemMatchers)
It creates a matcher for arrays that matches when each item in the examined array satisfies the corresponding matcher in the specified list of matchers.

Ex
String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
List<org.hamcrest.Matcher<? super String>> itemMatchers = new ArrayList<Matcher<? super String>>();
itemMatchers.add(equalTo("krishna"));
itemMatchers.add(equalTo("Chamu"));
itemMatchers.add(endsWith("lu"));
itemMatchers.add(endsWith("pi"));

assertThat("Checking names array", names, arrayContaining(itemMatchers));

Find the below working application.


TestApp.java

package com.sample.tests;

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

import java.util.ArrayList;
import java.util.List;

import org.hamcrest.Matcher;
import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
  List<org.hamcrest.Matcher<? super String>> itemMatchers = new ArrayList<Matcher<? super String>>();
  itemMatchers.add(equalTo("krishna"));
  itemMatchers.add(equalTo("Chamu"));
  itemMatchers.add(endsWith("lu"));
  itemMatchers.add(endsWith("pi"));

  assertThat("Checking names array", names, arrayContaining(itemMatchers));

 }
}




Previous                                                 Next                                                 Home

Wednesday, 7 March 2018

How to chain multiple different InputStreams into one InputStream

Java provides 'SequenceInputStream' class, this is used to process collection of input streams 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);

 }
}

You may like

hamcrest: hasItemInArray: Check the existence of item in the array

'hasItemInArray' is used to check the existance of item in the array.

It is available in two overloaded forms.

public static <T> org.hamcrest.Matcher<T[]> hasItemInArray(T element)
This method creates a matcher that is used to check whether the array has given element or not.

Ex
String[] empIds = { "I312", "I768", "I456" };
assertThat("empIds must have 'I768'", empIds, hasItemInArray("I768"));

Find the below working application.

TestApp.java
package com.sample.tests;

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

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String[] empIds = { "I312", "I768", "I456" };
  assertThat("empIds must have 'I768'", empIds, hasItemInArray("I768"));

  Integer[] primes = { 2, 3, 5, 7 };
  assertThat("empIds must have 5", primes, hasItemInArray(5));
 }
}

public static <T> org.hamcrest.Matcher<T[]> hasItemInArray(org.hamcrest.Matcher<? super T> elementMatcher)
You can create a matcher for arrays that matches when the examined array contains at least one item that is matched by the specified elementMatcher.

Ex
String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
assertThat("Any one of the names must starts with 'Ch'", names, hasItemInArray(startsWith("Ch")));

Find below working application.

TestApp.java
package com.sample.tests;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.hamcrest.Matchers.startsWith;

import org.junit.Test;

public class TestApp {

 @Test
 public void testmethod() {
  String names[] = { "krishna", "Chamu", "Sailu", "Gopi" };
  assertThat("Any one of the names must starts with 'Ch'", names, hasItemInArray(startsWith("Ch")));

 }
}



Previous                                                 Next                                                 Home

Tuesday, 6 March 2018

Base64 encoding and decoding in Java

In this post, you are going to learn below things.
a.   What is Base64 Encoding/decoding
b.   How to encode data in Base64
c.   Where can I use Base64 encoding
d.   How much more memory base-64 require to represent the data?
e.   How can I perform base64 encoding in Java?

What is Base64 encoding/decoding?
Base64 is one of binary-to-text encoding scheme. In binary-to-text encoding, we encode binary data in plain text.

Below tables summarizes all the symbols in base64 scheme.

Value
Char
Value
Char
Value
Char
Value
Char
0
A
16
Q
32
g
48
w
1
B
17
R
33
h
49
x
2
C
18
S
34
i
50
y
3
D
19
T
35
j
51
z
4
E
20
U
36
k
52
0
5
F
21
V
37
l
53
1
6
G
22
W
38
m
54
2
7
H
23
X
39
n
55
3
8
I
24
Y
40
o
56
4
9
J
25
Z
41
p
57
5
10
K
26
a
42
q
58
6
11
L
27
b
43
r
59
7
12
M
28
c
44
s
60
8
13
N
29
d
45
t
61
9
14
O
30
e
46
u
62
+
15
P
31
f
47
v
63
/

Output Padding
Each base-64 encoded digit is represented by 6 bits. When data is not split exactly by 6 bits, then padding needs to be done. Data can be padded by ‘==’ (or) =.

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

How to encode data in Base-64?
Let me explain with an example, how the string "java" is represented in Base64 encoding scheme.

"java" represented in ASCII form like below.
01101010011000010111011001100001

Since base64 encoding scheme requires 6 bits to represent a character, divide the above binary information into 6 bits groups from left to right.

011010   100110   000101   110110   011000   01
   26          38           5           54          24
   a            m            F           2            Y

As you see, above example, last group data is not split exactly by 6 bits. We end up with 2 bits. To make it 6 bits, we need to pad 4 0's at end.

011010   100110   000101   110110    011000   010000
   26          38           5           54           24          16
   a            m            F           2             Y            Q
  
Since last group contain only one byte (01, before adding 0000), we need to pad the encoded information with '=='.

So final encoded value is amF2YQ==.

Where can I use Base64 encoding?
It is used, when you want to transfer some binary information over network and network is not supporting transfer of binary information, you can encode the binary data using Base-64 and transfer over the network.

How much more memory base-64 require to represent the data?
Base-64 maps 3 bytes (8 x 3 = 24 bits) in 4 Base-64 characters (6 x 4 = 24 bits). Therefore it requires 4/3 = 1.3333333 times the original. So Base64 encoding uses 33% more storage.

How can I perform base64 encoding in Java?
'java.util.Base64' class provides functionality to encode and decode the information.

How to get Base64 Encoder?
Encoder encoder = Base64.getEncoder();

How to get Base64 Decoder?
Decoder decoder = Base64.getDecoder();

Find the below working application.
Test.java
package com.sample.test;

import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;

public class Test {
 public static void main(String args[]) {
  Encoder encoder = Base64.getEncoder();
  Decoder decoder = Base64.getDecoder();

  String originalData = "java";
  byte[] encodedBytes = encoder.encode(originalData.getBytes());
  String encodedStr = new String(encodedBytes);

  byte[] decodedBytes = decoder.decode(encodedBytes);
  String decodedStr = new String(decodedBytes);

  System.out.println("Original Data is : " + originalData);
  System.out.println("Encoded Data is : " + encodedStr);
  System.out.println("Decoded data is : " + decodedStr);

 }
}

Output
Original Data is : java
Encoded Data is : amF2YQ==
Decoded data is : java