All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gitee.maskit.web.WebHolder Maven / Gradle / Ivy

package com.gitee.maskit.web;

import org.springframework.http.HttpHeaders;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author z0228
 */

public enum WebHolder {
    AGENT,
    DOMAIN,
    PORT(80),
    LOCALE(Locale.getDefault()),
    SEO,
    REQUEST,
    RESPONSE;

    private static final ThreadLocal> MAP_THREAD_LOCAL =
        ThreadLocal.withInitial(ConcurrentHashMap::new);

    private final Object defaultValue;

    WebHolder() {
        defaultValue = null;
    }

    WebHolder(Object o) {
        defaultValue = o;
    }

    public boolean has() {
        return MAP_THREAD_LOCAL.get().containsKey(this);
    }

    @SuppressWarnings("unchecked")
    public  T get() {
        final Object r = MAP_THREAD_LOCAL.get().get(this);
        if (null != r) {
            return (T) r;
        }
        return (T) defaultValue;
    }

    @SuppressWarnings("unchecked")
    public  T set(Object object) {
        return (T) MAP_THREAD_LOCAL.get().put(this, object);
    }

    @SuppressWarnings("unchecked")
    public  T clear() {
        return (T) MAP_THREAD_LOCAL.get().remove(this);
    }

    public static void clearAll() {
        MAP_THREAD_LOCAL.get().clear();
    }

    public static String header(final String header) {
        if (REQUEST.has()) {
            return ((HttpServletRequest) REQUEST.get()).getHeader(header);
        }
        return null;
    }

    public static Enumeration headers(final String header) {
        if (REQUEST.has()) {
            return ((HttpServletRequest) REQUEST.get()).getHeaders(header);
        }
        return Collections.emptyEnumeration();
    }

    public static String host() {
        String host = null;
        if (REQUEST.has()) {
            host = ((HttpServletRequest) REQUEST.get()).getHeader(HttpHeaders.HOST);
        }
        if (null != host) {
            return host;
        }
        return "";
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy