be.bittich.quote.core.DynaUtil.java Source code

Java tutorial

Introduction

Here is the source code for be.bittich.quote.core.DynaUtil.java

Source

/*
 * Copyright 2014 nateriver.
 *
 * 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 be.bittich.quote.core;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author nateriver
 */
public interface DynaUtil {

    /**
     * Jsonify a map of K,V
     *
     * @param map
     * @return
     */
    static String jsonifyMap(Map<?, ?> map) {
        Gson gson = new GsonBuilder().create();
        String json = gson.toJson(map);
        return json;
    }

    /**
     * Convenient method to return an array of T. If this exist in another
     * library, such Guava, I will remove it
     *
     * @param <T>
     * @param ts
     * @return
     */
    static <T> T[] asPrimitiveArray(T... ts) {
        return ts;
    }

    static <N> N getRandom(List<N> list) {
        //on mlange la liste
        Collections.shuffle(list);
        return list.stream().findFirst().orElse(null);
    }

    public static String extractAuthTokenFromRequest(HttpServletRequest httpRequest) {
        String authToken = httpRequest.getHeader("X-Auth-Token");

        if (authToken == null) {
            authToken = httpRequest.getParameter("token");
        }

        return authToken;
    }

}