com.monarchapis.driver.util.MediaTypeUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.monarchapis.driver.util.MediaTypeUtils.java

Source

/*
 * Copyright (C) 2015 CapTech Ventures, Inc.
 * (http://www.captechconsulting.com) All Rights Reserved.
 *
 * 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.monarchapis.driver.util;

import java.util.List;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.monarchapis.driver.servlet.ApiRequest;

/**
 * Provides a helper method for determining the best media type to response with
 * given the request's accept header.
 * 
 * @author Phil Kedy
 */
public abstract class MediaTypeUtils {
    private static List<String> supportedMimeTypes = Lists.newArrayList(//
            MediaType.APPLICATION_JSON, //
            MediaType.APPLICATION_XML);

    private MediaTypeUtils() {
    }

    /**
     * Returns the best media type for the current API request.
     * 
     * @return the media type.
     */
    public static String getBestMediaType() {
        return getBestMediaType(ApiRequest.getCurrent());
    }

    /**
     * Returns the best media type for a specific API request.
     * 
     * @return the media type.
     */
    public static String getBestMediaType(ApiRequest request) {
        String mediaType = null;
        String accept = request.getHeader("Accept");

        if (StringUtils.isNotBlank(accept)) {
            mediaType = MIMEParse.bestMatch(supportedMimeTypes, accept);
        }

        if (StringUtils.isBlank(mediaType)) {
            mediaType = MediaType.APPLICATION_JSON;
        }

        return mediaType;
    }
}