MailHandlerDemo.java revision 769
/*
* Copyright (c) 2009-2015 Jason Mehrens. All Rights Reserved.
*
* 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
*
* - Neither the name of Oracle 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 OWNER 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.
*/
/**
* Demo for the different configurations for the MailHandler. If the logging
* properties file or class is not specified then this demo will apply some
* default settings to store emails in the users temp dir.
*
* @author Jason Mehrens
*/
public class MailHandlerDemo {
/**
* This class name.
*/
/**
* The logger for this class name.
*/
/**
* @param args the command line arguments
*/
+ "[[-all] | [-body] | [-debug] | [-low] | [-simple] "
+ "| [-pushlevel] | [-pushfilter] | [-pushnormal]"
+ "| [-pushonly]] "
+ "\n\n"
+ "-all\t\t: Execute all demos.\n"
+ "-body\t\t: An email with all records and only a body.\n"
+ "-debug\t\t: Output basic debug information about the JVM "
+ "and log configuration.\n"
+ "-low\t\t: Generates multiple emails due to low capacity."
+ "\n"
+ "-simple\t\t: An email with all records with body and "
+ "an attachment.\n"
+ "-pushlevel\t: Generates high priority emails when the"
+ " push level is triggered and normal priority when "
+ "flushed.\n"
+ "-pushFilter\t: Generates high priority emails when the "
+ "push level and the push filter is triggered and normal "
+ "priority emails when flushed.\n"
+ "-pushnormal\t: Generates multiple emails when the "
+ "MemoryHandler push level is triggered. All generated "
+ "email are sent as normal priority.\n"
+ "-pushonly\t: Generates multiple emails when the "
+ "MemoryHandler push level is triggered. Generates high "
+ "priority emails when the push level is triggered and "
+ "normal priority when flushed.\n");
} else {
init(l); //may create log messages.
try {
new MessagingException("Fake JavaMail issue."));
new NullPointerException("Fake bug."));
+ "please wait...", getTempDir());
try { //Waste some time for the custom formatter.
} catch (InterruptedException ex) {
}
new FileNotFoundException("Fake file chooser issue."));
new IOException("Fake access denied issue."));
} finally {
}
}
}
/**
* Used debug problems with the logging.properties. The system property
* java.security.debug=access,stack can be used to trace access to the
* LogManager reset.
*
* @param prefix a string to prefix the output.
* @param err any PrintStream or null for System.out.
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
prefix = "DEBUG";
}
}
try {
} else {
}
}
//Force any errors. This is only safe if key is present.
} else {
}
}
} else {
}
synchronized (manager) {
while (e.hasMoreElements()) {
if (l != null) {
+ ", " + l.getName());
}
}
}
}
}
}
}
/**
* Gets a formatting string describing the given handler.
*
* @param prefix the output prefix.
* @param err the error stream.
* @param h the handler.
* @return the formatted string.
*/
try {
if (h instanceof MailHandler) {
}
} catch (SecurityException error) {
}
try {
} catch (SecurityException error) {
}
try {
if (h instanceof MailHandler) {
}
} catch (SecurityException error) {
}
try {
} catch (SecurityException error) {
}
try {
} catch (SecurityException error) {
}
try {
} catch (SecurityException error) {
}
}
/**
* Example for body only messages. On close the remaining messages are sent. <code>
* MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.subject=Body only demo
* ##
* </code>
*/
private static void initBodyOnly() {
MailHandler h = new MailHandler();
h.setSubject("Body only demo");
LOGGER.addHandler(h);
}
/**
* Example showing that when the mail handler reaches capacity it will
* format and send the current records. Capacity is used to roughly limit
* the size of an outgoing message. On close any remaining messages are
* sent. <code>
* MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.subject=Low capacity demo
* com.sun.mail.util.logging.MailHandler.capacity=5
* ##
* </code>
*/
private static void initLowCapacity() {
h.setSubject("Low capacity demo");
LOGGER.addHandler(h);
}
/**
* Example for body only messages. On close any remaining messages are sent. <code>
* MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.subject=Body and attachment demo
* com.sun.mail.util.logging.MailHandler.attachment.formatters=java.util.logging.XMLFormatter
* com.sun.mail.util.logging.MailHandler.attachment.names=data.xml
* ##
* </code>
*/
private static void initSimpleAttachment() {
MailHandler h = new MailHandler();
h.setSubject("Body and attachment demo");
h.setAttachmentFormatters(new XMLFormatter());
h.setAttachmentNames("data.xml");
LOGGER.addHandler(h);
}
/**
* Example setup for priority messages by level. If the push level is
* triggered the message is high priority. Otherwise, on close any remaining
* messages are sent. <code>
* MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.subject=Push level demo
* com.sun.mail.util.logging.MailHandler.pushLevel=WARNING
* ##
* </code>
*/
private static void initWithPushLevel() {
MailHandler h = new MailHandler();
h.setSubject("Push level demo");
LOGGER.addHandler(h);
}
/**
* Example for priority messages by generation rate. If the push filter is
* triggered the message is high priority. Otherwise, on close any remaining
* messages are sent. If the capacity is set to the <code>
* MailHandlerDemo.handlers=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.subject=Push if under two records per minute.
* com.sun.mail.util.logging.MailHandler.pushLevel=ALL
* com.sun.mail.util.logging.MailHandler.pushFilter=com.sun.mail.util.logging.DurationFilter
* com.sun.mail.util.logging.DurationFilter.records=2
* com.sun.mail.util.logging.DurationFilter.duration=1 * 60 * 1000
* ##
* </code>
*/
private static void initWithPushFilter() {
MailHandler h = new MailHandler();
h.setSubject("Push filter demo");
LOGGER.addHandler(h);
}
/**
* Example for circular buffer behavior. The level, push level, and capacity
* are set the same so that the memory handler push results in a mail
* handler push. All messages are high priority. On close any remaining
* records are discarded because they never reach the mail handler. <code>
* MailHandlerDemo.handlers=java.util.logging.MemoryHandler
* java.util.logging.MemoryHandler.target=com.sun.mail.util.logging.MailHandler
* com.sun.mail.util.logging.MailHandler.level=ALL
* java.util.logging.MemoryHandler.level=ALL
* java.util.logging.MemoryHandler.push=WARNING
* com.sun.mail.util.logging.MailHandler.subject=Push on MessagingException demo
* com.sun.mail.util.logging.MailHandler.pushLevel=ALL
* com.sun.mail.util.logging.MailHandler.pushFilter=MailHandlerDemo$MessageErrorsFilter
* ##
* </code>
*/
private static void initPushOnly() {
final int capacity = 3;
h.setSubject("Push only demo");
LOGGER.addHandler(m);
pushOnlyHandler = h;
}
/**
* Holds on to the push only handler. Only declared here to apply fallback
* settings.
*/
private static Handler pushOnlyHandler;
/**
* Example for circular buffer behavior as normal priority. The push level,
* and capacity are set the same so that the memory handler push results in
* a mail handler push. All messages are normal priority. On close any
* remaining records are discarded because they never reach the mail
* handler. Use the LogManager config option or extend the MemoryHandler to
* emulate this behavior via the logging.properties.
*/
private static void initPushNormal() {
final int capacity = 3;
h.setSubject("Push normal demo");
public void push() {
super.push(); //push to target.
super.flush(); //make the target send the email.
}
};
LOGGER.addHandler(m);
pushNormalHandler = h;
}
/**
* Holds on to the push normal handler. Only declared here to apply fallback
* settings.
*/
private static Handler pushNormalHandler;
/**
* Example for various kinds of custom sorting, formatting, and filtering
* for multiple attachment messages. The subject will contain the most
* severe record and a count of remaining records. The log records are
* ordered from most severe to least severe. The body uses a custom
* formatter that includes a summary by date and time. The attachment use
* XML and plain text formats. Each attachment has a different set of
* filtering. The attachment names are generated from either a fixed name or
* are built using the number and type of the records formatted. On close
* any remaining messages are sent. Use the LogManager config option or
* extend the MemoryHandler to emulate this behavior via the
*/
private static void initCustomAttachments() {
MailHandler h = new MailHandler();
//Sort records by severity keeping the severe messages at the top.
//Use subject to provide a hint as to what is in the email.
h.setSubject(new CollectorFormatter());
//Make the body give a simple summary of what happened.
h.setFormatter(new SummaryFormatter());
//Create 3 attachments.
h.setAttachmentFormatters(new XMLFormatter(),
new XMLFormatter(), new SimpleFormatter());
//Filter each attachment differently.
//Creating the attachment name formatters.
new CollectorFormatter("{3} records and {5} errors.xml"),
new CollectorFormatter("{5,choice,0#no errors|1#1 error|1<"
+ "{5,number,integer} errors}.txt"));
LOGGER.addHandler(h);
}
/**
* Sets up the demos that will run.
*
* @param l the list of arguments.
*/
initBodyOnly();
}
}
}
}
}
}
initPushOnly();
}
}
boolean fallback = applyFallbackSettings();
}
if (!l.isEmpty()) {
}
if (fallback) {
}
}
/**
* Close and remove all handlers added to the class logger.
*/
private static void closeHandlers() {
h.close();
LOGGER.removeHandler(h);
}
}
/**
* Apply some fallback settings if no configuration file was specified.
*
* @return true if fallback settings were applied.
*/
private static boolean applyFallbackSettings() {
if (getConfigLocation() == null) {
fallbackSettings(h);
}
return true;
}
return false;
}
/**
* Common fallback settings for a single handler.
*
* @param h the handler.
*/
private static void fallbackSettings(Handler h) {
if (h != null) {
h.setErrorManager(new FileErrorManager());
}
}
/**
* Gets the system temp directory.
*
* @return the system temp directory.
*/
private static String getTempDir() {
}
/**
* Gets the configuration file or class name.
*
* @return the file name or class name.
*/
private static String getConfigLocation() {
}
return file;
}
}