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));
}
}
}

Wednesday, September 9, 2015

Java Arrays Utility

public class Arrayz {

    /**
     * Returns true if the array passed is {@code null} or has no elements
     *
     * @param array a nullable array to be checked
     * @return true if array is null or has no elements
     */
    public static <T> boolean isNullOrEmpty(T...array) {
        return array == null || array.length == 0;
    }
}

Tuesday, September 8, 2015

JAVA Strings Utility methods

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

/**
 * A set of commonly used utilities for {@link String}s
 * */
public class Strings {

    /**
     * A function that encodes any Object string value i.e.
     * {@code String.valueOf(object)}, within single-quotes (')
     */
    public static final Function<Object, String> WITHIN_SINGLE_QUOTES = new WithinSingleQuoteFunction();
    private static final Function<Object, String> TO_STRING_FUNCTION = new ToStringFunction();

    /**
     * Returns {@code true} if the string is {@code null} or is an empty string. <br/>
     * <br/>
     * <b>NOTE:</b> Does not consider any whitespace characters in the string as
     * empty. If you want to consider whitespace characters as effectively empty
     * then use {@link Strings#isNullOrBlank(String)} instead.
     *
     * <br/>
     * <br/>
     * Example: <br/> {@code Strings.isNullOrEmpty(null)} or
     * {@code Strings.isNullOrEmpty("")} will return true
     *
     * @param inputString
     *            string reference to check
     * @return {@code true} if the string is null or is an empty string
     */
    public static boolean isNullOrEmpty(String inputString) {
        return inputString == null || inputString.length() == 0;
    }

    /**
     * Returns {@code true} if the optional string is <i>absent</i> or is an
     * empty string. <br/>
     * <br/>
     * <b>NOTE:</b> Does not consider any whitespace characters in the string as
     * empty. If you want to consider whitespace characters as effectively empty
     * then use {@link Strings#isAbsentOrBlank(String)} instead.
     *
     * <br/>
     * <br/>
     * Example: <br/> {@code Strings.isAbsentOrEmpty(Optional.absent())} or
     * {@code Strings.isNullOrEmpty(Optional.of("")} will return true
     *
     * @param a
     *            non-null optional inputString string reference to check
     * @return {@code true} if the optional string is absent or is an empty
     *         string
     */
    public static boolean isAbsentOrEmpty(Optional<String> optionalInputString) {
        return optionalInputString.isPresent() == false
                || optionalInputString.get().length() == 0;
    }

    /**
     * Returns {@code true} if the string is {@code null} or is a blank string.
     * Considers any whitespace characters as blank. Trims the string to check
     * for blankness.
     *
     * <br/>
     * <br/>
     * <b>NOTE:</b> Does consider any whitespace characters in the string as
     * empty. If you do not want to consider whitespace characters as
     * effectively empty then use {@link Strings#isNullOrEmpty(String)} instead.
     *
     * <br/>
     * <br/>
     * Example: <br/> {@code Strings.isNullOrBlank(null)} or
     * {@code Strings.isNullOrBlank(" ")} will return true
     *
     * @param inputString
     *            string reference to check
     * @return {@code true} if the string is null or is a blank string
     *         (considering space, \t or other whitespace characters as blank)
     */
    public static boolean isNullOrBlank(String inputString) {
        return inputString == null || inputString.trim().length() == 0;
    }

    /**
     * Returns {@code true} if the optional string is <i>absent</i> or is a
     * blank string. Considers any whitespace characters as blank. Trims the
     * string to check for blankness.
     *
     * <br/>
     * <br/>
     * <b>NOTE:</b> Does consider any whitespace characters in the string as
     * empty. If you do not want to consider whitespace characters as
     * effectively empty then use {@link Strings#isAbsentOrEmpty(String)}
     * instead.
     *
     * <br/>
     * <br/>
     * Example: <br/> {@code Strings.isAbsentOrBlank(Optinal.absent())} or
     * {@code Strings.isAbsentOrBlank(Optional.of(" ")} will return true
     *
     * @param a
     *            non-null optional inputString string reference to check
     * @return {@code true} if the optional string is absent or is a blank
     *         string (considering space, \t or other whitespace characters as
     *         blank)
     * @throws NullPointerException
     *             if inputString is null
     */
    public static boolean isAbsentOrBlank(Optional<String> optionalInputString) {
        return optionalInputString.isPresent() == false
                || optionalInputString.get().trim().length() == 0;
    }

