illab.nabal.util.ParameterHelper.java Source code

Java tutorial

Introduction

Here is the source code for illab.nabal.util.ParameterHelper.java

Source

/*
 * Copyright (C) 2013-2014 Tan Jung
 *
 * 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 illab.nabal.util;

import illab.nabal.exception.SystemException;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.util.Log;

/**
 * Helper class for parmeter handling.
 * 
 * @version 1.0, 02/10/14
 * @author <a href="mailto:tanito.jung@gmail.com">Tan Jung</a>
 */
public class ParameterHelper {
    private final static String TAG = "ParameterHelper";

    /**
     * Constant for ampersend delimeter.
     */

    /**
     * Constant for http.
     */
    protected final static String HTTP = "http";

    /**
     * Constant for UTF-8;
     */
    protected final static String UTF_8 = "UTF-8";

    /**
     * Constant for ampersend delimeter.
     */
    protected final static String AMPERSEND = "&";

    /**
     * Constant for equal mark.
     */
    protected final static String EQUAL_MARK = "=";

    /**
     * Constant for OAuth signature.
     */
    private final static String OAUTH_SIGNATURE = "oauth_signature";

    /**
     * Comparator to sort parameters using lexicographical byte value ordering.
     */
    public static Comparator<NameValuePair> paramComparator = new Comparator<NameValuePair>() {
        public int compare(NameValuePair o1, NameValuePair o2) {
            String name1 = o1.getName();
            String name2 = o2.getName();
            int result = name1.compareTo(name2);
            if (result == 0) {
                String value1 = o1.getValue();
                String value2 = o2.getValue();
                result = (value1 != null) ? value1.compareTo(value2) : (value2 != null) ? 1 : 0;
            }
            return result;
        }
    };

    /**
     * Sort parameters using lexicographical byte value ordering.
     * 
     * @param params - list of parameters to sort
     * @return List<NameValuePair>
     */
    public static List<NameValuePair> sortParams(List<NameValuePair> params) {
        NameValuePair[] sortedParams = params.toArray(new NameValuePair[params.size()]);
        Arrays.sort(sortedParams, paramComparator);
        params.clear();
        for (NameValuePair param : sortedParams) {
            params.add(param);
        }
        sortedParams = null;
        return params;
    }

    /**
     * Add all name-value pairs to paramter list at once.
     * 
     * @param nvPairs
     * @return List<NameValuePair>
     */
    public static List<NameValuePair> addAllParams(BasicNameValuePair... nvPairs) {
        List<NameValuePair> params = null;
        if (nvPairs.length > 0) {
            params = new ArrayList<NameValuePair>();
            for (BasicNameValuePair nvPair : nvPairs) {
                params.add(nvPair);
            }
        }
        return params;
    }

    /**
     * Add OAuth 1.0a signature parameter.
     * 
     * @param secretKey
     * @param baseString
     * @param params
     * @return List<NameValuePair>
     * @throws Exception
     */
    public static List<NameValuePair> addSignature(String secretKey, String baseString, List<NameValuePair> params)
            throws Exception {

        if (StringHelper.isAllFull(secretKey, baseString) == true && params != null) {

            // generate HMAC-SHA1 signature
            String signature = SecurityHelper.getHmacSha1Signature(secretKey, baseString);

            Log.d(TAG, "baseString : " + baseString);
            Log.d(TAG, "oauthSignature (URL-encoded) : " + URLEncoder.encode(signature, UTF_8));

            // add HMAC-SHA1 signature as a parameter
            params.add(new BasicNameValuePair(OAUTH_SIGNATURE, StringHelper.nvl(signature)));

            // nullify this unnecessary variable
            signature = null;

        } else {
            // notify an error
            throw new SystemException("Failed to generate OAuth 1.0a signature.");
        }
        return params;
    }

    /**
     * URL-decodes bundle parameters. 
     * (x-www-form-urlencoded MIME content type)
     * 
     * @param queryString - query string parameters
     * @return Bundle
     */
    public static Bundle decodeGetParams(String queryString) {

        Bundle params = new Bundle();

        if (queryString != null) {
            String[] array = queryString.split(AMPERSEND);

            for (String parameter : array) {
                String[] nvPair = parameter.split(EQUAL_MARK);
                try {
                    params.putString(URLDecoder.decode(nvPair[0], UTF_8), URLDecoder.decode(nvPair[1], UTF_8));
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, e.getMessage());
                    Log.e(TAG, "Failed to decode parameter : " + parameter);
                }
            }
        }
        return params;
    }

    /**
     * Parse a URL query and fragment parameters into a key-value bundle.
     * 
     * @param url - the URL to parse
     * @return bundle - a dictionary bundle of keys and values
     */
    public static Bundle parseGetParams(String url) {

        // prepare a bundle
        Bundle bundle = null;
        try {
            URL u = new URL(url);
            bundle = decodeGetParams(u.getQuery());
            bundle.putAll(decodeGetParams(u.getRef()));
        } catch (MalformedURLException e) {
            Log.e(TAG, "malformed URL");
            Log.e(TAG, e.getMessage());
        }
        return bundle;
    }

}