Permalink
Browse files

Doing parsing an method injection.

  • Loading branch information...
1 parent 370dab8 commit d1a3e4c8bcce5ba08a438b7a68afd77db5185aaa jmartin committed Dec 21, 2012
@@ -1,25 +1,29 @@
+import org.apache.commons.logging.LogFactory
+
class SimplexMailGrailsPlugin {
+ private static final log = LogFactory.getLog("es.osoco.simplexmail")
+
// the plugin version
- def version = "0.1"
+ def version = "0.1-SNAPSHOT"
// the version or versions of Grails the plugin is designed for
def grailsVersion = "2.0 > *"
// the other plugins this plugin depends on
- def dependsOn = [:]
- //def loadBefore = ['asynchronous-mail']
+ //def dependsOn = ['asynchronous-mail' : "0.7>*"]
+ //def loadBefore = ['asynchronous-mail']
//def loadAfter = ['asynchronous-mail']
// resources that are excluded from plugin packaging
def pluginExcludes = [
"grails-app/views/error.gsp"
]
-
+
// TODO Fill in these fields
def title = "Grails Simplex Mail Plugin Plugin" // Headline display name of the plugin
def author = "Your name"
def authorEmail = ""
def description = '''\
-Brief summary/description of the plugin.
-'''
-
+ Simplex mail plugin provides a service for do a very simple mail definition
+ '''
+ def simplexMailService
// URL to the plugin's documentation
def documentation = "http://grails.org/plugin/grails-simplex-mail-plugin"
@@ -49,7 +53,7 @@ Brief summary/description of the plugin.
}
def doWithDynamicMethods = { ctx ->
- // TODO Implement registering dynamic methods to classes (optional)
+ reloadMailConfig(ctx)
}
def doWithApplicationContext = { applicationContext ->
@@ -60,15 +64,32 @@ Brief summary/description of the plugin.
// TODO Implement code that is executed when any artefact that this plugin is
// watching is modified and reloaded. The event contains: event.source,
// event.application, event.manager, event.ctx, and event.plugin.
- println "onChange for event $event"
- }
+ reloadMailConfig(event.ctx)
+ }
def onConfigChange = { event ->
// TODO Implement code that is executed when the project configuration changes.
// The event is the same as for 'onChange'.
+ reloadMailConfig(event.ctx)
}
def onShutdown = { event ->
// TODO Implement code that is executed when the application shuts down (optional)
}
+
+ def getWatchedResources() {
+ def watchedPaths = [grailsApplication.config.simplex.mail.config.files.paths].flatten()
+ def watchedFiles = watchedPaths.collect { "file:./${it}"}
+ log.info "The files for search changes for reload simplex mail service are $watchedFiles"
+ return watchedFiles
+ }
+
+ private reloadMailConfig(ctx) {
+ ctx.simplexMailLoaderService.loadMailConfig()
+ }
+
+ private getGrailsApplication() {
+ org.codehaus.groovy.grails.commons.ApplicationHolder.application
+ }
+
}
View
@@ -1,9 +1,6 @@
#Grails Metadata file
-#Fri Nov 30 14:02:21 CET 2012
+#Wed Dec 19 11:56:31 CET 2012
app.grails.version=2.1.1
app.name=simplex-mail
-plugins.asynchronous-mail=0.7
plugins.console=1.2
plugins.hibernate=2.1.1
-plugins.mail=1.0.1
-plugins.quartz2=0.2.3
@@ -1,27 +1 @@
-// configuration for plugin testing - will not be included in the plugin zip
-
-log4j = {
- // Example of changing the log pattern for the default console
- // appender:
- //
- //appenders {
- // console name:'stdout', layout:pattern(conversionPattern: '%c{2} %m%n')
- //}
-
- error 'org.codehaus.groovy.grails.web.servlet', // controllers
- 'org.codehaus.groovy.grails.web.pages', // GSP
- 'org.codehaus.groovy.grails.web.sitemesh', // layouts
- 'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
- 'org.codehaus.groovy.grails.web.mapping', // URL mapping
- 'org.codehaus.groovy.grails.commons', // core / classloading
- 'org.codehaus.groovy.grails.plugins', // plugins
- 'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
- 'org.springframework',
- 'org.hibernate',
- 'net.sf.ehcache.hibernate'
-
- warn 'org.mortbay.log'
-}
-
-
-simplex.mail.config.files.paths = 'grails-app/conf/MailConfig.groovy'
+
@@ -1,16 +1,20 @@
package es.osoco.simplexmail
import org.codehaus.groovy.control.CompilerConfiguration
+
+import es.osoco.simplexmail.exceptions.CircularInheritanceException
+import org.apache.commons.logging.LogFactory
import static es.osoco.simplexmail.MailPropertyType.*
class SimplexMailLoaderService {
-
- final String MAIL_METHOD_NAME = "methodName"
+ private static final log = LogFactory.getLog("es.osoco.simplexmail")
+
+ static final String MAIL_METHOD_NAME = "methodName"
static transactional = false
def grailsApplication
public loadMailConfig() {
- println ('Loading simplex-mail-config from file' +
+ log.info ('Loading simplex-mail-config from file' +
"${getResourceByPath(grailsApplication.config.simplex.mail.config.files.paths)}")
[grailsApplication.config.simplex.mail.config.files.paths].flatten().each { configFilePath ->
@@ -35,7 +39,9 @@ class SimplexMailLoaderService {
private injectMailSendingMethods(mailConfig) {
mailConfig.each { mail, props ->
def methodName = "send${mail.capitalize()}".toString()
- println "Injecting mail method $methodName with props $props"
+
+ log.info "Injecting mail method $methodName with props $props"
+
props[MAIL_METHOD_NAME] = methodName
SimplexMailService.metaClass."$methodName" = { Map overwrittenProps = [:] ->
@@ -76,13 +82,15 @@ class SimplexMailLoaderService {
throw new CircularInheritanceException(stack)
}
else {
- mailProps << call(mailConfig[inherits], stack << inherits)
+ call(mailConfig[inherits], stack << inherits).each {
+ property, value ->
+ if (!mailProps.containsKey(property)) {
+ mailProps[property] = value
+ }
+ }
}
}
- else
- {
- mailProps
- }
+ return mailProps
}
mailConfig.each { mailName, mailProps -> resolve(mailProps, [mailName]) }
mailConfig
@@ -1,104 +1,108 @@
package es.osoco.simplexmail
+
+import javax.activation.MimetypesFileTypeMap
import org.codehaus.groovy.control.CompilerConfiguration
+import es.osoco.simplexmail.exceptions.InvalidAttachmentException
+import es.osoco.simplexmail.exceptions.InvalidMailPropertyValueException
+import org.apache.commons.logging.LogFactory
import static es.osoco.simplexmail.MailPropertyType.*
class SimplexMailService {
-
- def transactional = false
- def asynchronousMailService
+ private static final log = LogFactory.getLog("es.osoco.simplexmail")
+
+ def asynchronousMailService
def grailsApplication
-
- public loadMailConfig() {
- println grailsApplication
- println getResourceByPath(grailsApplication.config.simplex.mail.config.files.paths)
-
- [grailsApplication.config.simplex.mail.config.files.paths].flatten().each { configFilePath ->
- injectMailSendingMethods(
- postProcessMailConfig(
- buildGroovyShell().evaluate(getResourceByPath(configFilePath)?.text)
- )
- )
- }
- }
-
- public sendEmail(emailProperties) {
- println "INVOKED $emailProperties"
- /*
- asynchronousMailService.sendAsynchronousMail {
- emailProperties.each { type, values -> with(types.configure(values) }
- }*//*
- asynchronousMailService.sendAsynchronousMail {
- to toEmail
- from fromEmail
- cc ccEmails
- bcc bccEmails
- replyTo replyToEmail
- subject emailSubject
- html emailBody
- attachments?.each {
- attachment ->
- attachBytes attachment.name, attachment.mimeType, attachment.content
- }
- }*/
- }
-
- private buildGroovyShell() {
- new GroovyShell(
- this.class.classLoader, new Binding(grailsApplication.config.toProperties()),
- new CompilerConfiguration().with { compilerConfig ->
- scriptBaseClass = SimplexMailBaseScript.class.name
- compilerConfig
- }
- )
- }
-
- private injectMailSendingMethods(mailConfig) {
- mailConfig.each { mail, props ->
- this.metaClass."send${mail.capitalize()}" = { Map overwrittenProps = [:] ->
- def effectiveProps = props + overwrittenProps
- println "Sending email $mail with props $effectiveProps"
- sendEmail(effectiveProps)
- }
- }
- }
-
- private getResourceByPath(path)
- {
- new File(new grails.util.BuildSettings().baseDir.path + "/" + path)
- }
-
- private postProcessMailConfig(mailConfig)
- {
- resolveAttachments(resolveInherits(mailConfig))
- }
-
- private resolveAttachments(mailConfig)
- {
- mailConfig.each { mailName, mailProps ->
- mailProps[ATTACHMENTS] = mailProps[ATTACHMENTS]?.collect { getResourceByPath(it) }
- }
- mailConfig
- }
+ def messageSource
+ def groovyPageRenderer
+
+ private sendEmail(emailProperties) {
+ calculateEmailInternacionalizedProperties(emailProperties)
+ checkPropertiesForErrors(emailProperties)
+
+ log.info( "Sending email from '${emailProperties[FROM]}'" +
+ "to ${anonymizesEmailTo(emailProperties[TO])}" +
+ "subject '${emailProperties[SUBJECT]}'" +
+ "and bcc '${emailProperties[BCC]}'" +
+ "${emailProperties[ATTACHMENTS] ?: 'not attached data'}" +
+ "locale ${emailProperties[LOCALE]}")
+
+ resolveaAttachments(emailProperties)
+
+ asynchronousMailService.sendMail {
+ multipart true
+ emailProperties.each { type, values ->
+ if(type instanceof MailPropertyType) {
+ if(type == MailPropertyType.ATTACHMENTS) {
+ values.each {
+ attachment ->
+ owner.delegate.attachBytes attachment.name , attachment.mimeType , attachment.content
+ }
+ } else {
+ delegate."$type.name"(values)
+ }
+ }
+ }
+ }
+ }
+
+ private def anonymizesEmailTo(def to)
+ {
+ if (to instanceof String) {
+ return to.substring(0,4).concat("****")
+ } else {
+ return to.collect { it.substring(0,4).concat("****") }
+ }
+ }
+
+ private calculateEmailInternacionalizedProperties(emailProperties) {
+ if(!emailProperties[LOCALE]) {
+ emailProperties[LOCALE] = new Locale(grailsApplication.config.simplex.mail.language.default.isoCode)
+ }
+ def mailLocale = emailProperties[LOCALE]
+
+ emailProperties[SUBJECT] = messageSource.getMessage(emailProperties[SUBJECT], null, mailLocale )
+
+ emailProperties[HTML] = groovyPageRenderer.render(view: emailProperties[HTML] ,
+ model: (emailProperties.model?:[:] << [locale:mailLocale] ) )
+ }
+
+ private checkPropertiesForErrors(emailProperties) {
+ MailPropertyType.findAll().each {
+ propertyType ->
+ if(!propertyType.validate(emailProperties[propertyType])) {
+ throw new InvalidMailPropertyValueException(propertyType,emailProperties[propertyType],
+ emailProperties[SimplexMailLoaderService.MAIL_METHOD_NAME])
+ }
+ }
+ }
+
+ private resolveaAttachments(emailProperties) {
+ if(emailProperties[ATTACHMENTS]) {
+ emailProperties[ATTACHMENTS] = generateAttachments(emailProperties[ATTACHMENTS],
+ emailProperties[SimplexMailLoaderService.MAIL_METHOD_NAME])
+ }
+ }
+
+ private def generateAttachments(files, methodName)
+ {
+ files.inject([]) {
+ attachments, file ->
+ if(file.exists())
+ {
+ def attachment = [
+ name: file.getName(),
+ mimeType: new MimetypesFileTypeMap().getContentType(file),
+ content: file.getBytes()
+ ]
+ attachments.add(attachment)
+ }
+ else
+ {
+ throw new InvalidAttachmentException(file, methodName)
+ }
+ return attachments
+ }
+
+ }
- private resolveInherits(mailConfig)
- {
- def resolve = { mailProps, stack ->
- def inherits = mailProps.remove(INHERITS)?.getAt(0)
- if (inherits)
- {
- if (inherits in stack) {
- throw new CircularInheritanceException(stack)
- }
- else {
- mailProps << call(mailConfig[inherits], stack << inherits)
- }
- }
- else
- {
- mailProps
- }
- }
- mailConfig.each { mailName, mailProps -> resolve(mailProps, [mailName]) }
- mailConfig
- }
}
@@ -1,12 +0,0 @@
-package es.osoco.simplexmail
-
-import sun.tools.tree.ThisExpression;
-
-class CircularInheritanceException extends Exception {
-
- public CircularInheritanceException(stack)
- {
- super("Found a circular inheritance: " + stack.join(' -> '))
- }
-
-}
Oops, something went wrong.

0 comments on commit d1a3e4c

Please sign in to comment.