Monday, October 19, 2015

JAVA COLLECTIONS UTILITY


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * A set of commonly used utilities for {@link Collection}s. Named as Collectionz to avoid
 * conflict with {@link java.util.Collections}
 *
 *
 */
public class Collectionz {

/**
* Checks whether the collection is null or empty.
*
* @param collection collection to be checked
* @return true if the collection is null or empty, false otherwise
*/
public static boolean isNullOrEmpty(Collection<?> collection) {
return collection == null ? true : collection.isEmpty();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code List<TypeThatsTooLongForItsOwnGood> list = new ArrayList<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code List<TypeThatsTooLongForItsOwnGood> list = Collectionz.newArrayList();}
* @return a new empty {@code ArrayList}
*/
public static <T> ArrayList<T> newArrayList() {
return new ArrayList<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code List<TypeThatsTooLongForItsOwnGood> list = new LinkedList<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code List<TypeThatsTooLongForItsOwnGood> list = Collectionz.newLinkedList();}
* @return a new empty {@code LinkedList}
*/
public static <T> LinkedList<T> newLinkedList() {
return new LinkedList<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = new HashSet<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = Collectionz.newHashSet();}
* @return a new empty {@code HashSet}
*/
public static <T> HashSet<T> newHashSet() {
return new HashSet<T>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = new LinkedHashSet<TypeThatsTooLongForItsOwnGood>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Set<TypeThatsTooLongForItsOwnGood> set = Collectionz.newLinkedHashSet();}
* @return a new empty {@code LinkedHashSet}
*/
public static <T> LinkedHashSet<T> newLinkedHashSet() {
return new LinkedHashSet<T>();
}

/**
* Transforms the collection to map using the type of collection {@code V} as value type in map
* and uses the {@code keyFormationFunction} to form keys of type {@code K} for each entry in collection.
*
* @param <K> the type of key in map
* @param <V> the type of value in map, same as type of value in collection
* @param collection a non-null collection which will be transformed to map
* @param valueToKeyFunction a non-null function that will form key based on value
* @return map created using all elements in collection
*/
public static <K,V> Map<K, V> asHashMap(Collection<V> collection, Function<V, K> valueToKeyFunction) {
checkNotNull(collection, "collection is null");
checkNotNull(valueToKeyFunction, "valueToKeyFunction is null");

Map<K,V> map = new HashMap<K, V>();
for(V element : collection){
map.put(valueToKeyFunction.apply(element),element);
}
return map;
}

/**
* From the given collections returns the first collection that is non-null and non-empty
* wrapped in optional.
* If no suitable collection is found then returns an {@link Optional#absent()}. Before
* getting the collection check to see if it is present using {@link Optional#isPresent()}.
*
* @param <T> any sub-type of collection
* @param collections a non-null collection array
* @return optional instance containing collection if a non-null and non-empty collection
* is found, {@code Optional.absent()} otherwise
*/
public static <T extends Collection<?>> Optional<T> firstNonEmpty(T... collections) {
for(T collection : collections) {
if(Collectionz.isNullOrEmpty(collection) == false) {
return Optional.of(collection);
}
}
return Optional.absent();
}

/**
* Returns a list as a resultant of applying function {@code mapper} to each element
* of the collection {@code coll}. Returns an empty mutable list if {@code coll} is
* {@code null} or if the collection is empty.
*
* @param <X> type of elements in source collection
* @param <Y> type of elements in mapped collection
* @param coll source collection on which mapping will be applied
* @param mapper a non-null function
* @return resultant list obtained by applying function {@code mapper} on collection,
* empty mutable list if {@code coll} is null or empty
* @throws NullPointerException is mapper function is null
*/
public static <X, Y> List<Y> map(Collection<X> coll, Function<X, Y> mapper) {
checkNotNull(mapper, "mapper function is null");

if (isNullOrEmpty(coll)) {
return new ArrayList<Y>(0);
}

List<Y> result = new ArrayList<Y>();
for (X element : coll) {
result.add(mapper.apply(element));
}
return result;
}

/**
* Filters the elements from the collection that don't satisfy the predicate passed.
* <p>This method eagerly evaluates the filter and removes the elements from the passed
* {@code unfiltered} collection. Uses {@link Iterator#remove()} method to remove elements
* that don't satisfy the filter, so remove method MUST be supported for this method
* to work.
*
* <p><b>NOTE:</b> This method eagerly evaluates the filter giving O(n) complexity.
*
* <p>Usage:
* <pre><code>
* Collection&lt;String&gt; unfiltered = ...
* Collectionz.filter(unfiltered, Predicates.nonNull());
* </code></pre>
*
* @param <T> type of elements in the collection
* @param unfiltered a non-null collection to be filtered
* @param predicate a non-null filter which will be applied to all elements in the collection
* @throws NullPointerException if any parameter passed is null
*/
public static <T> void filter(Collection<T> unfiltered,
Predicate<? super T> predicate) {
checkNotNull(unfiltered, "collection is null");
checkNotNull(predicate, "predicate is null");

Iterator<? extends T> iterator = unfiltered.iterator();
while (iterator.hasNext()) {
if (predicate.apply(iterator.next()) == false) {
iterator.remove();
}
}
}
}

