gov.usgs.cida.glri.sb.ui.GLRIUtil.java Source code

Java tutorial

Introduction

Here is the source code for gov.usgs.cida.glri.sb.ui.GLRIUtil.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package gov.usgs.cida.glri.sb.ui;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;

/**
 *
 * @author eeverman
 */
public class GLRIUtil {
    /**
     * Parses an http contentType header string into the encoding, if it exists.
     * If it cannot find the encoding, the default is returned.
     * 
     * @param entity Find the header in this entity
     * @param defaultEncoding Return this encoding if we cannot find the value in the header.
     * @return encoding
     */
    public static String findEncoding(HttpEntity entity, String defaultEncoding) {

        try {
            return findEncoding(entity.getContentType().getValue(), defaultEncoding);
        } catch (RuntimeException e) {
            return defaultEncoding;
        }
    }

    /**
     * Parses an http contentType header string into the encoding, if it exists.
     * If it cannot find the encoding, the default is returned.
     * 
     * @param contentTypeHeaderString The String value of the http contentType header
     * @param defaultEncoding Return this encoding if we cannot find the value in the header.
     * @return encoding
     */
    public static String findEncoding(String contentTypeHeaderString, String defaultEncoding) {

        try {
            //Example contentType:  text/html; charset=utf-8

            String[] parts = contentTypeHeaderString.split(";");
            String encoding = StringUtils.trimToNull(parts[1]);
            parts = encoding.split("=");

            if (parts[0].trim().equalsIgnoreCase("charset")) {
                encoding = StringUtils.trimToNull(parts[1]);
                return encoding.toUpperCase();
            } else {
                return defaultEncoding;
            }

        } catch (RuntimeException e) {
            return defaultEncoding;
        }
    }
}