Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
* Copyright (c) 2013, SRI International
* All rights reserved.
* Licensed under the The BSD 3-Clause License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://opensource.org/licenses/BSD-3-Clause
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of the aic-util nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.sri.ai.util;
import static com.sri.ai.util.base.PairOf.makePairOf;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringWriter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.StringJoiner;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.sri.ai.util.base.BinaryFunction;
import com.sri.ai.util.base.BinaryPredicate;
import com.sri.ai.util.base.Equals;
import com.sri.ai.util.base.NullaryFunction;
import com.sri.ai.util.base.Pair;
import com.sri.ai.util.base.PairOf;
import com.sri.ai.util.base.TernaryFunction;
import com.sri.ai.util.collect.EZIterator;
import com.sri.ai.util.math.Rational;
/**
* A suite of general purpose utility routines related to handling errors,
* string manipulation, I/O, collections, and math that have proven useful over
* time.
*
* @author braz
*
*/
@Beta
public class Util {
/**
* Logs the error message and stack trace for the given exception, and exits
* the program, returning code 1.
*
* @param e
* the throwable causing the fatal error.
*/
public static void fatalError(Throwable e) {
fatalError(e, true);
}
/**
* Logs a top level message, the error message and stack trace for the given
* exception, and exits the program, returning code 1.
*
* @param topLevelMessage
* the top level message describing the fatal error.
* @param e
* the throwable causing the fatal error.
*/
public static void fatalError(String topLevelMessage, Throwable e) {
fatalError(topLevelMessage, e, true);
}
/**
* Logs the error message for the given exception, and optionally logs a
* stack trace. Then exits the program with return code 1.
*
* @param e
* the throwable causing the fatal error.
* @param trace
* indicates whether or not to log the stack trace.
*/
public static void fatalError(Throwable e, boolean trace) {
fatalError("Fatal error: ", e, trace);
}
/**
* Logs error message and exits.
*
* @param msg
* the error message
*
*/
public static void fatalError(String msg) {
fatalError(msg, true);
}
/**
* Logs error message without loging stack trace, and exits.
*
* @param msg
* the error message
*/
public static void fatalErrorWithoutStack(String msg) {
fatalError(msg, false);
}
/**
* Logs a top level message, the error message for the given exception, and
* optionally logs a stack trace. Then exits the program with return code 1.
*
* @param topLevelMessage
* the top level message describing the fatal error.
* @param e
* the throwable causing the fatal error.
* @param trace
* indicates whether or not to log the stack trace.
*/
public static void fatalError(String topLevelMessage, Throwable e,
boolean trace) {
if (trace) {
if (e.getCause() != null) {
System.err.println(topLevelMessage + "\n" + e.getMessage()
+ "\n" + join("\n", e.getStackTrace()) + "\n"
+ e.getCause().getMessage() + "\n"
+ join("\n", e.getCause().getStackTrace()));
} else {
System.err.println(topLevelMessage + "\n" + e.getMessage());
}
} else {
System.err.println(topLevelMessage + "\n" + e.getMessage());
}
if (e != null) {
e.printStackTrace();
}
System.exit(1);
}
/**
* Logs error message, optionally logs stack trace, and exits.
*
* @param msg
* the error message
*
* @param trace
* if true, log a stack trace
*/
public static void fatalError(String msg, boolean trace) {
if (trace) {
System.err.println(msg + "\n"
+ join("\n", Thread.currentThread().getStackTrace()));
} else {
System.err.println(msg);
}
System.exit(1);
}
/**
* Returns a string with the entire context of an input stream.
*
* @param inputStream
* the input stream from which to read all from.
* @return a String representation of the entire contents of the given input
* stream.
*/
public static String readAll(InputStream inputStream) {
StringBuilder result = new StringBuilder();
String line;
boolean first = true;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
while ((line = reader.readLine()) != null) {
if (!first) {
result.append("\n");
}
result.append(line);
first = false;
}
return result.toString();
} catch (Exception e) {
Util.fatalError("Could not read " + inputStream, e);
}
return null;
}
/**
* Returns a string with the entire contents of an input reader.
*
* @param inputReader
* the input reader to be read from.
* @return all of the contents read from the input reader.
* @throws IOException if an error occurs.
*/
public static String readAll(Reader inputReader) throws IOException {
StringWriter result = new StringWriter();
char[] cbuf = new char[1024];
int read = 0;
while ((read = inputReader.read(cbuf)) != -1) {
result.write(cbuf, 0, read);
}
return result.toString();
}
/**
* Returns the string formed by concatenating the two given strings, with a
* space in between if both strings are non-empty.
*
* @param str1
* the first string to join.
* @param str2
* the second string to join.
* @return a concatenated version of str1 and str2 with a space in between.
*/
public static String join(String str1, String str2) {
if (str1.length() == 0) {
return str2;
}
if (str2.length() == 0) {
return str1;
}
StringJoiner sj = new StringJoiner(" ");
sj.add(str1).add(str2);
return sj.toString();
}
/**
* Returns a string formed by the concatenation of string versions of the
* elements in a collection, separated by a given separator.
*
* @param separator
* the separator to use between elements when creating the joined
* string.
* @param c
* the collection whose elements toString() values are to be
* joined together.
* @return a String constructed from the toString of each element of the
* given collection with the given separator between each argument.
*/
public static String join(String separator, Collection c) {
Iterator it = c.iterator();
return join(separator, it);
}
/**
* Returns a string formed by the concatenation of string versions of the
* elements in an iterator's range, separated by a given separator.
*
* @param separator
* the separator to use between elements when creating the joined
* string.
* @param it
* the iterator whose elements toString() values are to be joined
* together.
* @return a String constructed from the toString of each element of the
* given iterator with the given separator between each argument.
*/
@SuppressWarnings("unchecked")
public static String join(String separator, Iterator it) {
StringJoiner sj = new StringJoiner(separator);
it.forEachRemaining(e -> sj.add(e == null? "null" : e.toString()));
return sj.toString();
}
/**
* Same as {@link #join(String, Iterator)}, with ", " for a
* separator.
*
* @param it
* the iterator whose elements toString() values are to be joined
* together.
* @return a String constructed from the toString of each element of the
* given iterator with a comma (", ") separator between
* each argument.
*/
public static String join(Iterator it) {
return join(", ", it);
}
/**
* Same as {@link #join(String, Collection)}.
*
* @param c
* the collection whose elements toString() values are to be
* joined together.
* @param separator
* the separator to use between elements when creating the joined
* string.
* @return a String constructed from the toString of each element of the
* given collection with the given separator between each argument.
*/
public static String join(Collection c, String separator) {
return join(separator, c);
}
/**
* Calls {@link #join(String, Collection)} with ", " as separator.
*
* @param c
* the collection whose elements toString() values are to be
* joined together.
* @return a String constructed from the toString of each element of the
* given collection with a comma (", ") separator
* between each argument.
*/
public static String join(Collection c) {
return join(", ", c);
}
/**
* Calls {@link #join(Collection)} on the given array as a collection.
*
* @param a
* the array whose elements toString() values are to be joined
* together.
* @return a String constructed from the toString of each element of the
* given array with a comma (", ") separator between
* each argument.
*/
public static String join(Object[] a) {
return join(Arrays.asList(a));
}
/**
* Calls {@link #join(String, Collection)} on the given array as a
* collection.
*
* @param separator
* the separator to use between elements when creating the joined
* string.
* @param a
* the array whose elements toString() values are to be joined
* together.
* @return a String constructed from the toString of each element of the
* given array with the given separator between each argument.
*/
public static String join(String separator, Object[] a) {
return join(separator, Arrays.asList(a));
}
/**
* Produces a string with map entry representations separated by a given
* entry separator, where entry representations are the key and value
* representations separated by a key-value separator.
*
* @param entrySeparator
* the separator to use between each map entry in the join
* output.
* @param keyValueSeparator
* the separator to use between each entry's key value pair in
* the join output.
* @param map
* the map whose key value pairs are to be joined into a String.
* @return a joined string with an entrySeparator between each entry in the
* given map, each of which has a keyValueSeparator between the
* entry's key and value.
*/
public static String join(String entrySeparator, String keyValueSeparator,
Map extends Object, ? extends Object> map) {
List