Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.net.URLEncoder;
import java.util.*;

public class Main {
    /**
     * Used for flattening a collection of objects into a string
     * @param   array     Array of elements to flatten
     * @param   fmt       Format string to use for array flattening
     * @param   separator Separator to use for string concat
     * @return  Representative string made up of array elements
     */
    private static String flattenCollection(String elemName, Collection<?> array, String fmt, char separator) {
        StringBuilder builder = new StringBuilder();

        //append all elements in the array into a string
        for (Object element : array) {
            String elemValue = null;

            //replace null values with empty string to maintain index order
            if (null == element) {
                elemValue = "";
            } else if (element instanceof Date) {
                elemValue = dateToString((Date) element);
            } else {
                elemValue = element.toString();
            }
            elemValue = tryUrlEncode(elemValue);
            builder.append(String.format(fmt, elemName, elemValue, separator));
        }

        //remove the last separator, if appended
        if ((builder.length() > 1) && (builder.charAt(builder.length() - 1) == separator))
            builder.deleteCharAt(builder.length() - 1);

        return builder.toString();
    }

    /**
     * Convert a date to an ISO8601 formatted string
     * @param date Date object to format
     * @return ISO8601 formatted date string
     */
    public static String dateToString(Date date) {
        return com.fasterxml.jackson.databind.util.ISO8601Utils.format(date);
    }

    /**
     * Tries Url encode using UTF-8
     * @param value The value to url encode
     * @return
     */
    private static String tryUrlEncode(String value) {
        try {
            return URLEncoder.encode(value, "UTF-8");
        } catch (Exception ex) {
            return value;
        }
    }
}