    /**
     * Returns a string consisting of a specific number of concatenated copies
     * of an input string. For example, {@code repeat("hey", 3)} returns the
     * string {@code "heyheyhey"}.
     *
     * @param string
     *            any non-null string
     * @param count
     *            the number of times to repeat it; a nonnegative integer
     * @return a string containing {@code string} repeated {@code count} times
     *         (the empty string if {@code count} is zero)
     * @throws IllegalArgumentException
     *             if {@code count} is negative
     */
    public static String repeat(String string, int count) {
        checkNotNull(string, "string is null");

        if (count <= 1) {
            checkArgument(count >= 0, "invalid count: " + count);
            return (count == 0) ? "" : string;
        }

        final int len = string.length();
        final long longSize = (long) len * (long) count;
        final int size = (int) longSize;
        if (size != longSize) {
            throw new ArrayIndexOutOfBoundsException(
                    "Required array size too large: " + longSize);
        }

        final char[] array = new char[size];
        string.getChars(0, len, array, 0);
        int n;
        for (n = len; n < size - n; n <<= 1) {
            System.arraycopy(array, 0, array, n, n);
        }
        System.arraycopy(array, 0, array, n, size - n);
        return new String(array);
    }

    /**
     * Joins the String representation ( {@code String.valueOf(..)} ) of each
     * part given in {@code parts} array using the separator provided.
     *
     * <p>
     * Example: <code>
     *   Strings.join(",", new String[]{"a","b"})
     * }</code> will return {@code a,b}
     * <p>
     * <b>NOTE:</b> This method skips any {@code null} parts encountered.
     *
     * <p>
     * Example: {@code Strings.join(",", new String[] "a",null,"b"})} will
     * return {@code a,b}
     *
     * @param separator
     *            any non-null string
     * @param parts
     *            are the objects whose string representation will be joined
     *            using separator
     * @return a string containing the string representation of each part with
     *         separator in between each
     */
    public static String join(String separator, Object[] parts) {
        return join(separator, parts, TO_STRING_FUNCTION);
    }

    /**
     * Joins the String representation of each part in {@code parts} by applying
     * {@code partFunction} on it, using the separator provided.
     *
     * <p>
     * Example: <code>
     *   Strings.join(",", new String[]{"a","b"}, Strings.WITHIN_SINGLE_QUOTES)
     * }</code> will return {@code 'a','b'}
     * <p>
     * <b>NOTE:</b> This method skips any {@code null} parts encountered.
     *
     * <p>
     * Example: {@code Strings.join(",", new String[] "a",null,"b"},
     * Strings.WITHIN_SINGLE_QUOTES)} will return {@code 'a','b'}
     *
     * @param separator
     *            any non-null string
     * @param parts
     *            are the objects whose string representation will be joined
     *            using separator
     * @param partFunction
     *            a non-null function that will be applied to all non-null parts
     * @return a string containing the string representation of each part with
     *         separator in between each
     */
    public static String join(String separator, Object[] parts,
            Function<Object, String> partFunction) {
        checkNotNull(parts, "parts are null");
        return join(separator, Arrays.asList(parts), partFunction);
    }

    /**
     * @see Strings#join(String, Object[])
     */
    public static String join(String string, Iterable<?> parts) {
        return join(string, parts, TO_STRING_FUNCTION);
    }

    /**
     * @see Strings#join(String, Object[], Function)
     */
    public static String join(String string, Iterable<?> parts,
            Function<Object, String> partFunction) {
        checkNotNull(parts, "parts are null");
        return join(string, parts.iterator(), partFunction);
    }

    private static String join(String separator, Iterator<?> parts,
            Function<Object, String> partFunction) {
        checkNotNull(separator, "separator is null");
        checkNotNull(partFunction, "partFunction is null");

        StringBuilder builder = new StringBuilder();

        while (parts.hasNext()) {
            Object part = parts.next();
            if (part != null) {
                builder.append(partFunction.apply(part));
                break;
            }
        }

        while (parts.hasNext()) {
            Object part = parts.next();
            if (part != null) {
                builder.append(separator);
                builder.append(partFunction.apply(part));
            }
        }
        return builder.toString();
    }

    /**
     * Returns a string, of length at least {@code minLength}, consisting of
     * {@code string} prepended with as many copies of {@code padChar} as are
     * necessary to reach that length. For example,
     *
     * <ul>
     * <li>{@code padStart("7", 3, '0')} returns {@code "007"}
     * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"}
     * </ul>
     *
     * @param string
     *            the string which should appear at the end of the result
     * @param minLength
     *            the minimum length the resulting string must have. Can be zero
     *            or negative, in which case the input string is always
     *            returned.
     * @param padChar
     *            the character to insert at the beginning of the result until
     *            the minimum length is reached
     * @return the padded string
     */
    public static String padStart(String string, int minLength, char padChar) {
        checkNotNull(string, "string is null");
        if (string.length() >= minLength) {
            return string;
        }

        int padCount = minLength - string.length();
        StringBuilder builder = new StringBuilder(minLength);
        for (int i = 0; i < padCount; i++) {
            builder.append(padChar);
        }

        builder.append(string);
        return builder.toString();
    }

