package net.sourceforge.seriesdownloader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Util {
public static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
public static final SimpleDateFormat dateFormatLong = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
private static final String EOL = "\r\n";
public static String makeLength(Object text, int length, char filler) {
StringBuffer result = new StringBuffer();
for (int i = nonNullString(text).length(); i < length; i++)
result.append(filler);
result.append(Util.nonNullString(text));
return result.toString();
}
public static boolean isEmpty(Object o) {
if (o == null)
return true;
if (o instanceof Collection)
return ((Collection) o).size() == 0;
return o.toString().length() == 0;
}
public static String nonNullString(Object o) {
if (isEmpty(o))
return "";
return o.toString();
}
public static int nullableCompareTo(Comparable o1, Comparable o2) {
if (o1 == null && o2 == null)
return 0;
if (o1 != null && o2 == null)
return -1;
if (o1 != null)
return o1.compareTo(o2);
return 1;
}
public static String formatDate(Date date) {
return formatDate(date, dateFormat);
}
public static String formatDate(Date date, DateFormat format) {
if (date == null)
return "";
return format.format(date);
}
public static Date parseDate(Object date) {
return parseDate(date, dateFormat);
}
public static Date parseDate(Object date, DateFormat format) {
try {
return format.parse(nonNullString(date));
} catch (ParseException e) {
return null;
}
}
public static int parseInt(Object nr, int def) {
try {
return Integer.parseInt(Util.nonNullString(nr));
} catch (Exception e) {
return def;
}
}
public static String parseString(Object string, String def) {
if (Util.isEmpty(string))
return def;
return Util.nonNullString(string);
}
public static boolean parseBoolean(Object bool, boolean def) {
if (bool == null)
return def;
if (bool instanceof Boolean)
return (Boolean) bool;
return Util.nonNullString(bool).toLowerCase().startsWith("t");
}
/**
* parseStringToMap("x=a,y=b", ",", "=") => {x: 'a', y: 'b'}
*
* @param str
* @param separator
* @param subseparator
* @return
*/
public static Map<String, String> parseStringToMap(String str, String separator, String subseparator) {
Map result = new HashMap<String, String>();
if (str == null)
return result;
for (String line : str.split(separator)) {
String[] lineParts = line.split(subseparator, 2);
if (lineParts.length > 0)
result.put(lineParts[0], lineParts.length > 1 ? lineParts[1] : "");
}
return result;
}
public static final Collection toCollection(Collection col, Object[] arr) {
for (Object o : arr)
col.add(o);
return col;
}
public static final boolean containsAll(String haystack, Collection<String> needles) {
haystack = haystack.toLowerCase();
for (String needle : needles)
if (!Util.isEmpty(needle) && !haystack.contains(needle.toLowerCase()))
return false;
return true;
}
public static final boolean containsNone(String haystack, Collection<String> needles) {
haystack = haystack.toLowerCase();
for (String needle : needles)
if (!Util.isEmpty(needle) && haystack.contains(needle.toLowerCase()))
return false;
return true;
}
/**
* <b>Bare Bones Browser Launch for Java</b><br>
* Utility class to open a web page from a Swing application
* in the user's default browser.<br>
* Supports: Mac OS X, GNU/Linux, Unix, Windows XP/Vista<br>
* Example Usage:<code><br>
* String url = "http://www.google.com/";<br>
* BareBonesBrowserLaunch.openURL(url);<br></code>
* Latest Version: <a href="http://www.centerkey.com/java/browser/">www.centerkey.com/java/browser</a><br>
* Author: Dem Pilafian<br>
* Public Domain Software -- Free to Use as You Like
* @version 2.0, May 26, 2009
*/
static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
"seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
/**
* Opens the specified web page in a web browser
*
* @param url
* A web address (URL) of a web page (ex:
* "http://www.google.com/")
*/
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] { String.class });
openURL.invoke(null, new Object[] { url });
} else if (osName.startsWith("Windows"))
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
else { // assume Unix or Linux
boolean found = false;
for (String browser : browsers)
if (!found) {
found = Runtime.getRuntime().exec(
new String[] { "which", browser }).waitFor() == 0;
if (found)
Runtime.getRuntime().exec(new String[] { browser, url });
}
if (!found)
throw new Exception(Arrays.toString(browsers));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error attempting to launch web browser\n" + e.toString());
}
}
/**
* Tries to pretty print an XML Document.
* @param document The XML document that needs to be pretty printed.
* @param stripXMLTag Indicates if the<xml ...> tag should get stripped from the result.
* @return The pretty printed string. If the pretty printing is unsuccesful, the 1 lined xml string will be returned.
*/
public static String prettyPrintDocument(Document document, boolean stripXMLTag)
{
// Get the Ajax javascripts.
StringBuffer update = new StringBuffer();
List<Element> initInstructions = document.selectNodes("//initInstruction");
for (Element initInstruction : initInstructions)
{
update.append(initInstruction.getText() + Util.EOL);
initInstruction.detach();
}
String output = "";
try
{
// Try to output the xml 'pretty'
StringWriter stringWriter = new StringWriter();
OutputFormat outputFormat = OutputFormat.createPrettyPrint();
outputFormat.setPadText(false);
outputFormat.setTrimText(false);
XMLWriter out = new XMLWriter(stringWriter, outputFormat);
out.write(document);
output = stringWriter.toString();
}
catch (Exception e)
{
// Pretty printing didn't work, just dump the 1-lined output.
output = document.asXML();
}
// Strip CDATA tags.
output = output.replaceAll("<!\\[CDATA\\[", "").replaceAll("\\]\\]>", "");
if (stripXMLTag)
{
int pos = output.indexOf("<?xml");
if (pos != -1){output = output.substring(output.indexOf(">", pos)+1);}
}
return output;
}
}