[Schmitzm-commits] r1177 - in trunk: src/schmitzm/lang src/schmitzm/mail src/schmitzm/mail/resource src/schmitzm/mail/resource/locales src/schmitzm/swing src/schmitzm/swing/resource/locales src_junit/schmitzm/swing
scm-commit@wald.intevation.org
scm-commit at wald.intevation.org
Tue Oct 26 16:03:12 CEST 2010
Author: mojays
Date: 2010-10-26 16:03:11 +0200 (Tue, 26 Oct 2010)
New Revision: 1177
Added:
trunk/src/schmitzm/mail/resource/
trunk/src/schmitzm/mail/resource/locales/
trunk/src/schmitzm/mail/resource/locales/MailResourceBundle.properties
trunk/src/schmitzm/mail/resource/locales/MailResourceBundle_de.properties
Modified:
trunk/src/schmitzm/lang/LangUtil.java
trunk/src/schmitzm/mail/MailUtil.java
trunk/src/schmitzm/swing/ExceptionDialog.java
trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle.properties
trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle_de.properties
trunk/src_junit/schmitzm/swing/SwingUtilTest.java
Log:
LangUtil: new helper methods .getCurrentTimeFormatted(.) and .getStackTraceFromException(.)
MailUtil. new helper methods .sendDesktopMail(.) and .sendDesktopExceptionMail(.)
ExceptionDialog: option to generate a (desktop) mail for the exception
Modified: trunk/src/schmitzm/lang/LangUtil.java
===================================================================
--- trunk/src/schmitzm/lang/LangUtil.java 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/lang/LangUtil.java 2010-10-26 14:03:11 UTC (rev 1177)
@@ -31,14 +31,18 @@
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
+import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
+import java.util.Date;
import java.util.Locale;
import java.util.TreeSet;
import java.util.Vector;
@@ -49,6 +53,8 @@
import org.apache.log4j.Category;
import org.apache.log4j.Logger;
+import schmitzm.io.IOUtil;
+
/**
* Diese Klasse stellt Hilfsfunktionen fuer Basisoperationen bereit.
*
@@ -71,6 +77,11 @@
final static Pattern onlyZerosRegEx = Pattern.compile("^([\\s0.,]*)$");
/**
+ * Date formatter for "dd.MM.yyyy [HH:mm:ss]".
+ */
+ public static final DateFormat DEFAULT_DATE_TIME_FORMATTER = new SimpleDateFormat("dd.MM.yyyy [HH:mm:ss]");
+
+ /**
* Liefert <code>true</code> wenn der String nur Nullen, Leerzeichen,
* Kommata und/oder Punkte enthält.
*/
@@ -102,6 +113,35 @@
return "null";
return object.getClass().getSimpleName();
}
+
+ /**
+ * Returns the current time as formatted string.
+ * @param format date format as defined in {@link SimpleDateFormat}
+ * (if {@code null}, the default format is used)
+ * @see #DEFAULT_DATE_TIME_FORMATTER
+ */
+ public static String getCurrentTimeFormatted(String formatPattern) {
+ DateFormat formatter = DEFAULT_DATE_TIME_FORMATTER;
+ if ( formatPattern != null )
+ formatter = new SimpleDateFormat(formatPattern);
+ return formatter.format( new Date(System.currentTimeMillis()) );
+ }
+
+ /**
+ * Returns an exception stack as string.
+ */
+ public static String getStackTraceFromException(Throwable err) {
+ // convert exception stack to string
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream( outputStream );
+ err.printStackTrace(printStream);
+
+ String stackTraceStr = outputStream.toString();
+ printStream.close();
+ IOUtil.closeOutputStream(outputStream);
+
+ return stackTraceStr;
+ }
/**
* Haengt Strings aneinander, getrennt durch Trennzeichen.
Modified: trunk/src/schmitzm/mail/MailUtil.java
===================================================================
--- trunk/src/schmitzm/mail/MailUtil.java 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/mail/MailUtil.java 2010-10-26 14:03:11 UTC (rev 1177)
@@ -1,7 +1,18 @@
package schmitzm.mail;
+import java.awt.Desktop;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.io.PrintStream;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.text.CharacterIterator;
+import java.text.StringCharacterIterator;
import java.util.Date;
+import java.util.Locale;
import java.util.Properties;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
import javax.mail.Authenticator;
import javax.mail.Message;
@@ -12,16 +23,92 @@
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
+import javax.swing.JOptionPane;
+import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.log4j.Logger;
+import schmitzm.io.InputBuffer;
+import schmitzm.lang.LangUtil;
+import schmitzm.lang.ResourceProvider;
+import schmitzm.swing.ExceptionDialog;
+import schmitzm.swing.SwingUtil;
+
/**
* Diese Klasse stellt Hilfsmethoden zum verschicken von Mails bereit.
*/
public class MailUtil {
- private static Logger log = Logger.getLogger(MailUtil.class);
+ /** Mail address for Martin Schmitz. */
+ public static final String MAIL_ADDR_MARTIN_SCHMITZ = "Martin.Schmitz at koeln.de";
+ /** Mail address for Stefan Tzeggai. */
+ public static final String MAIL_ADDR_STEFAN_TZEGGAI = "tzeggai at wikisquare.de";
+
+ private static Logger log = Logger.getLogger(MailUtil.class);
+ /**
+ * {@link ResourceProvider} for the localization of the package
+ * {@code schmitzm.Mail}. These are provided in property files under
+ * {@code schmitzm.mail.resource.locales}.
+ */
+ public static ResourceProvider RESOURCE = ResourceProvider.newInstance(
+ LangUtil.extendPackagePath(MailUtil.class,
+ "resource.locales.MailResourceBundle"), Locale.ENGLISH);
+
+ /** Maximale Laenge des Mail-Bodies. Ist der Mail-Inhalt laenger, wird er
+ * gekuerzt. */
+ private static final int MAX_MAIL_BODY_SIZE = 1500;
+
/**
+ * Opens the local mail client with a new mail.
+ * @param mailDestAddr destination address(es); can be {@code null}
+ * @param mailSubject mail subject; can be {@code null}
+ * @param mailBody mail body content; can be {@code null}
+ */
+ public static void sendDesktopMail(String mailDestAddr, String mailSubject, String mailBody) {
+ if (!Desktop.isDesktopSupported() ||
+ !Desktop.getDesktop().isSupported(Desktop.Action.MAIL)) {
+ JOptionPane.showMessageDialog(null, RESOURCE.getString("MailUtil.DesktopMail.NotSupported"));
+ return;
+ }
+
+ try {
+ // Mail body can not be infinitely big
+ if ( mailBody.length() > MAX_MAIL_BODY_SIZE )
+ mailBody = mailBody.substring(0,MAX_MAIL_BODY_SIZE) + "...\n[...]";
+
+ StringBuffer uriMailStr = new StringBuffer();
+ uriMailStr.append( mailDestAddr != null ? mailDestAddr : "");
+ uriMailStr.append("?SUBJECT=").append( mailSubject != null ? mailSubject : "");
+ uriMailStr.append("&BODY=").append( mailBody != null ? mailBody : "");
+ URI uriMailTo = new URI("mailto",uriMailStr.toString(),null);
+ Desktop.getDesktop().mail(uriMailTo);
+ } catch (Exception err) {
+ ExceptionDialog.show(null, err, null, RESOURCE.getString("MailUtil.DesktopMail.CreationError"));
+ }
+ }
+
+ /**
+ * Opens the local mail client with a new mail for an exception.
+ * @param mailDestAddr destination address(es); can be {@code null}
+ * @param err exception to create a mail for
+ */
+ public static void sendDesktopExceptionMail(String mailDestAddr, Throwable err) {
+ String exceptionMess = err.getMessage();
+ String exceptionStack = LangUtil.getStackTraceFromException(err);
+
+ StringBuffer mailBody = new StringBuffer();
+ mailBody.append("\n")
+ .append("Date/Time: ").append(LangUtil.getCurrentTimeFormatted(null)).append("\n")
+ .append("Exception: ").append(exceptionMess).append("\n")
+ .append("Java version: ").append(System.getProperty("java.version")).append("\n")
+ .append("\n")
+ .append(exceptionStack);
+ String mailSubject = "Exception-Report: " + exceptionMess;
+
+ sendDesktopMail(mailDestAddr, mailSubject, mailBody.toString());
+ }
+
+ /**
* Verschickt eine Email, wobei der Login Klartext erfolgt. Die Email wird
* auf dem Aktuellen Thread verschickt und kann natürlich theoretisch
* längere zeit beanspruchen! Kein Parameter darf <code>null</code> sein.
@@ -30,7 +117,7 @@
* A {@link Properties} instance containing all basic
* configuration of the mailservice.
*/
- public void sendMail_cleartext(final String recipientsAddress,
+ public static void sendMail_cleartext(final String recipientsAddress,
final String subject, final String text, Properties settings)
throws MessagingException {
@@ -104,7 +191,7 @@
log.debug("Verschicken erfolgreich!");
}
- class MailAuthenticator extends Authenticator {
+ static class MailAuthenticator extends Authenticator {
/**
* Ein String, der den Usernamen nach der Erzeugung eines Objektes<br>
@@ -142,4 +229,51 @@
}
}
+// Sample code from http://www.javapractices.com/topic/TopicAction.do?Id=242
+// to quote the mail body by encodeUnusualChars(..)
+// Maybe we can reuse this (untested) code in future
+
+// private static final Pattern SIMPLE_CHARS = Pattern.compile("[a-zA-Z0-9]");
+//
+// private String encodeUnusualChars(String aText){
+// StringBuilder result = new StringBuilder();
+// CharacterIterator iter = new StringCharacterIterator(aText);
+// for(char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
+// char[] chars = {c};
+// String character = new String(chars);
+// if(isSimpleCharacter(character)){
+// result.append(c);
+// }
+// else {
+// hexEncode(character, "UTF-8", result);
+// }
+// }
+// return result.toString();
+// }
+//
+// private boolean isSimpleCharacter(String aCharacter){
+// Matcher matcher = SIMPLE_CHARS.matcher(aCharacter);
+// return matcher.matches();
+// }
+//
+// /**
+// For the given character and encoding, appends one or more hex-encoded characters.
+// For double-byte characters, two hex-encoded items will be appended.
+// */
+// private static void hexEncode(String aCharacter, String aEncoding, StringBuilder aOut) {
+// try {
+// String HEX_DIGITS = "0123456789ABCDEF";
+// byte[] bytes = aCharacter.getBytes(aEncoding);
+// for (int idx = 0; idx < bytes.length; idx++) {
+// aOut.append('%');
+// aOut.append(HEX_DIGITS.charAt((bytes[idx] & 0xf0) >> 4));
+// aOut.append(HEX_DIGITS.charAt(bytes[idx] & 0xf));
+// }
+// }
+// catch (UnsupportedEncodingException ex) {
+// ex.printStackTrace();
+// }
+// }
+
+
}
Added: trunk/src/schmitzm/mail/resource/locales/MailResourceBundle.properties
===================================================================
--- trunk/src/schmitzm/mail/resource/locales/MailResourceBundle.properties 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/mail/resource/locales/MailResourceBundle.properties 2010-10-26 14:03:11 UTC (rev 1177)
@@ -0,0 +1,62 @@
+##########
+#Copyright (c) 2009 Martin O. J. Schmitz.
+#
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focusing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#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 Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focussing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#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 Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+# ---------------------------------------------------------------
+# ------ Default Translations (english) for components ------
+# ------ in Package schmitzm.mail ------
+# ---------------------------------------------------------------
+
+MailUtil.DesktopMail.NotSupported=Mailing is not supported on your operating system!
+MailUtil.DesktopMail.CreationError=Error during creation of exception mail
Added: trunk/src/schmitzm/mail/resource/locales/MailResourceBundle_de.properties
===================================================================
--- trunk/src/schmitzm/mail/resource/locales/MailResourceBundle_de.properties 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/mail/resource/locales/MailResourceBundle_de.properties 2010-10-26 14:03:11 UTC (rev 1177)
@@ -0,0 +1,62 @@
+##########
+#Copyright (c) 2009 Martin O. J. Schmitz.
+#
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focusing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#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 Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+#This file is part of the SCHMITZM library - a collection of utility
+#classes based on Java 1.6, focussing (not only) on Java Swing
+#and the Geotools library.
+#
+#The SCHMITZM project is hosted at:
+#http://wald.intevation.org/projects/schmitzm/
+#
+#This program is free software; you can redistribute it and/or
+#modify it under the terms of the GNU Lesser General Public License
+#as published by the Free Software Foundation; either version 3
+#of the License, or (at your option) any later version.
+#
+#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 Lesser General Public License (license.txt)
+#along with this program; if not, write to the Free Software
+#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+#or try this link: http://www.gnu.org/licenses/lgpl.html
+#
+#Contributors:
+# Martin O. J. Schmitz - initial API and implementation
+# Stefan A. Tzeggai - additional utility classes
+##########
+# ----------------------------------------------------
+# ------ German Translations for components ------
+# ------ in Package schmitzm.mail ------
+# ----------------------------------------------------
+
+MailUtil.DesktopMail.NotSupported=Mailen wird von Ihrem Betriebssystem leider nicht unterst\u00FCtzt.
+MailUtil.DesktopMail.CreationError=Fehler beim Erstellen der Fehler-Mail
Modified: trunk/src/schmitzm/swing/ExceptionDialog.java
===================================================================
--- trunk/src/schmitzm/swing/ExceptionDialog.java 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/swing/ExceptionDialog.java 2010-10-26 14:03:11 UTC (rev 1177)
@@ -49,6 +49,7 @@
import javax.swing.SwingUtilities;
import schmitzm.lang.LangUtil;
+import schmitzm.mail.MailUtil;
/**
* Diese Klasse stellt eine modale Fehler-Meldung dar. Diese besteht neben einer
@@ -60,6 +61,10 @@
* @version 1.0
*/
public class ExceptionDialog extends JDialog {
+ /** Enthaelt die Empfaenger-Adresse, an die eine Exception gemailt wird.
+ * #see {@link #setMailDestinationAddress(String)} */
+ protected static String destMailAddr = MailUtil.MAIL_ADDR_MARTIN_SCHMITZ;
+
/** Speichert den angezeigten Fehler. */
protected Throwable err = null;
/** Label in dem die Meldung angezeigt wird. */
@@ -72,6 +77,8 @@
protected JButton copyToClipboardButton = null;
/** Button um die Exception auf die Console zu kopieren. */
protected JButton copyToConsoleButton = null;
+ /** Button um die Exception im Mail-Programm zu oeffnen. */
+ protected JButton mailButton = null;
/** Bereich, in dem die Details angezeigt werden. */
protected JTextArea detailsTextArea = null;
/** ScrollPane, in dem sich die TextArea fuer die Details befinden. */
@@ -90,6 +97,21 @@
private static boolean throwRuntimeExceptionsBack = false;
/**
+ * Liefert die Mail-Adresse(n), an die eine Exception gemailt wird.
+ */
+ public static String getMailDestinationAddress() {
+ return destMailAddr;
+ }
+
+ /**
+ * Setzt die Mail-Adresse(n), an die eine Exception gemailt wird.
+ */
+ public static void setMailDestinationAddress(String mailAddr) {
+ destMailAddr = mailAddr;
+ }
+
+
+ /**
* Erzeugt einen neuen Fehler-Dialog. Dem Dialog wird zunaechst noch keine
* Fehlermeldung zugeordnet.
*
@@ -184,6 +206,7 @@
SwingUtil.RESOURCE.getString("ExceptionDialog.CopyToConsole"));
this.copyToClipboardButton = new JButton(
SwingUtil.RESOURCE.getString("ExceptionDialog.CopyToClipboard"));
+ this.mailButton = new JButton(SwingUtil.RESOURCE.getString("ExceptionDialog.Mail"));
this.detailsButton = new JToggleButton(
SwingUtil.RESOURCE.getString("Details"), showDetails);
this.detailsTextArea = new JTextArea(10, 60);
@@ -195,7 +218,7 @@
JOptionPane pane = new JOptionPane(messageLabel,
JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION, null,
new Object[] { okButton, detailsButton, copyToConsoleButton,
- copyToClipboardButton });
+ copyToClipboardButton, mailButton });
JDialog dialog = pane.createDialog(parent, title);
// Dialog nach Vorlage initialisieren
@@ -229,12 +252,19 @@
getError().printStackTrace();
}
});
+ this.mailButton.addActionListener(new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ if (getError() == null)
+ return;
+ MailUtil.sendDesktopExceptionMail(destMailAddr, getError());
+ }
+ });
pack();
SwingUtil.setRelativeFramePosition(this,
SwingUtil.getParentWindow(parent), 0.5, 0.5);
}
-
+
/**
* Liefert die angezeigte Fehlermeldung.
*/
@@ -429,4 +459,5 @@
public static boolean isThrowRuntimeExceptionsBack() {
return throwRuntimeExceptionsBack;
}
+
}
Modified: trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle.properties
===================================================================
--- trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle.properties 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle.properties 2010-10-26 14:03:11 UTC (rev 1177)
@@ -92,6 +92,7 @@
ExceptionDialog.CopyToClipboard=Copy to clipboard
ExceptionDialog.CopyToConsole=Copy to console
+ExceptionDialog.Mail=Mail
ManualInputOption.PasswordVisible.visibility=visible
Modified: trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle_de.properties
===================================================================
--- trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle_de.properties 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src/schmitzm/swing/resource/locales/SwingResourceBundle_de.properties 2010-10-26 14:03:11 UTC (rev 1177)
@@ -89,6 +89,7 @@
ExceptionDialog.CopyToClipboard=In die Zwischenablage
ExceptionDialog.CopyToConsole=Auf Console ausgeben
+ExceptionDialog.Mail=Mailen
ManualInputOption.PasswordVisible.visibility=sichtbar
Modified: trunk/src_junit/schmitzm/swing/SwingUtilTest.java
===================================================================
--- trunk/src_junit/schmitzm/swing/SwingUtilTest.java 2010-10-26 12:21:00 UTC (rev 1176)
+++ trunk/src_junit/schmitzm/swing/SwingUtilTest.java 2010-10-26 14:03:11 UTC (rev 1177)
@@ -14,6 +14,13 @@
public class SwingUtilTest {
@Test
+ public void textExceptionDialog() {
+ if ( !TestingUtil.isInteractive() )
+ return;
+ ExceptionDialog.show( new Exception("Test exception") );
+ }
+
+ @Test
public void testConvertColorToHexColor() {
assertEquals("#0000ff", SwingUtil.convertColorToHex(Color.BLUE));
}
More information about the Schmitzm-commits
mailing list