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