Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.List;

import java.util.Map;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static String guessFileTypeFromFileName(String fileName) {
        if (isEmpty(fileName)) {
            return "text/plain;charset=utf-8";
        }
        if (contains(fileName, new String[] { "\\.json(\\.txt)?$" })) {
            return "application/json;charset=utf-8";
        }
        if (contains(fileName, new String[] { "\\.txt$" })) {
            return "text/plain;charset=utf-8";
        }
        if (contains(fileName, new String[] { "\\.js$" })) {
            return "application/javascript;charset=utf-8";
        }
        if (contains(fileName, new String[] { "\\.png$" })) {
            return "image/png";
        }
        if (contains(fileName, new String[] { "\\.jp(eg|e|g)$" })) {
            return "image/jpeg";
        }
        if (contains(fileName, new String[] { "\\.gif$" })) {
            return "image/gif";
        }
        if (contains(fileName, new String[] { "\\.htm(l)?$" })) {
            return "text/html;charset=utf-8";
        }
        if (contains(fileName, new String[] { "\\.XXX$" })) {
            return "XXX/XXX";
        }
        return "text/plain;charset=utf-8";
    }

    /**
     * Beware, the valid word "null" is also rendered as empty.
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || "".contentEquals(str) || "null".contentEquals(str);
    }

    public static <K, V> boolean isEmpty(Map<K, V> map) {
        return map == null || map.isEmpty();
    }

    public static <T> boolean isEmpty(List<T> l) {
        return l == null || l.isEmpty();
    }

    /**
     * Simple matcher that finds given regular expression patterns.
     * Samples:<br />
     * contains("selam", new String[]{"q", "r"}) -> returns false.<br />
     * contains("selam", new String[]{"q", "a"}) -> returns true.<br />
     * contains("selam", new String[]{"q", "a$"}) -> returns false.<br />
     * contains("selam", new String[]{"q", "m$"}) -> returns true.<br />
     * contains("selam", new String[]{"^m"}) -> returns false.<br />
     *
     * @param str Source string to search for.
     * @param regularExpressions Regular Expressions as an array.
     * @return TRUE if ANY of the given patterns match. FALSE, if ALL of the given patterns are not found.
     */
    public static boolean contains(String str, String[] regularExpressions) {
        for (String regularExpression : regularExpressions) {
            Pattern pattern = Pattern.compile(regularExpression);
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                return true;
            }
        }
        return false;
    }
}