JAVA FILES UTILITY


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Files {

/**
* Read full bytes of the given file.
*
* @param file a non-null file whose bytes will be read
* @return full bytes of the given file
* @throws FileNotFoundException if file does not exist
* @throws IOException if some issue occurs while reading from file
* @throws IllegalArgumentException if file is a directory
*/
public static byte[] readFully(File file) throws FileNotFoundException, IOException, IllegalArgumentException {
checkNotNull(file, "file is null");
checkArgument(file.isFile(), file.getPath() + " is not a file");

return ByteStreams.readFully(new FileInputStream(file));
}

/**
* Read full bytes of the file at given path.
*
* @param filePath non-null path of the file whose bytes will be read
* @return full bytes of file at given path
* @throws FileNotFoundException if file at given path does not exist
* @throws IOException if some issue occurs while reading from file
* @throws IllegalArgumentException if filePath points to a directory
*/
public static byte[] readFully(String filePath) throws FileNotFoundException, IOException, IllegalArgumentException {
checkNotNull(filePath, "filePath is null");

return readFully(new File(filePath));
}
}

JAVA MAPS UTILITY

public class Maps {

/**
* Checks whether the map is {@code null} or empty
* @param map a nullable map
* @return true if map is either {@code null} or empty, false otherwise
*/
public static boolean isNullOrEmpty(Map<?, ?> map) {
return map == null || map.isEmpty();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map =
* new HashMap<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map = Maps.newHashMap();}
* @return a new empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}

/**
* Before JDK 7, constructing new generic collections requires unpleasant code duplication:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map =
* new LinkedHashMap<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong>();}
*
* <p>But using these static factory methods, the type on the right side is automatically inferred:
* {@code Map<TypeThatsTooLongForItsOwnGood, AnotherTypeThatsTooLong> map = Maps.newLinkedHashMap();}
* @return a new empty {@code LinkedHashMap}
*/
public static <K, V> HashMap<K, V> newLinkedHashMap() {
return new LinkedHashMap<K, V>();
}
}

JAVA NUMBERS UTILITY


