package com.vip.saturn.job.console.utils;

import com.vip.saturn.job.console.exception.SaturnJobConsoleException;
import com.vip.saturn.job.console.exception.SaturnJobConsoleHttpException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;

import java.util.Map;

/**
 * Created by kfchu on 10/05/2017.
 */
public class ControllerUtils {

    public final static String BAD_REQ_MSG_PREFIX = "Invalid request.";

    public final static String MISSING_REQUEST_MSG = BAD_REQ_MSG_PREFIX + " Missing parameter: {%s}";

    public static String checkAndGetParametersValueAsString(Map<String, Object> map, String key, boolean isMandatory) throws SaturnJobConsoleException {
        if (map.containsKey(key)) {
            String value = (String) map.get(key);
            return StringUtils.isBlank(value) ? null : value;
        } else {
            if (isMandatory) {
                throw new SaturnJobConsoleHttpException(HttpStatus.BAD_REQUEST.value(), String.format(MISSING_REQUEST_MSG, key));
            }
            return null;
        }
    }

    public static Integer checkAndGetParametersValueAsInteger(Map<String, Object> map, String key, boolean isMandatory) throws SaturnJobConsoleException {
        if (map.containsKey(key)) {
            return (Integer) map.get(key);
        } else {
            if (isMandatory) {
                throw new SaturnJobConsoleHttpException(HttpStatus.BAD_REQUEST.value(), String.format(MISSING_REQUEST_MSG, key));
            }
            return null;
        }
    }

    public static Boolean checkAndGetParametersValueAsBoolean(Map<String, Object> map, String key, boolean isMandatory) throws SaturnJobConsoleException {
        if (map.containsKey(key)) {
            return (Boolean) map.get(key);
        } else {
            if (isMandatory) {
                throw new SaturnJobConsoleHttpException(HttpStatus.BAD_REQUEST.value(), String.format(MISSING_REQUEST_MSG, key));
            }
            return Boolean.FALSE;
        }
    }
}

@@ -268,24 +268,70 @@
 ttpStatus;%0A%0A
+import javax.servlet.http.HttpServletRequest;%0A
 import java.
@@ -2070,11 +2070,381 @@
  %7D%0A    %7D
+%0A%0A    public static String getClientIp(HttpServletRequest request) %7B%0A        String remoteAddr = %22%22;%0A%0A        if (request != null) %7B%0A            remoteAddr = request.getHeader(%22X-FORWARDED-FOR%22);%0A            if (remoteAddr == null %7C%7C %22%22.equals(remoteAddr)) %7B%0A                remoteAddr = request.getRemoteAddr();%0A            %7D%0A        %7D%0A%0A        return remoteAddr;%0A    %7D
 %0A%7D%0A

add getClientIp method