Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/sales.git
src/main/java/com/whitemagicsoftware/notify/HttpTransport.java
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import javax.mail.Address;
-import javax.mail.BodyPart;
-import javax.mail.Message;
-import javax.mail.MessagingException;
-import javax.mail.Multipart;
-import javax.mail.NoSuchProviderException;
-import javax.mail.PasswordAuthentication;
-import javax.mail.Session;
-import javax.mail.Transport;
-import javax.mail.URLName;
-import javax.mail.internet.AddressException;
-import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeBodyPart;
-import javax.mail.internet.MimeMultipart;
-
-/**
- * Responsible for sending messages over HTTP. Subclasses are responsible for
- * providing the sendMessage method implementation.
- *
- * @author White Magic Software, Ltd.
- */
-public abstract class HttpTransport extends Transport {
-
- public final static String MIME_TYPE_PLAIN = "text/plain";
- public final static String MIME_TYPE_MULTIPART = "multipart/*";
- public final static String MIME_TYPE_HTML = "text/html";
-
- /**
- * Constructs a new HttpTransport capable of sending notifications via a
- * RESTFUL API.
- *
- * @param session Session state.
- * @param urlname Set value to null for HTTP.
- */
- public HttpTransport( Session session, URLName urlname ) {
- // This should set the protected instance variables of "this.session"
- // and "this.urlname".
- super( session, urlname );
- }
-
- /**
- * Sets the credentials to use for permission to send messages.
- *
- * @param username The username authorised to send messages over HTTP.
- * @param password The password (or API key) associated with the username.
- */
- public void setAuthentication( String username, String password ) {
- getSession().setPasswordAuthentication(
- getURLName(),
- new PasswordAuthentication( username, password )
- );
- }
-
- /**
- * Sends the given data over the wire.
- *
- * @param data The URL-encoded parameters to send.
- *
- * @throws javax.mail.MessagingException
- */
- protected void send( String data ) throws MessagingException {
- HttpURLConnection connection = open();
-
- write( data, connection );
- String response = read( connection );
- }
-
- /**
- * Convenience method to help create a message with text and HTML body parts.
- *
- * @param text The message's text body part.
- * @param html The message's HTML body part.
- *
- * @return A Multipart instance that wraps the text and HTML.
- *
- * @throws MessagingException
- */
- public Multipart multipart( String text, String html )
- throws MessagingException {
- Multipart multipart = new MimeMultipart( "alternative" );
-
- multipart.addBodyPart( textBodyPart( text ) );
- multipart.addBodyPart( htmlBodyPart( html ) );
-
- return multipart;
- }
-
- /**
- * Helper method to create a new text body part.
- *
- * @param text The text body part to create.
- *
- * @return The text wrapped in a body part.
- *
- * @throws MessagingException
- */
- protected BodyPart textBodyPart( String text )
- throws MessagingException {
- return bodyPart( text, MIME_TYPE_PLAIN );
- }
-
- /**
- * Helper method to create a new HTML body part.
- *
- * @param html The HTML body part to create.
- *
- * @return The HTML wrapped in a body part.
- *
- * @throws MessagingException
- */
- protected BodyPart htmlBodyPart( String html )
- throws MessagingException {
- return bodyPart( html, MIME_TYPE_HTML );
- }
-
- /**
- * Create a new body part with the given content and MIME type.
- *
- * @param content The content to wrap in a MimeBodyPart.
- * @param mimeType The content's MIME type (text or HTML).
- *
- * @return A body part that wraps the content.
- *
- * @throws MessagingException
- */
- protected BodyPart bodyPart( String content, String mimeType )
- throws MessagingException {
- MimeBodyPart part = new MimeBodyPart();
- part.setContent( content, mimeType );
-
- return part;
- }
-
- /**
- * Returns the default encoding to use for converting plain text into safe URL
- * parameters.
- *
- * @return StandardCharsets.UTF_8 by default.
- */
- protected Charset getDefaultCharset() {
- return StandardCharsets.UTF_8;
- }
-
- /**
- * Returns the given text string encoded for passing as a URL parameter.
- *
- * @param text The text to encode.
- *
- * @return The encoded text.
- *
- * @throws MessagingException The text could not be encoded.
- */
- protected String encode( final String text ) throws MessagingException {
- String charset = getDefaultCharset().displayName();
-
- try {
- return URLEncoder.encode( text, charset );
- } catch( UnsupportedEncodingException e ) {
- throw new MessagingException(
- "Invalid default encoding: '" + charset + "'", e );
- }
- }
-
- /**
- * Helper method to return a URL-encoded string.
- *
- * @param text Text to encode.
- *
- * @return The StringBuilder's text, encoded to be URL-friendly.
- *
- * @throws MessagingException
- */
- protected String encode( final StringBuilder text )
- throws MessagingException {
- return encode( text.toString() );
- }
-
- /**
- * Answers whether the string contains any characters.
- *
- * @param string Can be null or empty.
- *
- * @return true The string is empty or zero length or contains only
- * whitespace.
- */
- private boolean isEmpty( final String string ) {
- return string == null || string.trim().length() == 0;
- }
-
- /**
- *
- * @param message Message that contains content to extract.
- *
- * @return The text and HTML portions of the message in array index 0 and 1,
- * respectively.
- *
- * @throws javax.mail.MessagingException Message body not extracted.
- */
- protected String[] extractMessageContents( Message message )
- throws MessagingException {
- String result[] = new String[]{ "", "" };
-
- try {
- // Ensure the mime types are applied.
- //
- // See also: http://stackoverflow.com/a/5031057/59087
- message.saveChanges();
- Object content = message.getContent();
-
- if( content instanceof Multipart ) {
- Multipart multipart = (Multipart)content;
-
- result[ 0 ] = extractMultipart( multipart, MIME_TYPE_PLAIN );
- result[ 1 ] = extractMultipart( multipart, MIME_TYPE_HTML );
- } else if( message.isMimeType( MIME_TYPE_PLAIN ) ) {
- result[ 0 ] = content.toString();
- }
- } catch( IOException e ) {
- throw new MessagingException( "Could not extract message content.", e );
- }
-
- return result;
- }
-
- /**
- * Extracts the content from the multipart instance that matches the given
- * mimeType.
- *
- * @param multipart The multipart instance with contents to extract.
- * @param mimeType The mimeType to match against the multipart.
- *
- * @return The contents from the multipart that match the mimeType.
- *
- * @throws MessagingException Failed to extract the content.
- */
- private String extractMultipart( Multipart multipart, String mimeType )
- throws MessagingException {
- String result = "";
- int count = multipart.getCount();
-
- for( int i = 0; i < count; i++ ) {
- BodyPart bodyPart = multipart.getBodyPart( i );
- Object content = exhumeBodyPart( bodyPart );
-
- if( content instanceof Multipart ) {
- result += extractMultipart( (Multipart)content, mimeType );
- } else if( bodyPart.isMimeType( mimeType ) ) {
- result += "\n" + content.toString();
- }
- }
-
- return result;
- }
-
- /**
- * Returns the body part content.
- *
- * @param bodyPart The body part containing content to retrieve.
- *
- * @return The body part's contents.
- *
- * @throws MessagingException Error extracting the body part contents.
- */
- private Object exhumeBodyPart( BodyPart bodyPart )
- throws MessagingException {
- try {
- return bodyPart.getContent();
- } catch( IOException e ) {
- throw new MessagingException( "Error opening body part contents.", e );
- }
- }
-
- /**
- * Writes the given URL-encoded parameters to the given connection.
- *
- * @param urlParameters The URL-encoded parameters to write.
- * @param connection The connection that can be written to.
- *
- * @throws MessagingException Error writing the parameters to the given
- * connection.
- */
- protected void write( String urlParameters, HttpURLConnection connection )
- throws MessagingException {
- try {
- write( urlParameters, connection.getOutputStream() );
-
- int response = connection.getResponseCode();
-
- // Ensure a 200 response code is returned.
- if( response != HttpURLConnection.HTTP_OK ) {
- throw new MessagingException( "Unexpected response code: " + response );
- }
- } catch( IOException e ) {
- throw new MessagingException( "Could not stream output connection.", e );
- }
- }
-
- /**
- * Writes a set of encoded URL parameters to the given stream.
- *
- * @param urlParameters The parameters to send.
- * @param outputStream The stream to receive the parameters.
- *
- * @throws MessagingException Message could not be sent.
- */
- protected void write( String urlParameters, OutputStream outputStream )
- throws MessagingException {
- try( OutputStreamWriter writer = new OutputStreamWriter( outputStream ); ) {
- writer.write( urlParameters );
- writer.flush();
- } catch( IOException e ) {
- throw new MessagingException( "Could not send message.", e );
- }
- }
-
- /**
- * Reads the response code returned from a previous call to write. This must
- * be called after write, not before.
- *
- * @param connection The connection that had data written to it.
- *
- * @return A non-null, possibly empty string.
- *
- * @throws MessagingException Response could not be read.
- */
- protected String read( URLConnection connection ) throws MessagingException {
- try {
- return read( new InputStreamReader( connection.getInputStream() ) );
- } catch( IOException e ) {
- throw new MessagingException( "Could not stream input connection.", e );
- }
- }
-
- /**
- * Helper method.
- *
- * @param in The stream from a connection that had data written to it.
- *
- * @return A non-null, possibly empty string.
- *
- * @throws MessagingException Response could not be read.
- */
- protected String read( InputStreamReader in ) throws MessagingException {
- try( BufferedReader rd = new BufferedReader( in ) ) {
- return rd.readLine();
- } catch( IOException e ) {
- throw new MessagingException( "Could not read status.", e );
- }
- }
-
- /**
- * Connects to the REST API over HTTP.
- *
- * @return An opened URLConnection instance.
- *
- * @throws javax.mail.MessagingException The REST API is unavailable.
- */
- protected HttpURLConnection open() throws MessagingException {
- HttpURLConnection connection = openConnection();
- connection.setDoOutput( true );
-
- return connection;
- }
-
- /**
- * Helper method to return an opened URL connection.
- *
- * @return An opened URLConnection instance.
- *
- * @throws javax.mail.MessagingException Error connecting to the provider.
- */
- public HttpURLConnection openConnection() throws MessagingException {
- try {
- return (HttpURLConnection)getURL().openConnection();
- } catch( IOException e ) {
- throw new MessagingException( "Could not connect to provider.", e );
- }
- }
-
- /**
- * Helper method to return the REST API URL for sending messages.
- *
- * @return An HTTP(S) URL, unopened.
- *
- * @return @throws javax.mail.MessagingException
- */
- private URL getURL() {
- try {
- return new URL( getRestApiUrl() );
- } catch( MalformedURLException e ) {
- throw new RuntimeException( "Provider URL not set.", e );
- }
- }
-
- /**
- * Returns the URLName by first creating a URL using the REST API URL.
- *
- * @return A non-null URLName.
- */
- @Override
- public URLName getURLName() {
- return new URLName( getURL() );
- }
-
- /**
- * Returns the path .
+import javax.mail.Address;
+import javax.mail.BodyPart;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.PasswordAuthentication;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.URLName;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMultipart;
+
+/**
+ * Responsible for sending messages over HTTP. Subclasses are responsible for
+ * providing the sendMessage method implementation.
+ *
+ * @author White Magic Software, Ltd.
+ */
+public abstract class HttpTransport extends Transport {
+
+ public final static String MIME_TYPE_PLAIN = "text/plain";
+ public final static String MIME_TYPE_MULTIPART = "multipart/*";
+ public final static String MIME_TYPE_HTML = "text/html";
+
+ /**
+ * Constructs a new HttpTransport capable of sending notifications via a
+ * RESTFUL API.
+ *
+ * @param session Session state.
+ * @param urlname Set value to null for HTTP.
+ */
+ public HttpTransport( Session session, URLName urlname ) {
+ // This should set the protected instance variables of "this.session"
+ // and "this.urlname".
+ super( session, urlname );
+ }
+
+ /**
+ * Sets the credentials to use for permission to send messages.
+ *
+ * @param username The username authorised to send messages over HTTP.
+ * @param password The password (or API key) associated with the username.
+ */
+ public void setAuthentication( String username, String password ) {
+ getSession().setPasswordAuthentication(
+ getURLName(),
+ new PasswordAuthentication( username, password )
+ );
+ }
+
+ /**
+ * Sends the given data over the wire.
+ *
+ * @param data The URL-encoded parameters to send.
+ *
+ * @throws javax.mail.MessagingException
+ */
+ protected void send( String data ) throws MessagingException {
+ HttpURLConnection connection = open();
+
+ write( data, connection );
+ String response = read( connection );
+ }
+
+ /**
+ * Convenience method to help create a message with text and HTML body parts.
+ *
+ * @param text The message's text body part.
+ * @param html The message's HTML body part.
+ *
+ * @return A Multipart instance that wraps the text and HTML.
+ *
+ * @throws MessagingException
+ */
+ public Multipart multipart( String text, String html )
+ throws MessagingException {
+ Multipart multipart = new MimeMultipart( "alternative" );
+
+ multipart.addBodyPart( textBodyPart( text ) );
+ multipart.addBodyPart( htmlBodyPart( html ) );
+
+ return multipart;
+ }
+
+ /**
+ * Helper method to create a new text body part.
+ *
+ * @param text The text body part to create.
+ *
+ * @return The text wrapped in a body part.
+ *
+ * @throws MessagingException
+ */
+ protected BodyPart textBodyPart( String text )
+ throws MessagingException {
+ return bodyPart( text, MIME_TYPE_PLAIN );
+ }
+
+ /**
+ * Helper method to create a new HTML body part.
+ *
+ * @param html The HTML body part to create.
+ *
+ * @return The HTML wrapped in a body part.
+ *
+ * @throws MessagingException
+ */
+ protected BodyPart htmlBodyPart( String html )
+ throws MessagingException {
+ return bodyPart( html, MIME_TYPE_HTML );
+ }
+
+ /**
+ * Create a new body part with the given content and MIME type.
+ *
+ * @param content The content to wrap in a MimeBodyPart.
+ * @param mimeType The content's MIME type (text or HTML).
+ *
+ * @return A body part that wraps the content.
+ *
+ * @throws MessagingException
+ */
+ protected BodyPart bodyPart( String content, String mimeType )
+ throws MessagingException {
+ MimeBodyPart part = new MimeBodyPart();
+ part.setContent( content, mimeType );
+
+ return part;
+ }
+
+ /**
+ * Returns the default encoding to use for converting plain text into safe URL
+ * parameters.
+ *
+ * @return StandardCharsets.UTF_8 by default.
+ */
+ protected Charset getDefaultCharset() {
+ return StandardCharsets.UTF_8;
+ }
+
+ /**
+ * Returns the given text string encoded for passing as a URL parameter.
+ *
+ * @param text The text to encode.
+ *
+ * @return The encoded text.
+ *
+ * @throws MessagingException The text could not be encoded.
+ */
+ protected String encode( final String text ) throws MessagingException {
+ String charset = getDefaultCharset().displayName();
+
+ try {
+ return URLEncoder.encode( text, charset );
+ } catch( UnsupportedEncodingException e ) {
+ throw new MessagingException(
+ "Invalid default encoding: '" + charset + "'", e );
+ }
+ }
+
+ /**
+ * Helper method to return a URL-encoded string.
+ *
+ * @param text Text to encode.
+ *
+ * @return The StringBuilder's text, encoded to be URL-friendly.
+ *
+ * @throws MessagingException
+ */
+ protected String encode( final StringBuilder text )
+ throws MessagingException {
+ return encode( text.toString() );
+ }
+
+ /**
+ * Answers whether the string contains any characters.
+ *
+ * @param string Can be null or empty.
+ *
+ * @return true The string is empty or zero length or contains only
+ * whitespace.
+ */
+ private boolean isEmpty( final String string ) {
+ return string == null || string.trim().length() == 0;
+ }
+
+ /**
+ *
+ * @param message Message that contains content to extract.
+ *
+ * @return The text and HTML portions of the message in array index 0 and 1,
+ * respectively.
+ *
+ * @throws javax.mail.MessagingException Message body not extracted.
+ */
+ protected String[] extractMessageContents( Message message )
+ throws MessagingException {
+ String result[] = new String[]{ "", "" };
+
+ try {
+ // Ensure the mime types are applied.
+ //
+ // See also: http://stackoverflow.com/a/5031057/59087
+ message.saveChanges();
+ Object content = message.getContent();
+
+ if( content instanceof Multipart ) {
+ Multipart multipart = (Multipart)content;
+
+ result[ 0 ] = extractMultipart( multipart, MIME_TYPE_PLAIN );
+ result[ 1 ] = extractMultipart( multipart, MIME_TYPE_HTML );
+ } else if( message.isMimeType( MIME_TYPE_PLAIN ) ) {
+ result[ 0 ] = content.toString();
+ }
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not extract message content.", e );
+ }
+
+ return result;
+ }
+
+ /**
+ * Extracts the content from the multipart instance that matches the given
+ * mimeType.
+ *
+ * @param multipart The multipart instance with contents to extract.
+ * @param mimeType The mimeType to match against the multipart.
+ *
+ * @return The contents from the multipart that match the mimeType.
+ *
+ * @throws MessagingException Failed to extract the content.
+ */
+ private String extractMultipart( Multipart multipart, String mimeType )
+ throws MessagingException {
+ String result = "";
+ int count = multipart.getCount();
+
+ for( int i = 0; i < count; i++ ) {
+ BodyPart bodyPart = multipart.getBodyPart( i );
+ Object content = exhumeBodyPart( bodyPart );
+
+ if( content instanceof Multipart ) {
+ result += extractMultipart( (Multipart)content, mimeType );
+ } else if( bodyPart.isMimeType( mimeType ) ) {
+ result += "\n" + content.toString();
+ }
+ }
+
+ return result;
+ }
+
+ /**
+ * Returns the body part content.
+ *
+ * @param bodyPart The body part containing content to retrieve.
+ *
+ * @return The body part's contents.
+ *
+ * @throws MessagingException Error extracting the body part contents.
+ */
+ private Object exhumeBodyPart( BodyPart bodyPart )
+ throws MessagingException {
+ try {
+ return bodyPart.getContent();
+ } catch( IOException e ) {
+ throw new MessagingException( "Error opening body part contents.", e );
+ }
+ }
+
+ /**
+ * Writes the given URL-encoded parameters to the given connection.
+ *
+ * @param urlParameters The URL-encoded parameters to write.
+ * @param connection The connection that can be written to.
+ *
+ * @throws MessagingException Error writing the parameters to the given
+ * connection.
+ */
+ protected void write( String urlParameters, HttpURLConnection connection )
+ throws MessagingException {
+ try {
+ write( urlParameters, connection.getOutputStream() );
+
+ int response = connection.getResponseCode();
+
+ // Ensure a 200 response code is returned.
+ if( response != HttpURLConnection.HTTP_OK ) {
+ throw new MessagingException( "Unexpected response code: " + response );
+ }
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not stream output connection.", e );
+ }
+ }
+
+ /**
+ * Writes a set of encoded URL parameters to the given stream.
+ *
+ * @param urlParameters The parameters to send.
+ * @param outputStream The stream to receive the parameters.
+ *
+ * @throws MessagingException Message could not be sent.
+ */
+ protected void write( String urlParameters, OutputStream outputStream )
+ throws MessagingException {
+ try( OutputStreamWriter writer = new OutputStreamWriter( outputStream ); ) {
+ writer.write( urlParameters );
+ writer.flush();
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not send message.", e );
+ }
+ }
+
+ /**
+ * Reads the response code returned from a previous call to write. This must
+ * be called after write, not before.
+ *
+ * @param connection The connection that had data written to it.
+ *
+ * @return A non-null, possibly empty string.
+ *
+ * @throws MessagingException Response could not be read.
+ */
+ protected String read( URLConnection connection ) throws MessagingException {
+ try {
+ return read( new InputStreamReader( connection.getInputStream() ) );
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not stream input connection.", e );
+ }
+ }
+
+ /**
+ * Helper method.
+ *
+ * @param in The stream from a connection that had data written to it.
+ *
+ * @return A non-null, possibly empty string.
+ *
+ * @throws MessagingException Response could not be read.
+ */
+ protected String read( InputStreamReader in ) throws MessagingException {
+ try( BufferedReader rd = new BufferedReader( in ) ) {
+ return rd.readLine();
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not read status.", e );
+ }
+ }
+
+ /**
+ * Connects to the REST API over HTTP.
+ *
+ * @return An opened URLConnection instance.
+ *
+ * @throws javax.mail.MessagingException The REST API is unavailable.
+ */
+ protected HttpURLConnection open() throws MessagingException {
+ HttpURLConnection connection = openConnection();
+ connection.setDoOutput( true );
+
+ return connection;
+ }
+
+ /**
+ * Helper method to return an opened URL connection.
+ *
+ * @return An opened URLConnection instance.
+ *
+ * @throws javax.mail.MessagingException Error connecting to the provider.
+ */
+ public HttpURLConnection openConnection() throws MessagingException {
+ try {
+ return (HttpURLConnection)getURL().openConnection();
+ } catch( IOException e ) {
+ throw new MessagingException( "Could not connect to provider.", e );
+ }
+ }
+
+ /**
+ * Helper method to return the REST API URL for sending messages.
+ *
+ * @return An HTTP(S) URL, unopened.
+ *
+ * @return @throws javax.mail.MessagingException
+ */
+ private URL getURL() {
+ try {
+ return new URL( getRestApiUrl() );
+ } catch( MalformedURLException e ) {
+ throw new RuntimeException( "Provider URL not set.", e );
+ }
+ }
+
+ /**
+ * Returns the URLName by first creating a URL using the REST API URL.
+ *
+ * @return A non-null URLName.
+ */
+ @Override
+ public URLName getURLName() {
+ return new URLName( getURL() );
+ }
+
+ /**
+ * Returns the fully qualified REST API URL, including host and path. The
+ * default port (e.g., https/443 or http/80) should be sufficient for most
+ * scenarios.
*
* @return A non-null path to the mailer's REST API.

Fixed comments

Author djarvis <email>
Date 2016-06-04 20:25:55 GMT-0700
Commit 5bb048d95b2d93563bd32668187f0ea803122992
Parent dd73bcc
Delta 407 lines added, 408 lines removed, 1-line decrease