UncaughtExceptionManager.java
| Index Score | ||
|---|---|---|
![]() |
![]() |
org.xnap.util |
![]() |
![]() |
XNap 3 |
View: Reasons, Metrics, Source Code
These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.
/*
* XNap - A P2P framework and client.
*
* See the file AUTHORS for copyright information.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.xnap.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import org.apache.log4j.Logger;
import org.xnap.plugin.PluginInfo;
import org.xnap.plugin.PluginManager;
public class UncaughtExceptionManager {
private static final String BLACKLIST_FILENAME
= FileHelper.getHomeDir() + "problemreport";
protected static Logger logger = Logger.getLogger(UncaughtExceptionManager.class);
private static Preferences prefs = Preferences.getInstance();
private static UncaughtExceptionManager singleton = new UncaughtExceptionManager();
private Vector listeners = new Vector();
private HashSet blacklist = new HashSet();
private UncaughtExceptionManager()
{
readBlackList();
}
public static UncaughtExceptionManager getInstance() {
return singleton;
}
public void addExceptionListener(UncaughtExceptionListener l) {
listeners.add(l);
}
public void removeExceptionListener(UncaughtExceptionListener l) {
listeners.remove(l);
}
/**
* Handles e thrown by t. Notifies all listeners in case e is not
* blacklisted.
*/
public void notify(Thread t, Throwable e)
{
// if exception on blacklist do nothing!
if (!notifyAgain(e)) {
logger.warn("Blacklisted error occured!");
e.printStackTrace(System.err);
return;
}
Object[] l = listeners.toArray();
if (l != null && l.length > 0) {
for (int i = l.length - 1; i >= 0; i--) {
((UncaughtExceptionListener)l[i]).uncaughtException(t, e);
}
}
else {
e.printStackTrace(System.err);
}
}
public void notify(Throwable e)
{
notify(Thread.currentThread(), e);
}
public void dontNotifyAgain(Throwable e) {
blacklist.add(buildMD5Hash(e));
writeBlacklist();
}
/**
* Returns stacktrace as String
*
* @param e
*/
public static String getStackTrace(Throwable e)
{
if (e == null) {
return "";
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintWriter printWriter = new PrintWriter(baos);
e.printStackTrace(printWriter);
printWriter.close();
return removeExceptionDescription
(removeExceptionDescription
(removeExceptionDescription
(baos.toString(),
"java.lang.IndexOutOfBoundsException"),
"java.lang.ArrayIndexOutOfBoundsException"),
"java.lang.RuntimeException");
}
public static String removeExceptionDescription(String trace,
String prefix)
{
if (trace.startsWith(prefix + ": ")) {
int i = trace.indexOf("\n");
if (i != -1) {
return prefix + trace.substring(i);
}
}
return trace;
}
// public static String getLoadedJars() {
// StringBuffer s = new StringBuffer();
// s.append("\nLoaded jars:\n");
// URL[] urls = XNapClassLoader.getInstance().getURLs();
// for (int i=0; i < urls.length; i++) {
// s.append(urls[i].toString()+"\n");
// }
// return s.toString();
// }
public static String getPlugin(Throwable e)
{
return getPlugin(getStackTrace(e));
}
/**
* Scans the stack trace of e for an plugin packages and returns the plugin
* name and version in case of success.
*
* @return null, if no plugin matched; the plugin name and version separated by a space, otherwise
*/
static String getPlugin(String s)
{
// in case we find no enabled plugin we might return a disabled plugin
// as some plugins could still have "zombie" threads arounds after
// they were disabled
String fallback = null;
StringTokenizer t = new StringTokenizer(s, "\n");
while (t.hasMoreTokens()) {
String line = t.nextToken();
if (line.indexOf("org.xnap.plugin") != -1) {
for (Iterator it = PluginManager.getInstance().infos(); it.hasNext();) {
PluginInfo info = (PluginInfo)it.next();
if (info.getClassName() != null && !info.isBase()) {
String packageName = StringHelper.lastPrefix(info.getClassName(), ".");
if (line.indexOf(packageName) != -1) {
if (info.isEnabled()) {
return info.getName() + " " + info.getVersion();
}
else if (fallback == null) {
fallback = info.getName() + " " + info.getVersion();
}
}
}
}
}
}
return fallback;
}
private static String asHex (byte hash[]) {
StringBuffer buf = new StringBuffer(hash.length * 2);
int i;
for (i = 0; i < hash.length; i++) {
if (((int) hash[i] & 0xff) < 0x10)
buf.append("0");
buf.append(Long.toString((int) hash[i] & 0xff, 16));
}
return buf.toString();
}
private static String buildMD5Hash(Throwable e)
{
return buildMD5Hash(getStackTrace(e));
}
private static String buildMD5Hash(String s)
{
MessageDigest md;
try {
md = MessageDigest.getInstance("MD5");
return asHex(md.digest(s.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace(System.err);
}
return "";
}
private boolean notifyAgain(Throwable e) {
return !(blacklist.contains(buildMD5Hash(e)));
}
private String encode(Object o)
{
return (o != null) ? URLEncoder.encode(o.toString()) : "";
}
/**
* @param thread
* @param throwable
*/
public void sendProblemReport(Thread thread, Throwable throwable)
throws IOException
{
Properties p = System.getProperties();
StringBuffer report = new StringBuffer();
report.append("version=" + encode(PluginManager.getCoreVersion()));
report.append("&plugin=" + encode(getPlugin(throwable)));
report.append("&locale=" + encode(Locale.getDefault()));
report.append("&os_name=" + encode(p.get("os.name")));
report.append("&os_version=" + encode(p.get("os.version")));
report.append("&os_arch=" + encode(p.get("os.arch")));
report.append("&java_vendor=" + encode(p.get("java.vendor")));
report.append("&java_version=" + encode(p.get("java.version")));
report.append("&stacktrace=" + encode(getStackTrace(throwable)));
String hash = buildMD5Hash(report.toString());
String problemHash = buildMD5Hash(throwable);
report.append("&hash=" + encode(hash));
report.append("&problem_hash=" + encode(problemHash));
URL url=new URL(prefs.get("problemReportURL"));
HttpURLConnection conn = (HttpURLConnection)(url.openConnection());
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
PrintWriter out=new PrintWriter(conn.getOutputStream());
out.println(report);
out.flush();
out.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String s;
while ((s = in.readLine())!=null) {
logger.debug(s);
}
in.close();
conn.disconnect();
//if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK)
// logger.error("Problem sending problem report");
// throw new IOException(conn.getResponseMessage());
}
/**
*
*/
private void readBlackList()
{
logger.info("reading problem report blacklist: "
+ BLACKLIST_FILENAME);
FileInputStream in = null;
try {
in = new FileInputStream(BLACKLIST_FILENAME);
ObjectInputStream p = new ObjectInputStream(in);
blacklist = (HashSet)p.readObject();
}
catch (Throwable e) {
}
finally {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
}
}
}
/**
*
*/
private void writeBlacklist()
{
logger.info("writing problem report blacklist: "
+ BLACKLIST_FILENAME);
FileOutputStream out = null;
try {
out = new FileOutputStream(BLACKLIST_FILENAME);
ObjectOutputStream p = new ObjectOutputStream(out);
p.writeObject(blacklist);
}
catch (IOException e) {
}
finally {
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
}
}
}
}
The table below shows all metrics for UncaughtExceptionManager.java.




