Java Timestamp argMapTimestamp(Map argMap, Map argMapNotUsed, String key)

Here you can find the source of argMapTimestamp(Map argMap, Map argMapNotUsed, String key)

Description

get the value from the argMap, throw exception if not there and required

License

Apache License

Parameter

Parameter Description
argMap a parameter
argMapNotUsed a parameter
key a parameter

Return

the value or null or exception

Declaration

public static Timestamp argMapTimestamp(Map<String, String> argMap,
        Map<String, String> argMapNotUsed, String key) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2012 Internet2//from   w ww  . java  2s  .c o  m
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;

import java.lang.reflect.Modifier;

import java.sql.Timestamp;

import java.util.ArrayList;

import java.util.Calendar;
import java.util.Collection;

import java.util.Date;

import java.util.Iterator;

import java.util.List;
import java.util.Map;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    /**
     * match regex pattern yyyy-mm-dd or yyyy/mm/dd
     */
    private static Pattern datePattern_yyyy_mm_dd = Pattern
            .compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
    /**
     * match regex pattern dd-mon-yyyy or dd/mon/yyyy
     */
    private static Pattern datePattern_dd_mon_yyyy = Pattern
            .compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})$");
    /**
     * match regex pattern yyyy-mm-dd hh:mm:ss or yyyy/mm/dd hh:mm:ss
     */
    private static Pattern datePattern_yyyy_mm_dd_hhmmss = Pattern
            .compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
    /**
     * match regex pattern dd-mon-yyyy hh:mm:ss or dd/mon/yyyy hh:mm:ss
     */
    private static Pattern datePattern_dd_mon_yyyy_hhmmss = Pattern
            .compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})$");
    /**
     * match regex pattern yyyy-mm-dd hh:mm:ss.SSS or yyyy/mm/dd hh:mm:ss.SSS
     */
    private static Pattern datePattern_yyyy_mm_dd_hhmmss_SSS = Pattern
            .compile("^(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,3})$");
    /**
     * match regex pattern dd-mon-yyyy hh:mm:ss.SSS or dd/mon/yyyy hh:mm:ss.SSS
     */
    private static Pattern datePattern_dd_mon_yyyy_hhmmss_SSS = Pattern
            .compile("^(\\d{1,2})[^\\d]+([a-zA-Z]{3,15})[^\\d]+(\\d{4})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,2})[^\\d]+(\\d{1,3})$");

    /**
     * get the value from the argMap, throw exception if not there and required
     * @param argMap
     * @param argMapNotUsed 
     * @param key
     * @return the value or null or exception
     */
    public static Timestamp argMapTimestamp(Map<String, String> argMap,
            Map<String, String> argMapNotUsed, String key) {
        String argString = argMapString(argMap, argMapNotUsed, key, false);
        if (isBlank(argString)) {
            return null;
        }
        Date date = stringToDate2(argString);
        return new Timestamp(date.getTime());
    }

    /**
     * get the value from the argMap, throw exception if not there and required
     * @param argMap
     * @param argMapNotUsed 
     * @param key
     * @param required
     * @return the value or null or exception
     */
    public static String argMapString(Map<String, String> argMap,
            Map<String, String> argMapNotUsed, String key, boolean required) {

        if (argMap.containsKey(key)) {

            //keep track that this is gone
            argMapNotUsed.remove(key);

            return argMap.get(key);
        }
        if (required) {
            throw new RuntimeException("Argument '--" + key
                    + "' is required, but not specified.  e.g. --" + key
                    + "=value");
        }
        return null;

    }

    /**
     * See if the input is null or if string, if it is empty or blank (whitespace)
     * @param input
     * @return true if blank
     */
    public static boolean isBlank(Object input) {
        if (null == input) {
            return true;
        }
        return (input instanceof String && isBlank((String) input));
    }

    /**
     * <p>Checks if a String is whitespace, empty ("") or null.</p>
     *
     * <pre>
     * isBlank(null)      = true
     * isBlank("")        = true
     * isBlank(" ")       = true
     * isBlank("bob")     = false
     * isBlank("  bob  ") = false
     * </pre>
     *
     * @param str  the String to check, may be null
     * @return <code>true</code> if the String is null, empty or whitespace
     * @since 2.0
     */
    public static boolean isBlank(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if ((Character.isWhitespace(str.charAt(i)) == false)) {
                return false;
            }
        }
        return true;
    }

    /**
     * take as input:
     * yyyy/mm/dd
     * yyyy-mm-dd
     * dd-mon-yyyy
     * yyyy/mm/dd hh:mm:ss
     * dd-mon-yyyy hh:mm:ss
     * yyyy/mm/dd hh:mm:ss.SSS
     * dd-mon-yyyy hh:mm:ss.SSS
     * @param input
     * @return the date
     */
    public static Date stringToDate2(String input) {

        if (isBlank(input)) {
            return null;
        }
        input = input.trim();
        Matcher matcher = null;

        int month = 0;
        int day = 0;
        int year = 0;
        int hour = 0;
        int minute = 0;
        int second = 0;
        int milli = 0;

        boolean foundMatch = false;

        //yyyy/mm/dd
        if (!foundMatch) {
            matcher = datePattern_yyyy_mm_dd.matcher(input);
            if (matcher.matches()) {
                year = intValue(matcher.group(1));
                month = intValue(matcher.group(2));
                day = intValue(matcher.group(3));
                foundMatch = true;
            }
        }

        //dd-mon-yyyy
        if (!foundMatch) {
            matcher = datePattern_dd_mon_yyyy.matcher(input);
            if (matcher.matches()) {
                day = intValue(matcher.group(1));
                month = monthInt(matcher.group(2));
                year = intValue(matcher.group(3));
                foundMatch = true;
            }
        }

        //yyyy/mm/dd hh:mm:ss
        if (!foundMatch) {
            matcher = datePattern_yyyy_mm_dd_hhmmss.matcher(input);
            if (matcher.matches()) {
                year = intValue(matcher.group(1));
                month = intValue(matcher.group(2));
                day = intValue(matcher.group(3));
                hour = intValue(matcher.group(4));
                minute = intValue(matcher.group(5));
                second = intValue(matcher.group(6));
                foundMatch = true;
            }
        }

        //dd-mon-yyyy hh:mm:ss
        if (!foundMatch) {
            matcher = datePattern_dd_mon_yyyy_hhmmss.matcher(input);
            if (matcher.matches()) {
                day = intValue(matcher.group(1));
                month = monthInt(matcher.group(2));
                year = intValue(matcher.group(3));
                hour = intValue(matcher.group(4));
                minute = intValue(matcher.group(5));
                second = intValue(matcher.group(6));
                foundMatch = true;
            }
        }

        //yyyy/mm/dd hh:mm:ss.SSS
        if (!foundMatch) {
            matcher = datePattern_yyyy_mm_dd_hhmmss_SSS.matcher(input);
            if (matcher.matches()) {
                year = intValue(matcher.group(1));
                month = intValue(matcher.group(2));
                day = intValue(matcher.group(3));
                hour = intValue(matcher.group(4));
                minute = intValue(matcher.group(5));
                second = intValue(matcher.group(6));
                milli = intValue(matcher.group(7));
                foundMatch = true;
            }
        }

        //dd-mon-yyyy hh:mm:ss.SSS
        if (!foundMatch) {
            matcher = datePattern_dd_mon_yyyy_hhmmss_SSS.matcher(input);
            if (matcher.matches()) {
                day = intValue(matcher.group(1));
                month = monthInt(matcher.group(2));
                year = intValue(matcher.group(3));
                hour = intValue(matcher.group(4));
                minute = intValue(matcher.group(5));
                second = intValue(matcher.group(6));
                milli = intValue(matcher.group(7));
                foundMatch = true;
            }
        }

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, milli);
        return calendar.getTime();
    }

    /**
     * Remove the iterator or index
     * 
     * @param arrayOrCollection
     * @param index
     * @return the object list or new array
     */
    public static Object remove(Object arrayOrCollection, int index) {
        return remove(arrayOrCollection, null, index);
    }

    /**
     * Remove the iterator or index
     * 
     * @param arrayOrCollection
     * @param iterator
     * @param index
     * @return the object list or new array
     */
    public static Object remove(Object arrayOrCollection,
            Iterator iterator, int index) {

        //if theres an iterator, just use that
        if (iterator != null) {
            iterator.remove();
            return arrayOrCollection;
        }
        if (arrayOrCollection.getClass().isArray()) {
            int newLength = Array.getLength(arrayOrCollection) - 1;
            Object newArray = Array.newInstance(arrayOrCollection
                    .getClass().getComponentType(), newLength);
            if (newLength == 0) {
                return newArray;
            }
            if (index > 0) {
                System.arraycopy(arrayOrCollection, 0, newArray, 0, index);
            }
            if (index < newLength) {
                System.arraycopy(arrayOrCollection, index + 1, newArray,
                        index, newLength - index);
            }
            return newArray;
        }
        if (arrayOrCollection instanceof List) {
            ((List) arrayOrCollection).remove(index);
            return arrayOrCollection;
        } else if (arrayOrCollection instanceof Collection) {
            //this should work unless there are duplicates or something weird
            ((Collection) arrayOrCollection).remove(get(arrayOrCollection,
                    index));
            return arrayOrCollection;
        }
        throw new RuntimeException("Invalid class type: "
                + arrayOrCollection.getClass().getName());
    }

    /**
     * Get a specific index of an array or collection (note for collections and
     * iterating, it is more efficient to get an iterator and iterate
     * 
     * @param arrayOrCollection
     * @param index
     * @return the object at that index
     */
    public static Object get(Object arrayOrCollection, int index) {

        if (arrayOrCollection == null) {
            if (index == 0) {
                return null;
            }
            throw new RuntimeException("Trying to access index " + index
                    + " of null");
        }

        // no need to iterator on list (e.g. FastProxyList has no iterator
        if (arrayOrCollection instanceof List) {
            return ((List) arrayOrCollection).get(index);
        }
        if (arrayOrCollection instanceof Collection) {
            Iterator iterator = iterator(arrayOrCollection);
            for (int i = 0; i < index; i++) {
                next(arrayOrCollection, iterator, i);
            }
            return next(arrayOrCollection, iterator, index);
        }

        if (arrayOrCollection.getClass().isArray()) {
            return Array.get(arrayOrCollection, index);
        }

        if (index == 0) {
            return arrayOrCollection;
        }

        throw new RuntimeException("Trying to access index " + index
                + " of and object: " + arrayOrCollection);
    }

    /**
     * Null safe array length or map
     * 
     * @param arrayOrCollection
     * @return the length of the array (0 for null)
     */
    public static int length(Object arrayOrCollection) {
        if (arrayOrCollection == null) {
            return 0;
        }
        if (arrayOrCollection.getClass().isArray()) {
            return Array.getLength(arrayOrCollection);
        }
        if (arrayOrCollection instanceof Collection) {
            return ((Collection) arrayOrCollection).size();
        }
        if (arrayOrCollection instanceof Map) {
            return ((Map) arrayOrCollection).size();
        }
        // simple non array non collection object
        return 1;
    }

    /**
     * trim whitespace from string
     * @param str
     * @return trimmed string
     */
    public static String trim(String str) {
        return str == null ? null : str.trim();
    }

    /**
     * convert an object to a int
     * @param input
     * @return the number
     */
    public static int intValue(Object input) {
        if (input instanceof String) {
            String string = (String) input;
            return Integer.parseInt(string);
        }
        if (input instanceof Number) {
            return ((Number) input).intValue();
        }
        if (false) {
            if (input == null) {
                return 0;
            }
            if (input instanceof String || isBlank((String) input)) {
                return 0;
            }
        }

        throw new RuntimeException("Cannot convert to int: "
                + className(input));
    }

    /**
     * convert an object to a int
     * @param input
     * @param valueIfNull is if the input is null or empty, return this value
     * @return the number
     */
    public static int intValue(Object input, int valueIfNull) {
        if (input == null || "".equals(input)) {
            return valueIfNull;
        }
        return intObjectValue(input, false);
    }

    /**
     * convert a month string to an int (1 indexed).
     * e.g. if input is feb or Feb or february or February return 2
     * @param mon
     * @return the month
     */
    public static int monthInt(String mon) {

        if (!isBlank(mon)) {
            mon = mon.toLowerCase();

            if (equals(mon, "jan") || equals(mon, "january")) {
                return 1;
            }

            if (equals(mon, "feb") || equals(mon, "february")) {
                return 2;
            }

            if (equals(mon, "mar") || equals(mon, "march")) {
                return 3;
            }

            if (equals(mon, "apr") || equals(mon, "april")) {
                return 4;
            }

            if (equals(mon, "may")) {
                return 5;
            }

            if (equals(mon, "jun") || equals(mon, "june")) {
                return 6;
            }

            if (equals(mon, "jul") || equals(mon, "july")) {
                return 7;
            }

            if (equals(mon, "aug") || equals(mon, "august")) {
                return 8;
            }

            if (equals(mon, "sep") || equals(mon, "september")) {
                return 9;
            }

            if (equals(mon, "oct") || equals(mon, "october")) {
                return 10;
            }

            if (equals(mon, "nov") || equals(mon, "november")) {
                return 11;
            }

            if (equals(mon, "dec") || equals(mon, "december")) {
                return 12;
            }

        }

        throw new RuntimeException("Invalid month: " + mon);
    }

    /**
     * Construct a class
     * @param <T> template type
     * @param theClass
     * @return the instance
     */
    public static <T> T newInstance(Class<T> theClass) {
        try {
            return theClass.newInstance();
        } catch (Throwable e) {
            if (theClass != null
                    && Modifier.isAbstract(theClass.getModifiers())) {
                throw new RuntimeException("Problem with class: "
                        + theClass + ", maybe because it is abstract!", e);
            }
            throw new RuntimeException("Problem with class: " + theClass, e);
        }
    }

    /**
     * Construct a class
     * @param <T> template type
     * @param theClass
     * @param allowPrivateConstructor true if should allow private constructors
     * @return the instance
     */
    public static <T> T newInstance(Class<T> theClass,
            boolean allowPrivateConstructor) {
        if (!allowPrivateConstructor) {
            return newInstance(theClass);
        }
        try {
            Constructor<?>[] constructorArray = theClass
                    .getDeclaredConstructors();
            for (Constructor<?> constructor : constructorArray) {
                if (constructor.getGenericParameterTypes().length == 0) {
                    if (allowPrivateConstructor) {
                        constructor.setAccessible(true);
                    }
                    return (T) constructor.newInstance();
                }
            }
            //why cant we find a constructor???
            throw new RuntimeException(
                    "Why cant we find a constructor for class: " + theClass);
        } catch (Throwable e) {
            if (theClass != null
                    && Modifier.isAbstract(theClass.getModifiers())) {
                throw new RuntimeException("Problem with class: "
                        + theClass + ", maybe because it is abstract!", e);
            }
            throw new RuntimeException("Problem with class: " + theClass, e);
        }
    }

    /**
     * null safe iterator getter if the type if collection
     * 
     * @param collection
     * @return the iterator
     */
    public static Iterator iterator(Object collection) {
        if (collection == null) {
            return null;
        }
        // array list doesnt need an iterator
        if (collection instanceof Collection
                && !(collection instanceof ArrayList)) {
            return ((Collection) collection).iterator();
        }
        return null;
    }

    /**
     * If array, get the element based on index, if Collection, get it based on
     * iterator.
     * 
     * @param arrayOrCollection
     * @param iterator
     * @param index
     * @return the object
     */
    public static Object next(Object arrayOrCollection, Iterator iterator,
            int index) {
        if (arrayOrCollection.getClass().isArray()) {
            return Array.get(arrayOrCollection, index);
        }
        if (arrayOrCollection instanceof ArrayList) {
            return ((ArrayList) arrayOrCollection).get(index);
        }
        if (arrayOrCollection instanceof Collection) {
            return iterator.next();
        }
        // simple object
        if (0 == index) {
            return arrayOrCollection;
        }
        throw new RuntimeException("Invalid class type: "
                + arrayOrCollection.getClass().getName());
    }

    /**
     * null safe classname method, gets the unenhanced name
     * 
     * @param object
     * @return the classname
     */
    public static String className(Object object) {
        return object == null ? null : object.getClass().getName();
    }

    /**
     * null safe string compare
     * @param first
     * @param second
     * @return true if equal
     */
    public static boolean equals(String first, String second) {
        if (first == second) {
            return true;
        }
        if (first == null || second == null) {
            return false;
        }
        return first.equals(second);
    }

    /**
     * <p>Compares two objects for equality, where either one or both
     * objects may be <code>null</code>.</p>
     *
     * <pre>
     * ObjectUtils.equals(null, null)                  = true
     * ObjectUtils.equals(null, "")                    = false
     * ObjectUtils.equals("", null)                    = false
     * ObjectUtils.equals("", "")                      = true
     * ObjectUtils.equals(Boolean.TRUE, null)          = false
     * ObjectUtils.equals(Boolean.TRUE, "true")        = false
     * ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE)  = true
     * ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
     * </pre>
     *
     * @param object1  the first object, may be <code>null</code>
     * @param object2  the second object, may be <code>null</code>
     * @return <code>true</code> if the values of both objects are the same
     */
    public static boolean equals(Object object1, Object object2) {
        if (object1 == object2) {
            return true;
        }
        if ((object1 == null) || (object2 == null)) {
            return false;
        }
        return object1.equals(object2);
    }

    /**
     * get the Integer value of an object
     * 
     * @param input
     *          is a number or String
     * @param allowNullBlank true if convert null or blank to null
     * 
     * @return the Integer equivalent
     */
    public static Integer intObjectValue(Object input,
            boolean allowNullBlank) {

        if (input instanceof Integer) {
            return (Integer) input;
        }

        if (allowNullBlank && isBlank(input)) {
            return null;
        }

        return Integer.valueOf(intValue(input));
    }
}

Related

  1. addTime(java.sql.Timestamp start, int year, int month, int day)
  2. adjustTimestamp(Timestamp stamp, int adjType, int adjQuantity, TimeZone timeZone, Locale locale)
  3. adjustTimestamp(Timestamp stamp, Integer adjType, Integer adjQuantity)
  4. adjustTimestamp(Timestamp timestamp, String timezone, int gmtOffset)
  5. afterMinutes(Timestamp date, long min)
  6. beforeTimestamp2Safety(Timestamp ts1, Timestamp ts2)
  7. between(Timestamp t1, Timestamp t2)
  8. calcRealTime(Timestamp beginTime, Timestamp endTime)
  9. calendar2Timestamp(Calendar c)