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
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 3 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    16  */
    17 package info.globalcode.sql.dk;
    18 
    19 import info.globalcode.sql.dk.configuration.NameIdentified;
    20 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
    21 import info.globalcode.sql.dk.configuration.PropertyDeclarations;
    22 import info.globalcode.sql.dk.formatting.Formatter;
    23 import java.io.BufferedReader;
    24 import java.io.File;
    25 import java.io.IOException;
    26 import java.io.InputStream;
    27 import java.io.InputStreamReader;
    28 import java.io.PrintWriter;
    29 import java.util.ArrayList;
    30 import java.util.Arrays;
    31 import java.util.Collection;
    32 import java.util.Collections;
    33 import java.util.List;
    34 import java.util.Map;
    35 import java.util.regex.Matcher;
    36 import java.util.regex.Pattern;
    37 
    38 /**
    39  *
    40  * @author Ing. František Kučera (frantovo.cz)
    41  */
    42 public class Functions {
    43 
    44 	private static final String NBSP = " ";
    45 	private static final Pattern WHITESPACE_TO_REPLACE = Pattern.compile("\\n|\\r|\\t|" + NBSP);
    46 
    47 	private Functions() {
    48 	}
    49 
    50 	public static boolean equalz(Object a, Object b) {
    51 		return a == null ? b == null : a.equals(b);
    52 	}
    53 
    54 	/**
    55 	 *
    56 	 * @param text String to be examinated
    57 	 * @param trim whether text should be trimmed before examination
    58 	 * @return whether text is not empty and one or more characters long (after prospective trim)
    59 	 */
    60 	public static boolean isEmpty(String text, boolean trim) {
    61 		if (text == null) {
    62 			return true;
    63 		} else {
    64 			if (trim) {
    65 				text = text.trim();
    66 			}
    67 			return text.isEmpty();
    68 		}
    69 	}
    70 
    71 	/**
    72 	 * @see #isEmpty(java.lang.String, boolean)
    73 	 */
    74 	public static boolean isNotEmpty(String text, boolean trim) {
    75 		return !isEmpty(text, trim);
    76 	}
    77 
    78 	public boolean isEmpty(Collection c) {
    79 		return c == null || c.isEmpty();
    80 	}
    81 
    82 	public boolean isNotEmpty(Collection c) {
    83 		return !isEmpty(c);
    84 	}
    85 
    86 	public boolean isEmpty(Map m) {
    87 		return m == null || m.isEmpty();
    88 	}
    89 
    90 	public boolean isNotEmpty(Map m) {
    91 		return !isEmpty(m);
    92 	}
    93 
    94 	/**
    95 	 * @return empty collection if given one is null | or the original one
    96 	 */
    97 	public static <T> Collection<T> notNull(Collection<T> c) {
    98 		if (c == null) {
    99 			return Collections.emptyList();
   100 		} else {
   101 			return c;
   102 		}
   103 	}
   104 
   105 	public static <T extends NameIdentified> T findByName(Collection<T> collection, String name) {
   106 		for (T element : notNull(collection)) {
   107 			if (element != null && equalz(element.getName(), name)) {
   108 				return element;
   109 			}
   110 		}
   111 
   112 		return null;
   113 	}
   114 
   115 	/**
   116 	 * Copy file from Java resources to file system.
   117 	 */
   118 	public static void installResource(String resourceName, File target) throws IOException {
   119 		try (BufferedReader reader = new BufferedReader(new InputStreamReader(Functions.class.getClassLoader().getResourceAsStream(resourceName)))) {
   120 			try (PrintWriter writer = new PrintWriter(target)) {
   121 				while (true) {
   122 					String line = reader.readLine();
   123 					if (line == null) {
   124 						break;
   125 					} else {
   126 						writer.println(line);
   127 					}
   128 				}
   129 			}
   130 		}
   131 	}
   132 
   133 	public static String rpad(String s, int n) {
   134 		if (n > 0) {
   135 			return String.format("%1$-" + n + "s", s);
   136 		} else {
   137 			return s;
   138 		}
   139 	}
   140 
   141 	public static String lpad(String s, int n) {
   142 		if (n > 0) {
   143 			return String.format("%1$" + n + "s", s);
   144 		} else {
   145 			return s;
   146 		}
   147 	}
   148 
   149 	public static String repeat(char ch, int count) {
   150 		char[] array = new char[count];
   151 		Arrays.fill(array, ch);
   152 		return new String(array);
   153 	}
   154 	private final static char[] HEX_ALPHABET = "0123456789abcdef".toCharArray();
   155 
   156 	public static String toHex(byte[] bytes) {
   157 		char[] hexChars = new char[bytes.length * 2];
   158 		for (int j = 0; j < bytes.length; j++) {
   159 			int v = bytes[j] & 0xFF;
   160 			hexChars[j * 2] = HEX_ALPHABET[v >>> 4];
   161 			hexChars[j * 2 + 1] = HEX_ALPHABET[v & 0x0F];
   162 		}
   163 		return new String(hexChars);
   164 	}
   165 
   166 	public static String readString(InputStream in) throws IOException {
   167 		try (BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
   168 			StringBuilder result = new StringBuilder();
   169 			for (String line = br.readLine(); line != null; line = br.readLine()) {
   170 				result.append(line);
   171 				result.append('\n');
   172 			}
   173 			return result.toString();
   174 		}
   175 	}
   176 
   177 	/**
   178 	 * @param <P> type of the last parent
   179 	 * @param <T> type of the examined class
   180 	 * @param type examined class
   181 	 * @param lastParent the last parent type to stop at
   182 	 * @return list of types starting with <code>type</code> and ending with <code>lastParent</code>
   183 	 */
   184 	public static <P, T extends P> List<Class<? extends P>> getClassHierarchy(Class<T> type, Class<P> lastParent) {
   185 		List<Class<? extends P>> hierarchy = new ArrayList<>();
   186 
   187 		for (Class current = type; current != null && lastParent.isAssignableFrom(current); current = current.getSuperclass()) {
   188 			hierarchy.add(current);
   189 		}
   190 
   191 		return hierarchy;
   192 	}
   193 
   194 	public static PropertyDeclaration[] getPropertyDeclarations(Class<? extends Formatter> formatterClass) {
   195 		PropertyDeclarations properties = formatterClass.getAnnotation(PropertyDeclarations.class);
   196 
   197 		if (properties == null) {
   198 			PropertyDeclaration p = formatterClass.getAnnotation(PropertyDeclaration.class);
   199 			return p == null ? new PropertyDeclaration[]{} : new PropertyDeclaration[]{p};
   200 		} else {
   201 			return properties.value();
   202 		}
   203 	}
   204 
   205 	/**
   206 	 * TODO: support background or styles and move to ColorfulPrintWriter
   207 	 *
   208 	 * @param out
   209 	 * @param valueString
   210 	 * @param basicColor
   211 	 * @param escapeColor
   212 	 */
   213 	public static void printValueWithWhitespaceReplaced(ColorfulPrintWriter out, String valueString, ColorfulPrintWriter.TerminalColor basicColor, ColorfulPrintWriter.TerminalColor escapeColor) {
   214 
   215 		Matcher m = WHITESPACE_TO_REPLACE.matcher(valueString);
   216 
   217 		int start = 0;
   218 
   219 		while (m.find(start)) {
   220 
   221 			printColorOrNot(out, basicColor, valueString.substring(start, m.start()));
   222 
   223 			switch (m.group()) {
   224 				case "\n":
   225 					out.print(escapeColor, "↲");
   226 					break;
   227 				case "\r":
   228 					out.print(escapeColor, "⏎");
   229 					break;
   230 				case "\t":
   231 					out.print(escapeColor, "↹");
   232 					break;
   233 				case NBSP:
   234 					out.print(escapeColor, "⎵");
   235 					break;
   236 				default:
   237 					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
   238 			}
   239 
   240 			start = m.end();
   241 		}
   242 
   243 		printColorOrNot(out, basicColor, valueString.substring(start, valueString.length()));
   244 	}
   245 
   246 	private static void printColorOrNot(ColorfulPrintWriter out, ColorfulPrintWriter.TerminalColor color, String text) {
   247 		if (color == null) {
   248 			out.print(text);
   249 		} else {
   250 			out.print(color, text);
   251 		}
   252 	}
   253 }