    /**
     * Returns a string, of length at least {@code minLength}, consisting of
     * {@code string} appended with as many copies of {@code padChar} as are
     * necessary to reach that length. For example,
     *
     * <ul>
     * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"}
     * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"}
     * </ul>
     *
     * @param string
     *            the string which should appear at the beginning of the result
     * @param minLength
     *            the minimum length the resulting string must have. Can be zero
     *            or negative, in which case the input string is always
     *            returned.
     * @param padChar
     *            the character to append to the end of the result until the
     *            minimum length is reached
     * @return the padded string
     */
    public static String padEnd(String string, int minLength, char padChar) {
        checkNotNull(string, "string is null");
        if (string.length() >= minLength) {
            return string;
        }

        int padCount = minLength - string.length();
        StringBuilder builder = new StringBuilder(minLength);
        builder.append(string);
        for (int i = 0; i < padCount; i++) {
            builder.append(padChar);
        }

        return builder.toString();
    }

    static class WithinSingleQuoteFunction implements Function<Object, String> {

        private static final String SINGLE_QUOTE = "'";

        @Override
        public String apply(Object input) {
            return SINGLE_QUOTE + TO_STRING_FUNCTION.apply(input)
                    + SINGLE_QUOTE;
        }
    }

    static class ToStringFunction implements Function<Object, String> {

        @Override
        public String apply(Object input) {
            return String.valueOf(input);
        }
    }

    /**
     * Provides a splitter for given separator.
     *
     * @param separator
     *            on which split is done.
     *
     * @return Splitter on Separator.
     * @see Splitter
     */
    public static Splitter splitter(final char separator) {
        return Splitter.on(separator);
    }

    /**
     * Returns predicate which evaluates to true if the string passed is
     * non-null and non-empty. It can be used in other utilities such as
     * {@link Collectionz#filter(java.util.Collection, Predicate)}
     *
     * <p>
     * Usage:
     *
     * <pre>
     * <code>Collectionz.filter(unfilteredCollection, Strings.nonNullAndNonEmpty())
     * </code>
     * </pre>
     *
     * @return predicate which evaluates to true if the string passed is
     *         non-null and non-empty
     * @see Predicate
     * @see Collectionz
     */
    public static Predicate<String> nonNullAndNonEmpty() {
        return NonNullAndNonEmpty.INSTANCE;
    }

    private static enum NonNullAndNonEmpty implements Predicate<String> {
        INSTANCE;

        @Override
        public boolean apply(String input) {
            return isNullOrEmpty(input) == false;
        }
    }

    /**
     * Returns predicate which evaluates to true if the string passed is
     * non-null and non-blank (whitespace characters are considered as empty).
     * It can be used in other utilities such as
     * {@link Collectionz#filter(java.util.Collection, Predicate)}
     *
     * <p>
     * Usage:
     *
     * <pre>
     * <code>Collectionz.filter(unfilteredCollection, Strings.nonNullAndNonBlank())
     * </code>
     * </pre>
     *
     * @return predicate which evaluates to true if the string passed is
     *         non-null and non-blank
     * @see Predicate
     * @see Collectionz
     */
    public static Predicate<String> nonNullAndNonBlank() {
        return NonNullAndNonBlank.INSTANCE;
    }

    private static enum NonNullAndNonBlank implements Predicate<String> {
        INSTANCE;

        @Override
        public boolean apply(String input) {
            return isNullOrBlank(input) == false;
        }
    }

    /**
     * Filters all null or empty elements from the underlying {@code collection}
     *
     * <p>
     * <b>NOTE: </b>Does not remove blank elements, use
     * {@link Strings#filterNullOrBlank(Collection)} for that.
     *
     * <p>
     * It has the same effect as calling
     * {@code Collectionz.filter(collection, Strings.nonNullAndNonEmpty());}
     *
     * @param collection
     *            a non-null collection of strings
     * @throws NullPointerException
     *             if collection passed is null
     */
    public static void filterNullOrEmpty(Collection<String> collection) {
        Collectionz.filter(collection, nonNullAndNonEmpty());
    }