public class Numbers {

/**
* A predicate for positive integers. Evaluates to false if the Integer is null.
*/
public static final Predicate<Integer> POSITIVE_INT = new PositiveIntPredicate();
/**
* A predicate for positive long value. Evaluates to false if the Long is null or zero.
*/
public static final Predicate<Long> POSITIVE_LONG = new PositiveLongPredicate();

/**
* Returns a big-endian representation of {@code value} as an n byte array, where
* n is the {@code noOfBytes}.
*
* <p>Returns an empty array if {@code noOfBytes} is {@code 0}
*
* <p> Example: {@code Numbers.toByteArray(0x1213,3)} will return a byte array
* {@code {0x00, 0x12, 0x13}}.
*
* @param value any integer value
* @param noOfBytes non-negative number of bytes
* @return a big-endian representation of value as a byte array.
* @throws IllegalArgumentException if {@code noOfBytes} is negative
*/
public static byte[] toByteArray(int value, int noOfBytes) {
checkArgument(noOfBytes >= 0, "noOfBytes cannot be negative");

if (noOfBytes == 0) {
return new byte[] {};
}

byte[] intBytes = new byte[noOfBytes];
for (int i = noOfBytes-1; i >= 0; i--, value >>>= 8) {
intBytes[i] = (byte)value;
}
return intBytes;
}

/**
* Returns a big-endian representation of {@code value} as an n byte array, where
* n is the {@code noOfBytes}.
*
* <p>Returns an empty array if {@code noOfBytes} is {@code 0}
*
* <p> Example: {@code Numbers.toByteArray(0x12131415,4)} will return a byte array
* {@code {0x12, 0x13, 0x14, 0x15}}.
*
* @param value any long value
* @param noOfBytes non-negative number of bytes
* @return a big-endian representation of value as a byte array.
* @throws IllegalArgumentException if {@code noOfBytes} is negative
*/
public static byte[] toByteArray(long value, int noOfBytes) {
checkArgument(noOfBytes >= 0, "noOfBytes cannot be negative");

if (noOfBytes == 0) {
return new byte[] {};
}

byte[] longBytes = new byte[noOfBytes];
for (int i = noOfBytes-1; i >= 0; i--, value >>>= 8) {
longBytes[i] = (byte)value;
}
return longBytes;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing integer representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed integer value on successful parsing or otherwise instead
*/
public static int parseInt(String value, int otherwise) {
return parseInt(value, Predicates.<Integer>alwaysTrue(), otherwise);
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing integer representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed integer value on successful parsing or otherwise instead
*/
public static Integer parseInt(String value, Integer otherwise) {
return parseInt(value, Predicates.<Integer>alwaysTrue(), otherwise);
}

/**
* Parses the string {@code value} using {@link Long#parseLong(String)} and returns
* the parsed value if parsing was successful or returns {@code otherwise} instead.
*
* @param value string containing long representation to be parsed
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* @return parsed long value on successful parsing or otherwise instead
*/
public static long parseLong(String value, long otherwise) {
long result = otherwise;
try {
result = Long.parseLong(value);
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful and the parsed value satisfies the
* predicate else returns {@code otherwise}.
*
* <p>
* Usage: Parse a string which should be a positive integer
* <pre>
*  int parsedPositiveValue = Numbers.parseInt("100", Numbers.POSITIVE_INT, DEFAULT_VALUE);
* </pre>
* @param value string containing integer representation to be parsed
* @param predicate a non-null predicate that the parsed value must satisfy
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* or the parsed value does not satisfy the predicate
* @return parsed integer value on successful parsing or otherwise instead
*/
public static int parseInt(String value, Predicate<Integer> predicate, int otherwise) {
int result = otherwise;
try {
result = Integer.parseInt(value);
result = predicate.apply(result) ? result : otherwise;
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

/**
* Parses the string {@code value} using {@link Integer#parseInt(String)} and returns
* the parsed value if parsing was successful and the parsed value satisfies the
* predicate else returns {@code otherwise}.
*
* <p>
* Usage: Parse a string which should be a positive integer
* <pre>
*  Integer parsedPositiveValue = Numbers.parseInt("100", Numbers.POSITIVE_INT, DEFAULT_VALUE);
* </pre>
* @param value string containing integer representation to be parsed
* @param predicate a non-null predicate that the parsed value must satisfy
* @param otherwise value to be returned if parsing causes {@code NumberFormatException}
* or the parsed value does not satisfy the predicate
* @return parsed integer value on successful parsing or otherwise instead
*/
public static Integer parseInt(String value, Predicate<Integer> predicate, Integer valueOtherwise) {
Integer result = valueOtherwise;
try {
result = Integer.parseInt(value);
result = predicate.apply(result) ? result : valueOtherwise;
} catch (NumberFormatException nfe) {
LogManager.getLogger().trace(nfe);
}
return result;
}

private static class PositiveIntPredicate implements Predicate<Integer> {
@Override
public boolean apply(Integer input) {
return input != null ? input > 0 : false;
}
}

private static class PositiveLongPredicate implements Predicate<Long> {
@Override
public boolean apply(Long input) {
return input != null ? input.longValue() > 0 : false;
}
}
}

Wednesday, September 16, 2015

JAVA Closeables Utility


import java.io.Closeable;
import java.io.IOException;
import java.net.ServerSocket;



/**
 * A set of utilities for all {@link Closeable}s
 *
 */
public class Closeables {

/**
* Closes the {@code closeable} passed ignoring any I/O exception by logging.
* Does nothing if {@code closeable} is {@code null}.
*
* @param closeable closeable to be closed, does nothing if {@code null}
*/
public static void closeQuietly(Closeable closeable) {
if (closeable == null) {
return;
}

try {
closeable.close();
} catch (IOException e) {

}
}

/**
* Closes all the {@code closeables} passed ignoring any I/O exceptions by logging.
* Skips any {@code null}s that occur.
*
* @param closeables all the closeables to be closed, does nothing if {@code null} is passed
*/
public static void closeQuietly(Closeable... closeables){
if (closeables == null) {
return;
}

for (Closeable closeable : closeables) {
closeQuietly(closeable);
}

}

/**
* Closes the {@code serverSocket} passed, ignoring any I/O exception by logging.
* Does nothing if {@code serverSocket} is {@code null}.
*
* @param serverSocket a nullable server socket to be closed, does nothing if null
*/
public static void closeQuietly(ServerSocket serverSocket) {
if (serverSocket == null) {
return;
}

try {
serverSocket.close();
} catch (IOException e) {

}
}
}

Monday, September 14, 2015

JAVA ByteStreams Utility class


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;



/**
 *
 * A set of utilities for byte oriented streams.
 *
 */
public class ByteStreams {

private static final int EOF = -1;
private static final int ONE_KB = 1024;

/**
* Reads {@code noOfBytesRequested} bytes from given input stream and returns
* read bytes as a byte-array.
*
* <p>Reads from the stream only when sufficient amount of bytes are available
* in the stream, throws IOException otherwise.
*
* @param inputStream a non-null input stream from which bytes will be read
* @param noOfBytesRequested a non-negative number of bytes to read
* @return bytes read from the stream
* @throws IOException if sufficient bytes are unavailable in stream or if there
* is some error while reading from the stream.
* @throws IllegalArgumentException if {@code noOfBytesRequested} is less than 0
*/
public static byte[] readBytes(InputStream inputStream, int noOfBytesRequested) throws IOException, IllegalArgumentException {
checkNotNull(inputStream, "inputStream is null");
checkArgument(noOfBytesRequested >= 0, "noOfBytes cannot be negative");

if (inputStream.available() < noOfBytesRequested) {
throw new IOException("insufficient bytes available: "
+ inputStream.available() + ", requested: " + noOfBytesRequested);
}

byte[] bytes = new byte[noOfBytesRequested];
inputStream.read(bytes);
return bytes;
}

/**
* Reads {@code noOfBytesRequested} bytes from given input stream and returns
* read bytes as a byte-array.
*
* <p>Does best effort to read requested number of bytes from the stream. Reads requested
* number of bytes from stream if available or reads available number of bytes.
*
* @param inputStream a non-null input stream from which bytes will be read
* @param noOfBytesRequested a non-negative number of bytes to read
* @return bytes read from the stream
* @throws IOException if sufficient bytes are unavailable in stream or if there
* is some error while reading from the stream.
* @throws IllegalArgumentException if {@code noOfBytesRequested} is less than 0
*/
public static byte[] tryReadBytes(InputStream inputStream, int noOfBytesRequested) throws IOException {
checkNotNull(inputStream, "inputStream is null");
checkArgument(noOfBytesRequested >= 0, "noOfBytes cannot be negative");

int byteCountToRead = inputStream.available() < noOfBytesRequested
? inputStream.available() : noOfBytesRequested;

byte[] bytes = new byte[byteCountToRead];
inputStream.read(bytes);
return bytes;
}

/**
* A utility to provide non-exception throwing method for writing bulk bytes to
* {@code ByteArrayOutputStream}.
*
* <p>Tries to <i>silently</i> write given bytes to stream swallowing any I/O exception
* while writing by logging.
*
* @param inputStream a non-null {@code ByteArrayOutputStream} in which bytes will be written
* @param bytesToWrite non-null bytes to write
*
*/
public static void writeBytesSilently(ByteArrayOutputStream inputStream, byte... bytesToWrite) {
checkNotNull(inputStream, "inputStream is null");
checkNotNull(bytesToWrite, "bytesToWrite are null");

try {
inputStream.write(bytesToWrite);
} catch (IOException e) {
LogManager.getLogger().trace(e);
}
}

/**
* Read all available bytes in the stream until EOF (-1) is detected.
*
* <p><b>WARNING:</b> This call may block until {@code read()} on input stream
* returns.
*
* <p><b>NOTE:</b> Does not close the input stream
*
* @param inputStream a non-null input stream from which bytes will be read
* @return bytes read from the stream. Returns an empty byte array if the stream has
* reached EOF.
*
* @throws IOException if there is any exception while reading from stream
*/
public static byte[] readFully(InputStream inputStream) throws IOException {
checkNotNull(inputStream, "inputStream is null");

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[ONE_KB];
int i;

while (true) {
i = inputStream.read(buffer);

if (i == EOF){
break;
}

out.write(buffer, 0, i);
}

return out.toByteArray();
}


/**
* Checks if {@code requiredAvailability} number of bytes are available in {@code stream}. If insufficient bytes are available
* then it throws {@code IOException}.
*
* @param inputStream a non-null stream from which availability will be checked
* @param requiredAvailability a non-negative value
* @throws IOException if any I/O error occurs
* @throws IllegalArgumentException if {@code requiredAvailability} is negative
*/
public static void checkAvailability(InputStream inputStream, int requiredAvailability) throws IOException {
checkNotNull(inputStream, "inputStream is null");
checkArgument(requiredAvailability >= 0, "requiredAvailability count should be non-negative: " + requiredAvailability);

int available = inputStream.available();
if (available < requiredAvailability) {
throw new IOException("Insufficient bytes available in stream, required: "
+ requiredAvailability + " available: " + available);
}
}

/**
* Checks if {@code requiredAvailability} number of bytes are available in {@code stream}. If insufficient bytes are available
* then it throws {@code IOException}.
*
* @param inputStream a non-null stream from which availability will be checked
* @param requiredAvailability a non-negative value
* @param message will be used as message of IOException if sufficient bytes are unavailable
* @throws IOException if any I/O error occurs
* @throws IllegalArgumentException if {@code requiredAvailability} is negative
*/
public static void checkAvailability(InputStream inputStream, int requiredAvailability, String message) throws IOException {
checkNotNull(inputStream, "inputStream is null");
checkArgument(requiredAvailability >= 0, "requiredAvailability count should be non-negative: " + requiredAvailability);

if (inputStream.available() < requiredAvailability) {
throw new IOException(message);
}
}

/**
* Reads {@code byteCount} number of bytes from the {@code inputStream} and converts
* them to integer.
*
* <p>NOTE: It is expected that at least {@code byteCount} number of bytes must be available in
* the stream.
*
* @param inputStream a non-null input stream
* @param byteCount number of bytes in closed range [0:4] that will be read
* @return integer value read from the stream
* @throws IOException if any I/O error occurs or {@code byteCount} number of bytes
* are unavailable in stream
* @throws IllegalArgumentException if {@code byteCount} does not fall in closed range [0:4]
*/
/*
* This code has been copied from Bytes.toInt() for performance purposes. Reflect any changes
* there as well.
*/
public static int readInt(InputStream inputStream, int byteCount) throws IOException {
checkArgument(byteCount >= 0 && byteCount <= 4, "byteCount should be in closed-range [0:4], found: " + byteCount);
checkAvailability(inputStream, byteCount);

int value = 0;
for (int i = 0; i < byteCount; i++) {
value = value << 8 | (inputStream.read() & 0xFF);
}

return value;
}

/**
* Reads 4 bytes from the {@code inputStream} and converts them to integer.
*
* <p>NOTE: It is expected that at least 4 bytes must be available in the stream.
*
* @param inputStream a non-null input stream
* @return integer value read from the stream
* @throws IOException if any I/O error occurs or 4 bytes are unavailable in stream
*/
public static int readInt(InputStream inputStream) throws IOException{
return readInt(inputStream, 4);
}

/**
* Reads {@code byteCount} number of bytes from the {@code inputStream} and converts
* them to long.
*
* <p>NOTE: It is expected that at least {@code byteCount} number of bytes must be available in
* the stream.
*
* @param inputStream a non-null input stream
* @param byteCount number of bytes in closed range [0:8] that will be read
* @return long value read from the stream
* @throws IOException if any I/O error occurs or {@code byteCount} number of bytes
* are unavailable in stream
* @throws IllegalArgumentException if {@code byteCount} does not fall in closed range [0:8]
*/
/*
* This code has been copied from Bytes.toLong() for performance purposes. Reflect any changes
* there as well.
*/
public static long readLong(InputStream inputStream, int byteCount) throws IOException {
checkArgument(byteCount >= 0 && byteCount <= 8, "byteCount should be in closed-range [0:8], found: " + byteCount);
checkAvailability(inputStream, byteCount);

long value = 0;
for (int i = 0; i < byteCount; i++) {
value = value << 8 | (inputStream.read() & 0xFF);
}
return value;
}

/**
* Reads 8 bytes from the {@code inputStream} and converts them to long.
*
* <p>NOTE: It is expected that at least 8 bytes must be available in the stream.
*
* @param inputStream a non-null input stream
* @return long value read from the stream
* @throws IOException if any I/O error occurs or 8 bytes are unavailable in stream
*/
public static long readLong(InputStream inputStream) throws IOException {
return readLong(inputStream, 8);
}

/**
* Copies all bytes from the input stream to the output stream.
* <p>It is recommended to use this method when copying whole streams as it works
* in a memory efficient manner. It reads bytes from input stream in chunks of
* 1 KB and writes them to the output stream. So this method does not hog up a lot
* of memory.
*
* <p><b>NOTE:</b> Does not close any of the streams
*
* @param inputStream a non-null input stream to read from
* @param outputStream a non-null output stream to write to
* @throws IOException if an I/O error occurs
* @throws NullPointerException if any of stream is null
*/
public static void copy(InputStream inputStream, OutputStream outputStream) throws IOException {
checkNotNull(inputStream, "inputStream is null");
checkNotNull(outputStream, "outputStream is null");

byte[] buffer = new byte[ONE_KB];
int i;
while (true) {
i = inputStream.read(buffer);
if (i == EOF) {
break;
}
outputStream.write(buffer, 0, i);
}
}
}



public class Preconditions {
private Preconditions(){}

/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
*     string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}

/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
*     string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
/**
* Ensures the truth of an expression involving the state of the calling instance, but not
* involving any parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
*     string using {@link String#valueOf(Object)}
* @throws IllegalStateException if {@code expression} is false
*/
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
}

Java Bytes Utility class


/**
 * A set of byte related utilities, best used as static imports.
 *
 */
public class Bytes {

/**
* Converts {@code bytes} to integer.
*
* <p>Usage:<br/>
* <code>Bytes.toInt(new byte[]{0x00, 0x01, 0x00})</code> will return {@code 256}
* @param bytes a non-null byte array with length less than or equal to 4
* @return converted integer value
* @throws IllegalArgumentException if {@code bytes.length} is greater than 4
*/
public static int toInt(byte[] bytes) {
checkNotNull(bytes, "bytes are null");
checkArgument(bytes.length <= 4, "byteCount should be in closed-range [0:4], found: " + bytes.length);

return toIntInternal(bytes, 0, bytes.length);
}

private static int toIntInternal(byte[] bytes, int startIndex, int endIndex) {
int value = 0;
for (int i = startIndex; i < endIndex; i++) {
value = value << 8 | (bytes[i] & 0xFF);
}

return value;
}

/**
* Converts {@code bytes} to long.
*
* <p>Usage:<br/>
* <code>Bytes.toLong(new byte[]{0x00, 0x01, 0x00, 0x01})</code> will return {@code 65537}
* @param bytes a non-null byte array with length less than or equal to 8
* @return converted long value
* @throws IllegalArgumentException if {@code bytes.length} is greater than 8
*/
public static long toLong(byte[] bytes) {
checkNotNull(bytes, "bytes are null");
checkArgument(bytes.length <= 8, "byteCount should be in closed-range [0:8], found: " + bytes.length);

return toLongInternal(bytes, 0, bytes.length);
}

private static long toLongInternal(byte[] bytes, int startIndex, int endIndex) {
long value = 0;
for (int i = startIndex; i < endIndex; i++) {
value = value << 8 | (bytes[i] & 0xFF);
}

return value;
}

/**
* Returns the values from each provided array combined into a single array.
* For example,<br/>
* <code>concat(new byte[] {a, b}, new byte[] {}, new
* byte[] {c}</code> returns the array <code> {a, b, c}</code>.
*
* @param arrays zero or more {@code byte} arrays
* @return a single array containing all the values from the source arrays, in
* order
*/
public static byte[] concat(byte[]... byteArrays) {
int length = 0;
for (byte[] byteArray : byteArrays) {
length += byteArray.length;
}

byte[] result = new byte[length];
int position = 0;
for (byte[] byteArray : byteArrays) {
System.arraycopy(byteArray, 0, result, position, byteArray.length);
position += byteArray.length;
}
return result;
}
}

public class Preconditions {
private Preconditions(){}

/**
* Ensures that an object reference passed as a parameter to the calling method is not null.
*
* @param reference an object reference
* @param errorMessage the exception message to use if the check fails; will be converted to a
*     string using {@link String#valueOf(Object)}
* @return the non-null reference that was validated
* @throws NullPointerException if {@code reference} is null
*/
public static <T> T checkNotNull(T reference, Object errorMessage) {
if (reference == null) {
throw new NullPointerException(String.valueOf(errorMessage));
}
return reference;
}

/**
* Ensures the truth of an expression involving one or more parameters to the calling method.
*
* @param expression a boolean expression
* @param errorMessage the exception message to use if the check fails; will be converted to a
*     string using {@link String#valueOf(Object)}
* @throws IllegalArgumentException if {@code expression} is false
*/
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
}

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...