java/sql-dk/src/main/java/info/globalcode/sql/dk/Functions.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 24 Oct 2019 21:43:08 +0200
branchv_0
changeset 250 aae5009bd0af
parent 238 4a1864c3e867
permissions -rw-r--r--
fix license version: GNU GPLv3

/**
 * SQL-DK
 * Copyright © 2013 František Kučera (frantovo.cz)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package info.globalcode.sql.dk;

import info.globalcode.sql.dk.configuration.NameIdentified;
import info.globalcode.sql.dk.configuration.PropertyDeclaration;
import info.globalcode.sql.dk.configuration.PropertyDeclarations;
import info.globalcode.sql.dk.formatting.Formatter;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Ing. František Kučera (frantovo.cz)
 */
public class Functions {

	private static final String NBSP = " ";
	private static final Pattern WHITESPACE_TO_REPLACE = Pattern.compile("\\n|\\r|\\t|" + NBSP);

	private Functions() {
	}

	public static boolean equalz(Object a, Object b) {
		return a == null ? b == null : a.equals(b);
	}

	/**
	 *
	 * @param text String to be examinated
	 * @param trim whether text should be trimmed before examination
	 * @return whether text is not empty and one or more characters long (after prospective trim)
	 */
	public static boolean isEmpty(String text, boolean trim) {
		if (text == null) {
			return true;
		} else {
			if (trim) {
				text = text.trim();
			}
			return text.isEmpty();
		}
	}

	/**
	 * @see #isEmpty(java.lang.String, boolean)
	 */
	public static boolean isNotEmpty(String text, boolean trim) {
		return !isEmpty(text, trim);
	}

	public boolean isEmpty(Collection c) {
		return c == null || c.isEmpty();
	}

	public boolean isNotEmpty(Collection c) {
		return !isEmpty(c);
	}

	public boolean isEmpty(Map m) {
		return m == null || m.isEmpty();
	}

	public boolean isNotEmpty(Map m) {
		return !isEmpty(m);
	}

	/**
	 * @return empty collection if given one is null | or the original one
	 */
	public static <T> Collection<T> notNull(Collection<T> c) {
		if (c == null) {
			return Collections.emptyList();
		} else {
			return c;
		}
	}

	public static <T extends NameIdentified> T findByName(Collection<T> collection, String name) {
		for (T element : notNull(collection)) {
			if (element != null && equalz(element.getName(), name)) {
				return element;
			}
		}

		return null;
	}

	/**
	 * Copy file from Java resources to file system.
	 */
	public static void installResource(String resourceName, File target) throws IOException {
		try (BufferedReader reader = new BufferedReader(new InputStreamReader(Functions.class.getClassLoader().getResourceAsStream(resourceName)))) {
			try (PrintWriter writer = new PrintWriter(target)) {
				while (true) {
					String line = reader.readLine();
					if (line == null) {
						break;
					} else {
						writer.println(line);
					}
				}
			}
		}
	}

	public static String rpad(String s, int n) {
		if (n > 0) {
			return String.format("%1$-" + n + "s", s);
		} else {
			return s;
		}
	}

	public static String lpad(String s, int n) {
		if (n > 0) {
			return String.format("%1$" + n + "s", s);
		} else {
			return s;
		}
	}

	public static String repeat(char ch, int count) {
		char[] array = new char[count];
		Arrays.fill(array, ch);
		return new String(array);
	}
	private final static char[] HEX_ALPHABET = "0123456789abcdef".toCharArray();

	public static String toHex(byte[] bytes) {
		char[] hexChars = new char[bytes.length * 2];
		for (int j = 0; j < bytes.length; j++) {
			int v = bytes[j] & 0xFF;
			hexChars[j * 2] = HEX_ALPHABET[v >>> 4];
			hexChars[j * 2 + 1] = HEX_ALPHABET[v & 0x0F];
		}
		return new String(hexChars);
	}

	public static String readString(InputStream in) throws IOException {
		try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
			StringBuilder result = new StringBuilder();
			for (String line = br.readLine(); line != null; line = br.readLine()) {
				result.append(line);
				result.append('\n');
			}
			return result.toString();
		}
	}

	/**
	 * @param <P> type of the last parent
	 * @param <T> type of the examined class
	 * @param type examined class
	 * @param lastParent the last parent type to stop at
	 * @return list of types starting with <code>type</code> and ending with <code>lastParent</code>
	 */
	public static <P, T extends P> List<Class<? extends P>> getClassHierarchy(Class<T> type, Class<P> lastParent) {
		List<Class<? extends P>> hierarchy = new ArrayList<>();

		for (Class current = type; current != null && lastParent.isAssignableFrom(current); current = current.getSuperclass()) {
			hierarchy.add(current);
		}

		return hierarchy;
	}

	public static PropertyDeclaration[] getPropertyDeclarations(Class<? extends Formatter> formatterClass) {
		PropertyDeclarations properties = formatterClass.getAnnotation(PropertyDeclarations.class);

		if (properties == null) {
			PropertyDeclaration p = formatterClass.getAnnotation(PropertyDeclaration.class);
			return p == null ? new PropertyDeclaration[]{} : new PropertyDeclaration[]{p};
		} else {
			return properties.value();
		}
	}

	/**
	 * TODO: support background or styles and move to ColorfulPrintWriter
	 *
	 * @param out
	 * @param valueString
	 * @param basicColor
	 * @param escapeColor
	 */
	public static void printValueWithWhitespaceReplaced(ColorfulPrintWriter out, String valueString, ColorfulPrintWriter.TerminalColor basicColor, ColorfulPrintWriter.TerminalColor escapeColor) {

		Matcher m = WHITESPACE_TO_REPLACE.matcher(valueString);

		int start = 0;

		while (m.find(start)) {

			printColorOrNot(out, basicColor, valueString.substring(start, m.start()));

			switch (m.group()) {
				case "\n":
					out.print(escapeColor, "↲");
					break;
				case "\r":
					out.print(escapeColor, "⏎");
					break;
				case "\t":
					out.print(escapeColor, "↹");
					break;
				case NBSP:
					out.print(escapeColor, "⎵");
					break;
				default:
					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
			}

			start = m.end();
		}

		printColorOrNot(out, basicColor, valueString.substring(start, valueString.length()));
	}

	private static void printColorOrNot(ColorfulPrintWriter out, ColorfulPrintWriter.TerminalColor color, String text) {
		if (color == null) {
			out.print(text);
		} else {
			out.print(color, text);
		}
	}
}