    /**
     * Filters all null or blank elements from the underlying {@code collection}
     * , elements containing just whitespace characters are also removed from
     * the collection.
     *
     * <p>
     * <b>NOTE: </b>For removing just empty elements, use
     * {@link Strings#filterNullOrEmpty(Collection)} for that.
     *
     * <p>
     * It has the same effect as calling
     * {@code Collectionz.filter(collection, Strings.nonNullAndNonBlank());}
     *
     * @param collection
     *            a non-null collection of strings
     * @throws NullPointerException
     *             if collection passed is null
     */
    public static void filterNullOrBlank(Collection<String> collection) {
        Collectionz.filter(collection, nonNullAndNonBlank());
    }

    /**
     * Returns {@code true} if trimmed input is true or yes, false otherwise.
     * <p>
     * Note that this method trims the input and performs a case insensitive match.
     */
    public static boolean toBoolean(String booleanInString) {
        if (booleanInString == null) {
            return false;
        }
       
        String trimmedString = booleanInString.trim();
        return "true".equalsIgnoreCase(trimmedString)
                || "yes".equalsIgnoreCase(trimmedString);
    }

    /**
     * Returns a function that converts the string to integer.
     * <p>
     * Note that the returned function throws {@code NumberFormatException} if the
     * string does not contain a parsable integer.
     *
     * @see Integer#parseInt(String)
     */
    public static Function<String, Integer> toInt() {
        return ToIntFunction.INSTANCE;
    }
   
    private static enum ToIntFunction implements Function<String, Integer> {
        INSTANCE;
       
        @Override
        public Integer apply(String input) {
            return Integer.parseInt(input);
        }
    }
}

/**
 * Simple static methods to be called at the start of your own methods to verify
 * correct arguments and state. This allows constructs such as
 * <pre>
 *     if (count <= 0) {
 *       throw new IllegalArgumentException("must be positive: " + count);
 *     }</pre>
 *
 * to be replaced with the more compact
 * <pre>
 *     checkArgument(count > 0, "must be positive: %s", count);
 * </pre>
 *
 * Use of check nulls can be used before assigning the references for fail fast approach such as
 * <pre>
 *     class MyClass{
 *      public MyClass(Object arg1, Object arg2){
 *       this.arg1 = checkNotNull(arg1,"arg1 is null");
 *       this.arg2 = checkNotNull(arg2,"arg2 is null");
 *      }
 *     }</pre>
 *
 * <p><b>NOTE:</b> Best when used as static imports.
 *
 * 
 *
 */
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));
        }
    }
}

What is Hibernate ?


  • Its actual meaning is “To be active and Spending a long time in a asleep State”. Frogs and Lizards and many more does this in their life of Winter.  
  • Our Hibernate Framework also works the same way. It remains active behind the application.

  • Hibernate is the open source light weight Framework invented by Gavin King.
  • Hibernate is ORM based Framework , it transfer the data between an application and a database (Relational) in the form of the objects.
  • It is Object Relational Mapping (ORM) framework.
  • Hibernate is a non-invasive framework, means it will not force the programmer to extend/implement any class/interface, and in hibernate we have to use POJO classes so it is light weight framework.
  • Hibernate can be use for a standalone desktop application and also for web based application, In short it is suitable for all types of applications (stand alone or desktop or any web application)
  •  
  • Hibernate is use to insert/update/Select/delete data from Database.


It builds persistent objects using following Java feature:
Inheritance
Association
Composition
Polymorphism
Collections API for Mappings
Easy query feature
Hibernate Query Language (HQL)
Criteria Query
Query by Example

Wednesday, September 2, 2015

Servlet Container's Role

Loads the servlet.
Authenticate the user (if required).
Calls the service method.
Update the current session(if required).
Create a resuest object (javax.servlet.ServletRequest interface or the javax.servlet.http.ServletRequest).
Populate the required information in the request object.
Create a response object (javax.servlet.ServletResponse interface or the javax.servlet.http.ServletResponse).

WEB Server

A Web Server is also called a HTTP server. because it uses the HTTP protocol to communicate with its clients (web-browsers).

A java based web server mainly uses two classes
1) java.net.Socket
2) Java.net.ServerSocket
and the communication are done through the HTTP messages.

Here the HTTP protocol  plays a main role to send and receive the data over the Internet.
HTTP is a request and response protocol.
The client sends the request and the server sends the response.

Difference between Tomcat 4 and 5

Tomcat 5 supports Servlet 2.4 and Tomcat 4 supports Servlet 2..

Tomcat 5 supports JSP 2.0 specifications, Tomcat 4 JSP 1.2. 



Tomcat 5 does not need a mapper component to find a child component, therefore simplifying the code.
Tomcat 5 has a more efficient default connector than Tomcat 4. 

Tomcat 5 shares a thread for background processing whereas Tomcat 4's components all have their own threads for background processing. 

Therefore, Tomcat 5 uses less resources in this regard.


Tuesday, September 1, 2015

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...