public class MailHandler
extends java.util.logging.Handler
This Handler will store a fixed number of log records used to generate a single email message. When the internal buffer reaches capacity, all log records are formatted and placed in an email which is sent to an email server. The code to manually setup this handler can be as simple as the following:
Properties props = new Properties(); props.put("mail.smtp.host", "my-mail-server"); props.put("mail.to", "me@example.com"); props.put("verify", "local"); MailHandler h = new MailHandler(props); h.setLevel(Level.WARNING);
Configuration: The LogManager should define at least one or more recipient addresses and a mail host for outgoing email. The code to setup this handler via the logging properties can be as simple as the following:
#Default MailHandler settings. com.sun.mail.util.logging.MailHandler.mail.smtp.host = my-mail-server com.sun.mail.util.logging.MailHandler.mail.to = me@example.com com.sun.mail.util.logging.MailHandler.level = WARNING com.sun.mail.util.logging.MailHandler.verify = localFor a custom handler, e.g. com.foo.MyHandler, the properties would be:
#Subclass com.foo.MyHandler settings. com.foo.MyHandler.mail.smtp.host = my-mail-server com.foo.MyHandler.mail.to = me@example.com com.foo.MyHandler.level = WARNING com.foo.MyHandler.verify = localAll mail properties documented in the Java Mail API cascade to the LogManager by prefixing a key using the fully qualified class name of this MailHandler or the fully qualified derived class name dot mail property. If the prefixed property is not found, then the mail property itself is searched in the LogManager. By default each MailHandler is initialized using the following LogManager configuration properties where <handler-name> refers to the fully qualified class name of the handler. If properties are not defined, or contain invalid values, then the specified default values are used.
Normalization: The error manager, filters, and formatters when loaded from the LogManager are converted into canonical form inside the MailHandler. The pool of interned values is limited to each MailHandler object such that no two MailHandler objects created by the LogManager will be created sharing identical error managers, filters, or formatters. If a filter or formatter should not be interned then it is recommended to retain the identity equals and identity hashCode methods as the implementation. For a filter or formatter to be interned the class must implement the equals and hashCode methods. The recommended code to use for stateless filters and formatters is:
public boolean equals(Object obj) { return obj == null ? false : obj.getClass() == getClass(); } public int hashCode() { return 31 * getClass().hashCode(); }
Sorting: All LogRecord objects are ordered prior to formatting if this Handler has a non null comparator. Developers might be interested in sorting the formatted email by thread id, time, and sequence properties of a LogRecord. Where as system administrators might be interested in sorting the formatted email by thrown, level, time, and sequence properties of a LogRecord. If comparator for this handler is null then the order is unspecified.
Formatting: The main message body is formatted using the Formatter returned by getFormatter(). Only records that pass the filter returned by getFilter() will be included in the message body. The subject Formatter will see all LogRecord objects that were published regardless of the current Filter. The MIME type of the message body can be overridden by adding a MIME entry using the simple class name of the body formatter as the file extension. The MIME type of the attachments can be overridden by changing the attachment file name extension or by editing the default MIME entry for a specific file name extension.
Attachments: This Handler allows multiple attachments per each email message. The presence of an attachment formatter will change the content type of the email message to a multi-part message. The attachment order maps directly to the array index order in this Handler with zero index being the first attachment. The number of attachment formatters controls the number of attachments per email and the content type of each attachment. The attachment filters determine if a LogRecord will be included in an attachment. If an attachment filter is null then all records are included for that attachment. Attachments without content will be omitted from email message. The attachment name formatters create the file name for an attachment. Custom attachment name formatters can be used to generate an attachment name based on the contents of the attachment.
Push Level and Push Filter: The push method, push level, and optional push filter can be used to conditionally trigger a push at or prior to full capacity. When a push occurs, the current buffer is formatted into an email and is sent to the email server. If the push method, push level, or push filter trigger a push then the outgoing email is flagged as high importance with urgent priority.
Buffering: Log records that are published are stored in an internal buffer. When this buffer reaches capacity the existing records are formatted and sent in an email. Any published records can be sent before reaching capacity by explictly calling the flush, push, or close methods. If a circular buffer is required then this handler can be wrapped with a MemoryHandler typically with an equivalent capacity, level, and push level.
Error Handling: If the transport of an email message fails, the email is converted to a raw string and is then passed as the msg parameter to reportError along with the exception describing the cause of the failure. This allows custom error managers to store, reconstruct, and resend the original MimeMessage. The message parameter string is not a raw email if it starts with value returned from Level.SEVERE.getName(). Custom error managers can use the following test to determine if the msg parameter from this handler is a raw email:
public void error(String msg, Exception ex, int code) { if (msg == null || msg.length() == 0 || msg.startsWith(Level.SEVERE.getName())) { super.error(msg, ex, code); } else { //The 'msg' parameter is a raw email. } }
Modifier and Type | Class and Description |
---|---|
private static class |
MailHandler.DefaultAuthenticator
Used for storing a password from the LogManager or literal string.
|
private static class |
MailHandler.GetAndSetContext
Performs a get and set of the context class loader with privileges
enabled.
|
private static class |
MailHandler.TailNameFormatter
Used for naming attachment file names and the main subject line.
|
Modifier and Type | Field and Description |
---|---|
private java.util.logging.Filter[] |
attachmentFilters
Holds the filters for each attachment.
|
private java.util.logging.Formatter[] |
attachmentFormatters
Holds the formatters that create the content for each attachment.
|
private java.util.logging.Formatter[] |
attachmentNames
Holds the formatters that create the file name for each attachment.
|
private Authenticator |
auth
Holds the authenticator required to login to the email server.
|
private int |
capacity
The maximum number of log records to format per email.
|
private java.util.Comparator<? super java.util.logging.LogRecord> |
comparator
Used to order all log records prior to formatting.
|
private javax.activation.FileTypeMap |
contentTypes
Used to override the content type for the body and set the content type
for each attachment.
|
private java.util.logging.LogRecord[] |
data
Holds all of the log records that will be used to create the email.
|
private static java.util.logging.Filter[] |
EMPTY_FILTERS
Use the emptyFilterArray method.
|
private static java.util.logging.Formatter[] |
EMPTY_FORMATTERS
Use the emptyFormatterArray method.
|
private java.lang.String |
encoding
Holds the encoding name for this handler.
|
private java.util.logging.ErrorManager |
errorManager
Holds the error manager for this handler.
|
private java.util.logging.Filter |
filter
Holds the entry and body filter for this handler.
|
private java.util.logging.Formatter |
formatter
Holds the entry and body filter for this handler.
|
private boolean |
isWriting
Determines if we are inside of a push.
|
private java.util.logging.Level |
logLevel
Holds the level for this handler.
|
private static java.security.PrivilegedAction<java.lang.Object> |
MAILHANDLER_LOADER
The action to set the context class loader for use with the JavaMail API.
|
private java.util.Properties |
mailProps
Holds all of the email server properties.
|
private int[] |
matched
A mapping of log record to matching filter index.
|
private static int |
MIN_HEADER_SIZE
Min byte size for header data.
|
private static java.lang.ThreadLocal<java.lang.Integer> |
MUTEX
A thread local mutex used to prevent logging loops.
|
private static java.lang.Integer |
MUTEX_LINKAGE
The used for linkage error reporting.
|
private static java.lang.Integer |
MUTEX_PUBLISH
The marker object used to report a publishing state.
|
private static java.lang.Integer |
MUTEX_REPORT
The used for the error reporting state.
|
private static int |
offValue
Cache the off value.
|
private java.util.logging.Filter |
pushFilter
Holds the push filter for trigger conditions requiring an early push.
|
private java.util.logging.Level |
pushLevel
Holds the push level for this handler.
|
private boolean |
sealed
Used to turn off security checks.
|
private Session |
session
Holds the session object used to generate emails.
|
private int |
size
The number of log records in the buffer.
|
private java.util.logging.Formatter |
subjectFormatter
Holds the formatter used to create the subject line of the email.
|
Constructor and Description |
---|
MailHandler()
Creates a MailHandler that is configured by the
LogManager configuration properties.
|
MailHandler(int capacity)
Creates a MailHandler that is configured by the
LogManager configuration properties but overrides the
LogManager capacity with the given capacity.
|
MailHandler(java.util.Properties props)
Creates a mail handler with the given mail properties.
|
Modifier and Type | Method and Description |
---|---|
private boolean |
alignAttachmentFilters()
Expand or shrink the attachment filters with the attachment formatters.
|
private boolean |
alignAttachmentNames()
Expand or shrink the attachment name formatters with the attachment
formatters.
|
private boolean |
allowRestrictedHeaders()
Determines if restricted headers are allowed in the current environment.
|
private void |
appendContentLang(MimePart p,
java.util.Locale l)
Appends the content language to the given mime part.
|
private void |
appendFileName(Part part,
java.lang.String chunk)
Constructs a file name from a formatter.
|
private void |
appendFileName0(Part part,
java.lang.String chunk)
It is assumed that file names are short and that in most cases
getTail will be the only method that will produce a result.
|
private void |
appendSubject(Message msg,
java.lang.String chunk)
Constructs a subject line from a formatter.
|
private void |
appendSubject0(Message msg,
java.lang.String chunk)
It is assumed that subject lines are short and that in most cases
getTail will be the only method that will produce a result.
|
private static java.lang.String |
atIndexMsg(int i)
Outline the creation of the index error message.
|
private static MessagingException |
attach(MessagingException required,
java.lang.Exception optional)
Try to attach a suppressed exception to a MessagingException in any order
that is possible.
|
private static java.lang.RuntimeException |
attachmentMismatch(int expected,
int found)
Outline the attachment mismatch message.
|
private static java.lang.RuntimeException |
attachmentMismatch(java.lang.String msg)
A factory used to create a common attachment mismatch type.
|
private void |
checkAccess()
Calls log manager checkAccess if this is sealed.
|
private void |
clearMatches(int index)
Clear previous matches when the filters are modified and there are
existing log records that were matched.
|
void |
close()
Prevents any other records from being published.
|
(package private) java.lang.String |
contentTypeOf(java.lang.CharSequence chunk)
Determines the mimeType of a formatter from the getHead call.
|
(package private) java.lang.String |
contentTypeOf(java.util.logging.Formatter f)
Determines the mimeType of a formatter by the class name.
|
private java.lang.String |
contentWithEncoding(java.lang.String type,
java.lang.String encoding)
Replaces the charset parameter with the current encoding.
|
private MimeBodyPart |
createBodyPart()
Factory to create the in-line body part.
|
private MimeBodyPart |
createBodyPart(int index)
Factory to create the attachment body part.
|
private static java.util.logging.Formatter |
createSimpleFormatter()
Factory method used to create a java.util.logging.SimpleFormatter.
|
private java.util.logging.ErrorManager |
defaultErrorManager()
Used to get or create the default ErrorManager used before init.
|
private java.lang.String |
descriptionFrom(java.util.Comparator<?> c,
java.util.logging.Level l,
java.util.logging.Filter f)
Gets the description for the MimeMessage itself.
|
private java.lang.String |
descriptionFrom(java.util.logging.Formatter f,
java.util.logging.Filter filter,
java.util.logging.Formatter name)
Creates a description for a body part.
|
private static java.util.logging.Filter[] |
emptyFilterArray()
Factory for empty filter arrays.
|
private static java.util.logging.Formatter[] |
emptyFormatterArray()
Factory for empty formatter arrays.
|
private void |
envelopeFor(Message msg,
boolean priority)
Creates all of the envelope information for a message.
|
void |
flush()
Pushes any buffered records to the email server as normal priority.
|
private java.lang.String |
format(java.util.logging.Formatter f,
java.util.logging.LogRecord r)
Creates the formatted log record or reports a formatting error.
|
private java.lang.Object |
getAndSetContextClassLoader(java.lang.Object ccl)
Replaces the current context class loader with our class loader.
|
java.util.logging.Filter[] |
getAttachmentFilters()
Gets the attachment filters.
|
java.util.logging.Formatter[] |
getAttachmentFormatters()
Gets the attachment formatters.
|
java.util.logging.Formatter[] |
getAttachmentNames()
Gets the attachment name formatters.
|
Authenticator |
getAuthenticator()
Gets the Authenticator used to login to the email server.
|
int |
getCapacity()
Gets the number of log records the internal buffer can hold.
|
private java.lang.String |
getClassId(java.util.logging.Formatter f)
Gets a class name represents the behavior of the formatter.
|
java.util.Comparator<? super java.util.logging.LogRecord> |
getComparator()
Gets the comparator used to order all LogRecord objects prior
to formatting.
|
private java.lang.String |
getContentType(java.lang.String name)
Determines the mimeType from the given file name.
|
java.lang.String |
getEncoding()
Return the character encoding for this Handler.
|
private java.lang.String |
getEncodingName()
Gets the encoding set for this handler, mime encoding, or file encoding.
|
java.util.logging.ErrorManager |
getErrorManager()
Retrieves the ErrorManager for this Handler.
|
java.util.logging.Filter |
getFilter()
Get the current Filter for this Handler.
|
java.util.logging.Formatter |
getFormatter()
Return the Formatter for this Handler.
|
java.util.logging.Level |
getLevel()
Get the log level specifying which messages will be logged by this
Handler.
|
private java.lang.String |
getLocalHost(Service s)
Gets the local host from the given service object.
|
java.util.Properties |
getMailProperties()
Gets a copy of the mail properties used for the session.
|
private int |
getMatchedPart()
This is used to get the filter index from when
isLoggable and
isAttachmentLoggable was invoked by publish method. |
java.util.logging.Filter |
getPushFilter()
Gets the push filter.
|
java.util.logging.Level |
getPushLevel()
Gets the push level.
|
private Session |
getSession(Message msg)
Google App Engine doesn't support Message.getSession.
|
java.util.logging.Formatter |
getSubject()
Gets the formatter used to create the subject line.
|
private void |
grow()
Expands the internal buffer up to the capacity.
|
private static boolean |
hasValue(java.lang.String name)
Checks that a string is not empty and not equal to the literal "null".
|
private java.lang.String |
head(java.util.logging.Formatter f)
Creates the head or reports a formatting error.
|
private void |
init(java.util.Properties props)
Configures the handler properties from the log manager.
|
private void |
initAttachmentFilters(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initAttachmentFormaters(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initAttachmentNames(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initAuthenticator(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initCapacity(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initComparator(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initEncoding(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initErrorManager(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initFilter(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initFormatter(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initLevel(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initPushFilter(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
initPushLevel(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private Session |
initSession()
Creates a session using a proxy properties object.
|
private void |
initSubject(java.lang.String p)
Parses LogManager string values into objects used by this handler.
|
private void |
intern()
Interns the error manager, formatters, and filters contained in this
handler.
|
private java.lang.Object |
intern(java.util.Map<java.lang.Object,java.lang.Object> m,
java.lang.Object o)
If possible performs an intern of the given object into the
map.
|
private boolean |
isAttachmentLoggable(java.util.logging.LogRecord record)
Check if any attachment would actually format the given
LogRecord.
|
private static boolean |
isEmpty(java.lang.CharSequence s)
Checks a char sequence value for null or empty.
|
boolean |
isLoggable(java.util.logging.LogRecord record)
Check if this Handler would actually log a given
LogRecord into its internal buffer.
|
(package private) boolean |
isMissingContent(Message msg,
java.lang.Throwable t)
Determines if the given throwable is a no content exception.
|
private boolean |
isPushable(java.util.logging.LogRecord record)
Check if this Handler would push after storing the
LogRecord into its internal buffer.
|
private java.util.Locale |
localeFor(java.util.logging.LogRecord r)
Gets the locale for the given log record from the resource bundle.
|
void |
postConstruct()
A callback method for when this object is about to be placed into
commission.
|
void |
preDestroy()
A callback method for when this object is about to be decommissioned.
|
void |
publish(java.util.logging.LogRecord record)
Stores a LogRecord in the internal buffer.
|
private void |
publish0(java.util.logging.LogRecord record)
Performs the publish after the record has been filtered.
|
void |
push()
Pushes any buffered records to the email server as high importance with
urgent priority.
|
private void |
push(boolean priority,
int code)
Used to perform push or flush.
|
private java.util.logging.Filter[] |
readOnlyAttachmentFilters()
Gets the attachment filters using a happens-before relationship between
this method and setAttachmentFilters.
|
private void |
releaseMutex()
Releases the mutex held by the current thread.
|
private void |
reportError(Message msg,
java.lang.Exception ex,
int code)
Converts a mime message to a raw string or formats the reason
why message can't be changed to raw string and reports it.
|
protected void |
reportError(java.lang.String msg,
java.lang.Exception ex,
int code)
Protected convenience method to report an error to this Handler's
ErrorManager.
|
private void |
reportFilterError(java.util.logging.LogRecord record)
Used when a log record was loggable prior to being inserted
into the buffer but at the time of formatting was no longer loggable.
|
private void |
reportLinkageError(java.lang.Throwable le,
int code)
Reports the given linkage error or runtime exception.
|
private void |
reportNonDiscriminating(java.lang.Object o,
java.lang.Object found)
Reports equals implementations that do not discriminate between objects
of different types or subclass types.
|
private void |
reportNonSymmetric(java.lang.Object o,
java.lang.Object found)
Reports symmetric contract violations an equals implementation.
|
private void |
reportNullError(int code)
Used to outline the bytes to report a null pointer exception.
|
private void |
reportUnexpectedSend(MimeMessage msg,
java.lang.String verify,
java.lang.Exception cause)
Reports that an empty content message was sent and should not have been.
|
private void |
reportUnPublishedError(java.util.logging.LogRecord record)
Report to the error manager that a logging loop was detected and
we are going to break the cycle of messages.
|
private void |
reset()
Sets the size to zero and clears the current buffer.
|
private void |
saveChangesNoContent(Message abort,
java.lang.String msg)
Handles all exceptions thrown when save changes is called on a message
that doesn't have any content.
|
private void |
send(Message msg,
boolean priority,
int code)
Used to send the generated email or write its contents to the
error manager for this handler.
|
private void |
setAcceptLang(Part p)
Sets the accept language to the default locale of the JVM.
|
void |
setAttachmentFilters(java.util.logging.Filter... filters)
Sets the attachment filters.
|
void |
setAttachmentFormatters(java.util.logging.Formatter... formatters)
Sets the attachment Formatter object for this handler.
|
void |
setAttachmentNames(java.util.logging.Formatter... formatters)
Sets the attachment file name formatters.
|
void |
setAttachmentNames(java.lang.String... names)
Sets the attachment file name for each attachment.
|
void |
setAuthenticator(Authenticator auth)
Sets the Authenticator used to login to the email server.
|
void |
setAuthenticator(char... password)
Sets the Authenticator used to login to the email server.
|
private void |
setAuthenticator0(Authenticator auth)
A private hook to handle possible future overrides.
|
private void |
setAutoSubmitted(Message msg)
Signals that this message was generated by automatic process.
|
private void |
setCapacity0(int newCapacity)
Sets the capacity for this handler.
|
void |
setComparator(java.util.Comparator<? super java.util.logging.LogRecord> c)
Sets the comparator used to order all LogRecord objects prior
to formatting.
|
private void |
setContent(MimePart part,
java.lang.CharSequence buf,
java.lang.String type)
Set the content for a part using the encoding assigned to the handler.
|
private void |
setDefaultFrom(Message msg)
Sets the from header to the local address.
|
private void |
setDefaultRecipient(Message msg,
Message.RecipientType type)
Computes the default to-address if none was specified.
|
void |
setEncoding(java.lang.String encoding)
Set the character encoding used by this Handler.
|
private void |
setEncoding0(java.lang.String e)
Set the character encoding used by this handler.
|
private void |
setErrorContent(MimeMessage msg,
java.lang.String verify,
java.lang.Throwable t)
Creates and sets the message content from the given Throwable.
|
void |
setErrorManager(java.util.logging.ErrorManager em)
Define an ErrorManager for this Handler.
|
private void |
setErrorManager0(java.util.logging.ErrorManager em)
Sets the error manager on this handler and the super handler.
|
void |
setFilter(java.util.logging.Filter newFilter)
Set a Filter to control output on this Handler.
|
void |
setFormatter(java.util.logging.Formatter newFormatter)
Set a Formatter.
|
private void |
setFrom(Message msg)
Sets from address header.
|
private void |
setIncompleteCopy(Message msg)
Used to signal that body parts are missing from a message.
|
void |
setLevel(java.util.logging.Level newLevel)
Set the log level specifying which message levels will be
logged by this Handler.
|
private void |
setMailer(Message msg)
Sets the x-mailer header.
|
void |
setMailProperties(java.util.Properties props)
Sets the mail properties used for the session.
|
private void |
setMailProperties0(java.util.Properties props)
A private hook to handle overrides when the public method is declared
non final.
|
private void |
setMatchedPart(int index)
This is used to record the filter index when
isLoggable and
isAttachmentLoggable was invoked by publish method. |
private void |
setPriority(Message msg)
Sets the priority and importance headers.
|
void |
setPushFilter(java.util.logging.Filter filter)
Sets the push filter.
|
void |
setPushLevel(java.util.logging.Level level)
Sets the push level.
|
private boolean |
setRecipient(Message msg,
java.lang.String key,
Message.RecipientType type)
Sets the recipient for the given message.
|
private void |
setReplyTo(Message msg)
Sets reply-to address header.
|
private void |
setSender(Message msg)
Sets sender address header.
|
void |
setSubject(java.util.logging.Formatter format)
Sets the subject formatter for email.
|
void |
setSubject(java.lang.String subject)
Sets a literal string for the email subject.
|
private void |
sort()
Performs a sort on the records if needed.
|
private java.lang.String |
tail(java.util.logging.Formatter f,
java.lang.String def)
Creates the tail or reports a formatting error.
|
private java.lang.String |
toMsgString(java.lang.Throwable t)
Converts a throwable to a message string.
|
private AddressException |
tooManyAddresses(Address[] address,
int offset)
A common factory used to create the too many addresses exception.
|
private java.lang.String |
toRawString(Message msg)
Converts an email message to a raw string.
|
private java.lang.String |
toString(java.util.logging.Formatter f)
Ensure that a formatter creates a valid string for a part name.
|
private boolean |
tryMutex()
Used to detect reentrance by the current thread to the publish method.
|
private Session |
updateSession()
Used to update the cached session object based on changes in
mail properties or authenticator.
|
private static void |
verifyAddresses(Address[] all)
Calls validate for every address given.
|
private static java.net.InetAddress |
verifyHost(java.lang.String host)
Perform a lookup of the host address or FQDN.
|
private static void |
verifyProperties(Session session,
java.lang.String protocol)
Cache common session properties into the LogManagerProperties.
|
private void |
verifySettings(Session session)
Checks all of the settings if the caller requests a verify and a verify
was not performed yet and no verify is in progress.
|
private void |
verifySettings0(Session session,
java.lang.String verify)
Checks all of the settings using the given setting.
|
private Message |
writeLogRecords(int code)
Formats all records in the buffer and places the output in a Message.
|
private Message |
writeLogRecords0()
Formats all records in the buffer and places the output in a Message.
|
private static final java.util.logging.Filter[] EMPTY_FILTERS
private static final java.util.logging.Formatter[] EMPTY_FORMATTERS
private static final int MIN_HEADER_SIZE
private static final int offValue
private static final java.security.PrivilegedAction<java.lang.Object> MAILHANDLER_LOADER
private static final java.lang.ThreadLocal<java.lang.Integer> MUTEX
private static final java.lang.Integer MUTEX_PUBLISH
private static final java.lang.Integer MUTEX_REPORT
private static final java.lang.Integer MUTEX_LINKAGE
private volatile boolean sealed
private boolean isWriting
private java.util.Properties mailProps
private Authenticator auth
private Session session
private int[] matched
private java.util.logging.LogRecord[] data
private int size
private int capacity
private java.util.Comparator<? super java.util.logging.LogRecord> comparator
private java.util.logging.Formatter subjectFormatter
private java.util.logging.Level pushLevel
private java.util.logging.Filter pushFilter
private volatile java.util.logging.Filter filter
private volatile java.util.logging.Level logLevel
private volatile java.util.logging.Filter[] attachmentFilters
private java.lang.String encoding
private java.util.logging.Formatter formatter
private java.util.logging.Formatter[] attachmentFormatters
private java.util.logging.Formatter[] attachmentNames
private javax.activation.FileTypeMap contentTypes
private volatile java.util.logging.ErrorManager errorManager
public MailHandler()
java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public MailHandler(int capacity)
capacity
- of the internal buffer.java.lang.IllegalArgumentException
- if capacity less than one.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public MailHandler(java.util.Properties props)
props
- a non null properties object.java.lang.NullPointerException
- if props is null.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public boolean isLoggable(java.util.logging.LogRecord record)
This method checks if the LogRecord has an appropriate level and whether it satisfies any Filter including any attachment filters. However it does not check whether the LogRecord would result in a "push" of the buffer contents.
isLoggable
in class java.util.logging.Handler
record
- a LogRecordpublic void publish(java.util.logging.LogRecord record)
The isLoggable method is called to check if the given log record is loggable. If the given record is loggable, it is copied into an internal buffer. Then the record's level property is compared with the push level. If the given level of the LogRecord is greater than or equal to the push level then the push filter is called. If no push filter exists, the push filter returns true, or the capacity of the internal buffer has been reached then all buffered records are formatted into one email and sent to the server.
publish
in class java.util.logging.Handler
record
- description of the log event.private void publish0(java.util.logging.LogRecord record)
record
- the record.private void reportUnPublishedError(java.util.logging.LogRecord record)
record
- the record or null.private boolean tryMutex()
private void releaseMutex()
private int getMatchedPart()
isLoggable
and
isAttachmentLoggable
was invoked by publish
method.java.lang.NullPointerException
- if tryMutex was not called.private void setMatchedPart(int index)
isLoggable
and
isAttachmentLoggable
was invoked by publish
method.index
- the filter index.private void clearMatches(int index)
index
- the lowest filter index to clear.public void postConstruct()
org.glassfish.hk2.api.PostConstruct
interface. If this class is
loaded via a lifecycle managed environment other than HK2 then it is
recommended that this method is called either directly or through
extending this class to signal that this object is ready for use.public void preDestroy()
org.glassfish.hk2.api.PreDestory
interface. If this class is loaded via a lifecycle managed environment
other than HK2 then it is recommended that this method is called either
directly or through extending this class to signal that this object will
be destroyed.public void push()
flush()
public void flush()
flush
in class java.util.logging.Handler
push()
public void close()
If this Handler is only implicitly closed by the LogManager, then verification should be turned on.
close
in class java.util.logging.Handler
java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").flush()
public void setLevel(java.util.logging.Level newLevel)
setLevel
in class java.util.logging.Handler
newLevel
- the new value for the log leveljava.lang.NullPointerException
- if newLevel is null.java.lang.SecurityException
- if a security manager exists and
the caller does not have LoggingPermission("control").public java.util.logging.Level getLevel()
getLevel
in class java.util.logging.Handler
public java.util.logging.ErrorManager getErrorManager()
getErrorManager
in class java.util.logging.Handler
java.lang.SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").public void setErrorManager(java.util.logging.ErrorManager em)
The ErrorManager's "error" method will be invoked if any errors occur while using this Handler.
setErrorManager
in class java.util.logging.Handler
em
- the new ErrorManagerjava.lang.SecurityException
- if a security manager exists and if the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if the given error manager is null.private void setErrorManager0(java.util.logging.ErrorManager em)
em
- a non null error manager.java.lang.NullPointerException
- if the given error manager is null.public java.util.logging.Filter getFilter()
getFilter
in class java.util.logging.Handler
public void setFilter(java.util.logging.Filter newFilter)
For each call of publish the Handler will call this Filter (if it is non-null) to check if the LogRecord should be published or discarded.
setFilter
in class java.util.logging.Handler
newFilter
- a Filter object (may be null)java.lang.SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").public java.lang.String getEncoding()
getEncoding
in class java.util.logging.Handler
public void setEncoding(java.lang.String encoding) throws java.io.UnsupportedEncodingException
The encoding should be set before any LogRecords are written to the Handler.
setEncoding
in class java.util.logging.Handler
encoding
- The name of a supported character encoding. May be
null, to indicate the default platform encoding.java.lang.SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").java.io.UnsupportedEncodingException
- if the named encoding is not
supported.private void setEncoding0(java.lang.String e) throws java.io.UnsupportedEncodingException
e
- any encoding name or null for the default.java.io.UnsupportedEncodingException
- if the given encoding is not supported.public java.util.logging.Formatter getFormatter()
getFormatter
in class java.util.logging.Handler
public void setFormatter(java.util.logging.Formatter newFormatter) throws java.lang.SecurityException
Some Handlers may not use Formatters, in which case the Formatter will be remembered, but not used.
setFormatter
in class java.util.logging.Handler
newFormatter
- the Formatter to use (may not be null)java.lang.SecurityException
- if a security manager exists and if the caller
does not have LoggingPermission("control").java.lang.NullPointerException
- if the given formatter is null.public final java.util.logging.Level getPushLevel()
public final void setPushLevel(java.util.logging.Level level)
level
- Level object.java.lang.NullPointerException
- if level is null.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.public final java.util.logging.Filter getPushFilter()
public final void setPushFilter(java.util.logging.Filter filter)
filter
- push filter or nulljava.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.public final java.util.Comparator<? super java.util.logging.LogRecord> getComparator()
public final void setComparator(java.util.Comparator<? super java.util.logging.LogRecord> c)
c
- the LogRecord comparator.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.public final int getCapacity()
public final Authenticator getAuthenticator()
java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public final void setAuthenticator(Authenticator auth)
auth
- an Authenticator object or null if none is required.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.public final void setAuthenticator(char... password)
password
- a password, empty array can be used to only supply a
user name set by mail.user property, or null if no credentials
are required.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.String.toCharArray()
private void setAuthenticator0(Authenticator auth)
auth
- see public method.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.public final void setMailProperties(java.util.Properties props)
props
- a non null properties object.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if props is null.java.lang.IllegalStateException
- if called from inside a push.private void setMailProperties0(java.util.Properties props)
props
- see public method.public final java.util.Properties getMailProperties()
java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").public final java.util.logging.Filter[] getAttachmentFilters()
public final void setAttachmentFilters(java.util.logging.Filter... filters)
filters
- a non null array of filters. A null
index value is allowed. A null value means that all
records are allowed for the attachment at that index.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if filters is nulljava.lang.IndexOutOfBoundsException
- if the number of attachment
name formatters do not match the number of attachment formatters.java.lang.IllegalStateException
- if called from inside a push.public final java.util.logging.Formatter[] getAttachmentFormatters()
public final void setAttachmentFormatters(java.util.logging.Formatter... formatters)
formatters
- a non null array of formatters.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if the given array or any array index is
null.java.lang.IllegalStateException
- if called from inside a push.public final java.util.logging.Formatter[] getAttachmentNames()
public final void setAttachmentNames(java.lang.String... names)
names
- an array of names.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IndexOutOfBoundsException
- if the number of attachment
names do not match the number of attachment formatters.java.lang.IllegalArgumentException
- if any name is empty.java.lang.NullPointerException
- if any given array or name is null.java.lang.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final void setAttachmentNames(java.util.logging.Formatter... formatters)
formatters
- and array of attachment name formatters.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IndexOutOfBoundsException
- if the number of attachment
name formatters do not match the number of attachment formatters.java.lang.NullPointerException
- if any given array or name is null.java.lang.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final java.util.logging.Formatter getSubject()
public final void setSubject(java.lang.String subject)
subject
- a non null string.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if subject is null.java.lang.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
public final void setSubject(java.util.logging.Formatter format)
format
- the subject formatter.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.NullPointerException
- if format is null.java.lang.IllegalStateException
- if called from inside a push.Character.isISOControl(char)
,
Character.isISOControl(int)
protected void reportError(java.lang.String msg, java.lang.Exception ex, int code)
reportError
in class java.util.logging.Handler
msg
- a descriptive string (may be null)ex
- an exception (may be null)code
- an error code defined in ErrorManagerprivate void checkAccess()
final java.lang.String contentTypeOf(java.lang.CharSequence chunk)
chunk
- any char sequence or null.final java.lang.String contentTypeOf(java.util.logging.Formatter f)
f
- the formatter or null.final boolean isMissingContent(Message msg, java.lang.Throwable t)
msg
- the message without content.t
- the throwable chain to test.java.lang.NullPointerException
- if any of the arguments are null.private void reportError(Message msg, java.lang.Exception ex, int code)
msg
- the mime message.ex
- the original exception.code
- the ErrorManager code.private void reportLinkageError(java.lang.Throwable le, int code)
le
- the linkage error or a RuntimeException.code
- the ErrorManager code.java.lang.NullPointerException
- if error is null.private java.lang.String getContentType(java.lang.String name)
name
- the file name or class name.private java.lang.String getEncodingName()
private void setContent(MimePart part, java.lang.CharSequence buf, java.lang.String type) throws MessagingException
part
- the part to assign.buf
- the formatted data.type
- the mime type or null, meaning text/plain.MessagingException
- if there is a problem.private java.lang.String contentWithEncoding(java.lang.String type, java.lang.String encoding)
type
- the content type.encoding
- the java charset name.private void setCapacity0(int newCapacity)
newCapacity
- the max number of records.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").java.lang.IllegalStateException
- if called from inside a push.private java.util.logging.Filter[] readOnlyAttachmentFilters()
private static java.util.logging.Formatter[] emptyFormatterArray()
private static java.util.logging.Filter[] emptyFilterArray()
private boolean alignAttachmentNames()
private boolean alignAttachmentFilters()
private void reset()
private void grow()
private void init(java.util.Properties props)
props
- the given mail properties. Maybe null and are never
captured by this handler.java.lang.SecurityException
- if a security manager exists and the
caller does not have LoggingPermission("control").private void intern()
private java.lang.Object intern(java.util.Map<java.lang.Object,java.lang.Object> m, java.lang.Object o) throws java.lang.Exception
m
- the map used to record the interned values.o
- the object to try an intern.java.lang.SecurityException
- if this operation is not allowed by the
security manager.java.lang.Exception
- if there is an unexpected problem.private static java.util.logging.Formatter createSimpleFormatter()
private static boolean isEmpty(java.lang.CharSequence s)
s
- the char sequence.private static boolean hasValue(java.lang.String name)
name
- the string to check for a value.private void initAttachmentFilters(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initAttachmentFormaters(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initAttachmentNames(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initAuthenticator(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initLevel(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initFilter(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initCapacity(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if argument is null.java.lang.SecurityException
- if not allowed.private void initEncoding(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private java.util.logging.ErrorManager defaultErrorManager()
private void initErrorManager(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initFormatter(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initComparator(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initPushLevel(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initPushFilter(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private void initSubject(java.lang.String p)
p
- the handler class name used as the prefix.java.lang.NullPointerException
- if the given argument is null.java.lang.SecurityException
- if not allowed.private boolean isAttachmentLoggable(java.util.logging.LogRecord record)
record
- a LogRecordprivate boolean isPushable(java.util.logging.LogRecord record)
record
- a LogRecordjava.lang.NullPointerException
- if tryMutex was not called.private void push(boolean priority, int code)
priority
- true for high priority otherwise false for normal.code
- the error manager code.private void send(Message msg, boolean priority, int code)
msg
- the message or null.priority
- true for high priority or false for normal.code
- the ErrorManager code.java.lang.NullPointerException
- if message is null.private void sort()
private Message writeLogRecords(int code)
code
- the error manager code.private Message writeLogRecords0() throws java.lang.Exception
MessagingException
- if there is a problem.java.io.IOException
- if there is a problem.java.lang.RuntimeException
- if there is an unexpected problem.java.lang.Exception
private void verifySettings(Session session)
session
- the current session or null.private void verifySettings0(Session session, java.lang.String verify)
session
- the current session.verify
- the type of verify to perform.private void saveChangesNoContent(Message abort, java.lang.String msg)
abort
- the message requiring save changes.msg
- the error description.private static void verifyProperties(Session session, java.lang.String protocol)
session
- the session.protocol
- the mail protocol.java.lang.NullPointerException
- if session is null.private static java.net.InetAddress verifyHost(java.lang.String host) throws java.io.IOException
host
- the host or null.java.io.IOException
- if the host name is not valid.java.lang.SecurityException
- if security manager is present and doesn't
allow access to check connect permission.private static void verifyAddresses(Address[] all) throws AddressException
all
- any address array, null or empty.AddressException
- if there is a problem.private void reportUnexpectedSend(MimeMessage msg, java.lang.String verify, java.lang.Exception cause)
msg
- the MimeMessage.verify
- the verify enum.cause
- the exception that caused the problem or null.private void setErrorContent(MimeMessage msg, java.lang.String verify, java.lang.Throwable t)
msg
- the message with or without content.verify
- the verify enum.t
- the throwable or null.private Session updateSession()
private Session initSession()
private void envelopeFor(Message msg, boolean priority)
msg
- the Message to write the envelope information.priority
- true for high priority.private MimeBodyPart createBodyPart() throws MessagingException
MessagingException
- if there is a problem.private MimeBodyPart createBodyPart(int index) throws MessagingException
index
- the attachment index.MessagingException
- if there is a problem.java.lang.IndexOutOfBoundsException
- if the given index is not an valid
attachment index.private java.lang.String descriptionFrom(java.util.Comparator<?> c, java.util.logging.Level l, java.util.logging.Filter f)
c
- the comparator.l
- the pushLevel.f
- the pushFilterjava.lang.NullPointerException
- if level is null.private java.lang.String descriptionFrom(java.util.logging.Formatter f, java.util.logging.Filter filter, java.util.logging.Formatter name)
f
- the content formatter.filter
- the content filter.name
- the naming formatter.private java.lang.String getClassId(java.util.logging.Formatter f)
f
- the formatter.java.lang.NullPointerException
- if the parameter is null.private java.lang.String toString(java.util.logging.Formatter f)
f
- the formatter.private void appendFileName(Part part, java.lang.String chunk)
part
- to append to.chunk
- non null string to append.private void appendFileName0(Part part, java.lang.String chunk)
part
- to append to.chunk
- non null string to append.private void appendSubject(Message msg, java.lang.String chunk)
msg
- to append to.chunk
- non null string to append.private void appendSubject0(Message msg, java.lang.String chunk)
msg
- to append to.chunk
- non null string to append.private java.util.Locale localeFor(java.util.logging.LogRecord r)
r
- the log record.private void appendContentLang(MimePart p, java.util.Locale l)
p
- the mime part.l
- the locale to append.java.lang.NullPointerException
- if any argument is null.private void setAcceptLang(Part p)
p
- the part to set.private void reportFilterError(java.util.logging.LogRecord record)
record
- that was not formatted.private void reportNonSymmetric(java.lang.Object o, java.lang.Object found)
o
- the test object must be non null.found
- the possible intern, must be non null.java.lang.NullPointerException
- if any argument is null.private void reportNonDiscriminating(java.lang.Object o, java.lang.Object found)
o
- the test object must be non null.found
- the possible intern, must be non null.java.lang.NullPointerException
- if any argument is null.private void reportNullError(int code)
code
- the ErrorManager code.private java.lang.String head(java.util.logging.Formatter f)
f
- the formatter.private java.lang.String format(java.util.logging.Formatter f, java.util.logging.LogRecord r)
f
- the formatter.r
- the log record.private java.lang.String tail(java.util.logging.Formatter f, java.lang.String def)
f
- the formatter.def
- the default string to use when there is an error.private void setMailer(Message msg)
msg
- the target message.private void setPriority(Message msg)
msg
- the target message.private void setIncompleteCopy(Message msg)
msg
- the message.private void setAutoSubmitted(Message msg)
msg
- the message.private void setFrom(Message msg)
msg
- the target message.private void setDefaultFrom(Message msg)
msg
- the target message.private void setDefaultRecipient(Message msg, Message.RecipientType type)
msg
- the messagetype
- the recipient type.private void setReplyTo(Message msg)
msg
- the target message.private void setSender(Message msg)
msg
- the target message.private AddressException tooManyAddresses(Address[] address, int offset)
address
- the addresses, never null.offset
- the starting address to display.private boolean setRecipient(Message msg, java.lang.String key, Message.RecipientType type)
msg
- the message.key
- the key to search in the session.type
- the recipient type.private java.lang.String toRawString(Message msg) throws MessagingException, java.io.IOException
msg
- a Message object.MessagingException
- if there was a problem with the message.java.io.IOException
- if there was a problem.private java.lang.String toMsgString(java.lang.Throwable t)
t
- any throwable or null.private java.lang.Object getAndSetContextClassLoader(java.lang.Object ccl)
ccl
- null for boot class loader, a class loader, a class used to
get the class loader, or a source object to get the class loader.private static java.lang.RuntimeException attachmentMismatch(java.lang.String msg)
msg
- the exception message.private static java.lang.RuntimeException attachmentMismatch(int expected, int found)
expected
- the expected array length.found
- the array length that was given.private static MessagingException attach(MessagingException required, java.lang.Exception optional)
required
- the exception expected to see as a reported failure.optional
- the suppressed exception.private java.lang.String getLocalHost(Service s)
s
- the service to check.private Session getSession(Message msg)
msg
- the message.java.lang.NullPointerException
- if the given message is null.private boolean allowRestrictedHeaders()
private static java.lang.String atIndexMsg(int i)
i
- the index.