fi.vm.kapa.identification.adapter.utils.AuthenticationHandlerUtils.java Source code

Java tutorial

Introduction

Here is the source code for fi.vm.kapa.identification.adapter.utils.AuthenticationHandlerUtils.java

Source

/**
 * The MIT License
 * Copyright (c) 2015 Population Register Centre
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package fi.vm.kapa.identification.adapter.utils;

import java.util.HashMap;
import java.util.Map;
import java.math.BigInteger;
import java.security.SecureRandom;

import javax.inject.Singleton;
import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.lang.StringUtils;

import org.springframework.stereotype.Service;

@Service
@Singleton
public class AuthenticationHandlerUtils {

    private Map<String, MultivaluedMap<String, String>> authenticationsCache = new HashMap<>();
    private Map<String, Map<String, String>> attributesCache = new HashMap<>();

    public void insertIntoCache(String token, MultivaluedMap<String, String> requestParams) {
        authenticationsCache.put(token, requestParams);
    }

    public MultivaluedMap<String, String> popFromCache(String token) {
        MultivaluedMap<String, String> requestParams = null;

        if (StringUtils.isNotBlank(token) && authenticationsCache.containsKey(token)) {
            requestParams = authenticationsCache.remove(token);
        }

        return requestParams;
    }

    public String createToken() {
        return new BigInteger(64, new SecureRandom()).toString(16);
    }

    public void addToAttributesCache(String token, Map<String, String> attributes) {
        attributesCache.put(token, attributes);
    }

    public Map<String, String> popFromAttributesCache(String token) {
        Map<String, String> attributes = null;

        if (attributesCache.containsKey(token)) {
            attributes = attributesCache.remove(token);
        }

        return attributes;
    }
}