com.jamonapi.utils.Misc Maven / Gradle / Ivy
package com.jamonapi.utils;
import java.lang.reflect.Constructor;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
/** Difficult to group Utilities **/
public class Misc {
/** Returns an Objects ClassName minus the package name
*
* Sample Call:
* String className=Misc.getClassName("My Object"); // returns "String"
*
**/
public static String getClassName(Object object) {
String className = (object==null ? "null" : object.getClass().getName()); // gov.gsa.fss.fim.Misc
return className.substring(className.lastIndexOf(".")+1); // Misc
}
/** Return Exception information as a row (1 dim array) */
public static String getExceptionTrace(Throwable exception) {
// each line of the stack trace will be returned in the array.
StackTraceElement elements[] = exception.getStackTrace();
StringBuffer trace = new StringBuffer().append(exception).append("\n");
for (int i = 0; i < elements.length; i++) {
trace.append(elements[i]).append("\n");
}
return trace.toString();
}
/** Note if the passed object is a Colleciton itself or an Object[] it will be expanded */
public static void addTo(Collection coll, Object objToAdd) {
if (objToAdd instanceof Collection)
coll.addAll((Collection)objToAdd);
else if (objToAdd instanceof Object[])
coll.addAll(Arrays.asList((Object[])objToAdd));
else if (objToAdd instanceof ToArray)
coll.addAll(Arrays.asList(((ToArray)objToAdd).toArray()));
else
coll.add(objToAdd);
}
public static String getAsString(Object obj) {
try {
if (obj==null)
return null;
else if (obj instanceof Collection)
return getCollAsString((Collection)obj);
else if (obj instanceof Object[])
return getArrAsString((Object[]) obj);
else if (obj instanceof ToArray)
return getArrAsString(((ToArray)obj).toArray());
else if (obj instanceof Throwable)
return getExceptionTrace((Throwable)obj);
else
return obj.toString();
}
catch(Throwable e) {
// ignore any exception here since
return "???";
}
}
private static String getCollAsString(Collection coll) {
int currentElement=1;
int lastElement=coll.size();
Iterator iter=coll.iterator();
StringBuffer buff=new StringBuffer();
// loop through elements creating a comma delimeted list of the values
while(iter.hasNext()) {
Object obj=iter.next();
if (obj instanceof Throwable)
obj=getExceptionTrace((Throwable)obj);
buff.append(obj);
if (currentElement!=lastElement)
buff.append(",\n");
currentElement++;
}
return buff.toString();
}
private static String getArrAsString(Object[] arr) {
int lastElement=arr.length-1;
StringBuffer buff=new StringBuffer();
for (int i=0;i