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

com.ifengxue.http.executor.RequestContext Maven / Gradle / Ivy

/*
 * Copyright 2019 https://www.ifengxue.com
 *
 * 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 com.ifengxue.http.executor;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * request context
 */
public interface RequestContext {

  /**
   * set attribute to context
   *
   * @param name attribute name
   * @param value attribute value
   * @return this
   */
   RequestContext setAttribute(String name, T value);

  /**
   * get attribute from context
   *
   * @param name attribute name
   * @return attribute value. maybe null
   */
   T getAttribute(String name);

  /**
   * get attribute from context, if null then return defValue
   *
   * @param name attribute name
   * @param defValue default value
   * @return attribute value
   */
   T getAttribute(String name, T defValue);

  /**
   * remove attribute from context
   *
   * @param name attribute name
   * @return attribute value. maybe null
   */
   T removeAttribute(String name);

  /**
   * clear all attribute from context
   */
  void clearAllAttribute();

  class SimpleRequestContext implements RequestContext {

    private Map contextMap = Collections.emptyMap();

    @Override
    public  RequestContext setAttribute(String name, T value) {
      getContextMapInternal().put(name, value);
      return this;
    }

    @Override
    @SuppressWarnings("unchecked")
    public  T getAttribute(String name) {
      return (T) contextMap.get(name);
    }

    @Override
    @SuppressWarnings("unchecked")
    public  T getAttribute(String name, T defValue) {
      return (T) contextMap.getOrDefault(name, defValue);
    }

    @Override
    @SuppressWarnings("unchecked")
    public  T removeAttribute(String name) {
      return (T) getContextMapInternal().remove(name);
    }

    @Override
    public void clearAllAttribute() {
      getContextMapInternal().clear();
    }

    private Map getContextMapInternal() {
      Map emptyMap = Collections.emptyMap();
      if (contextMap == emptyMap) {
        contextMap = new HashMap<>();
        return contextMap;
      }
      return contextMap;
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy