/*
 * Copyright 2015 52°North Initiative for Geospatial Open Source
 * Software GmbH
 *
 * 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.
 */
package org.n52.iceland.util;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Set;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Sets;

/**
 * Helper class for Java objects.
 *
 * @since 1.0.0
 *
 */
public final class JavaHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(JavaHelper.class);

    /**
     * hexadecimal values
     */
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F' };

    /**
     * Message digest for generating single identifier
     */
    private static MessageDigest messageDigest;

    /**
     * Generates a sensor id from description and current time as long.
     *
     * @param message
     *            sensor description
     * @return generated sensor id as hex SHA-1.
     * @throws NoSuchAlgorithmException
     */
    public static String generateID(final String message) {
        final long autoGeneratredID = new DateTime().getMillis();
        final String concate = message + Long.toString(autoGeneratredID);
        return bytesToHex(getMessageDigest().digest(concate.getBytes()));
    }

    private static MessageDigest getMessageDigest() {
        try {
            if (messageDigest == null) {
                messageDigest = MessageDigest.getInstance("SHA-256");
            }
        } catch (final NoSuchAlgorithmException nsae) {
            LOGGER.error("Error while getting SHA-1 messagedigest!", nsae);
        }

        return messageDigest;
    }

    /**
     * Transforms byte to hex representation
     *
     * @param b
     *            bytes
     * @return hex
     */
    private static String bytesToHex(final byte[] b) {
        final StringBuilder buf = new StringBuilder();
        for (final byte element : b) {
            buf.append(HEX_DIGITS[(element >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[element & 0x0f]);
        }
        return buf.toString();
    }

    @Deprecated
    public static void appendTextToStringBuilderWithLineBreak(final StringBuilder stringBuilder, final String message) {
        if (stringBuilder != null && StringHelper.isNotEmpty(message)) {
            stringBuilder.append(message);
            stringBuilder.append(Constants.LINE_SEPARATOR_STRING);
        }
    }

    /**
     * return Object value as String
     *
     * @param object
     *            to get as String
     * @return String value
     */
    public static String asString(final Object object) {
        if (object instanceof String) {
            return (String) object;
        } else if (object instanceof BigDecimal) {
            final BigDecimal bdValue = (BigDecimal) object;
            return Double.toString(bdValue.doubleValue());
        } else if (object instanceof Double) {
            return ((Double) object).toString();
        } else if (object instanceof Integer) {
            return ((Integer) object).toString();
        }
        // TODO why not object.toString()?
        return Constants.EMPTY_STRING;
    }

    /**
     * return Object value as Double
     *
     * @param object
     *            to get as Double
     * @return Double value
     */
    public static Double asDouble(final Object object) {
        if (object instanceof String) {
            return Double.parseDouble((String) object);
        } else if (object instanceof BigDecimal) {
            final BigDecimal bdValue = (BigDecimal) object;
            return bdValue.doubleValue();
        } else if (object instanceof Double) {
            return (Double) object;
        }
        return Double.NaN;
    }

    /**
     * return Object value as Integer
     *
     * @param object
     *            to get as Integer
     * @return Integer value
     */
    public static Integer asInteger(Object object) {
        if (object == null) {
            return null;
        } else if (object instanceof Integer) {
            return (Integer) object;
        } else if (object instanceof String) {
            return Integer.valueOf((String) object);
        }
        return null;
    }

    /**
     * return Object value as Boolean
     *
     * @param object
     *            to get as Boolean
     * @return Boolean value
     */
    public static Boolean asBoolean(Object object) {
        if (object == null) {
            return null;
        } else if (object instanceof Boolean) {
            return (Boolean) object;
        } else if (object instanceof String) {
            return Boolean.valueOf((String) object);
        }
        return null;
    }

    public static Set<Integer> getIntegerSetFromString(String s) {
        HashSet<Integer> set = Sets.newHashSet();
        if (StringHelper.isNotEmpty(s)) {
            Set<String> splitToSet = StringHelper.splitToSet(s, Constants.COMMA_STRING);
            if (CollectionHelper.isNotEmpty(splitToSet)) {
                for (String string : splitToSet) {
                    set.add(Integer.parseInt(string));
                }
            }
        }
        return set;
    }

    private JavaHelper() {
    }

}

@@ -1446,16 +1446,320 @@
 igest;%0A%0A
+%0A    /**%0A     * Instantiation of the message digest%0A     */%0A    static %7B%0A        try %7B%0A            messageDigest = MessageDigest.getInstance(%22SHA-256%22);%0A        %7D catch (final NoSuchAlgorithmException nsae) %7B%0A            LOGGER.error(%22Error while getting SHA-256 messagedigest!%22, nsae);%0A        %7D%0A    %7D%0A%0A
     /**%0A
@@ -1942,17 +1942,19 @@
 hex SHA-
-1
+256
 .%0A     *
@@ -2221,20 +2221,17 @@
 esToHex(
-getM
+m
 essageDi
@@ -2234,18 +2234,16 @@
 geDigest
-()
 .digest(
@@ -2275,381 +2275,8 @@
  %7D%0A%0A
-    private static MessageDigest getMessageDigest() %7B%0A        try %7B%0A            if (messageDigest == null) %7B%0A                messageDigest = MessageDigest.getInstance(%22SHA-256%22);%0A            %7D%0A        %7D catch (final NoSuchAlgorithmException nsae) %7B%0A            LOGGER.error(%22Error while getting SHA-1 messagedigest!%22, nsae);%0A        %7D%0A%0A        return messageDigest;%0A    %7D%0A%0A
     

Change to use static init method for MessageDigest