JavaMail SMTPAddressFailedException: 550 5.7.1 Unable to relay for ... (Grails) - grails

I am trying to send mail using javamail from my Grails application (via a service).
Both the from and to addresses being used have the organization domain names.
The same code, when run via command line as a groovy script (on the same server) works as expected.
However, running on the grails server (under war mode) produces the following exception :
javax.mail.SendFailedException: Invalid Addresses;
nested exception is:
com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay for ---#---.com
at com.sun.mail.smtp.SMTPTransport.rcptTo(SMTPTransport.java:1873)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at javax.mail.Transport$send.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at cs.MailService.mail(MailService.groovy:66)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at
The code is written as follows :
import javax.mail.internet.*
import javax.mail.*
import javax.activation.*
class Mailer {
def static mail(String toAddress, String subject, String body) {
println "mail called"
println "${toAddress}, ${subject}, ${body}"
try {
def fromAddress = "---#---.com"
def properties = new Properties()
properties.setProperty("mail.transport.protocol","smtp")
properties.setProperty("mail.smtp.host","---------")
def sessionInstance = Session.getDefaultInstance(properties,null);
def msg = new MimeMessage(sessionInstance)
def stringTokenizer = new StringTokenizer(toAddress,";")
def toAddressList = []
while(stringTokenizer.hasMoreElements()){
toAddressList.add(new InternetAddress(stringTokenizer.nextElement().toString()));
}
def to = new InternetAddress[toAddressList.size()]
to = (InternetAddress[]) toAddressList.toArray(to)
msg.setRecipients(MimeMessage.RecipientType.TO,to)
def from = new InternetAddress(fromAddress)
msg.setFrom(from);
msg.setSubject(subject)
def mimeMultipart = new MimeMultipart()
def mimeBodyPart = new MimeBodyPart()
mimeBodyPart.setContent("<p style='font-family:calibri;color:blue;font-size:20px;text-align:center;'>"+body+"</p>", "text/html")
mimeMultipart.addBodyPart(mimeBodyPart)
msg.setContent(mimeMultipart)
def transporter = sessionInstance.getTransport("smtp")
transporter.connect()
transporter.send(msg)
} catch(Exception e) {
e.printStackTrace()
}
}
public static void main(String[] args) {
def to="---#---.com"
def subject="Call Scheduler Notification"
def body='<font face="Segoe UI"><p><b><font color="#6B0667">Hi --- ---,<br><br>Your Call (id: 1281) Was Updated Successfully</b></font></p><table cellpadding="10" bgcolor="#B799B6"><caption><b><font color="#6B0667">Call Details</font></b></caption><tr><td><b>Title</b></td><td>---------</td></tr><tr><td><b>Start</b></td><td>---------</td></tr><tr><td><b>End</b></td><td>---------</td></tr><tr><td><b>Number</b></td><td>---------</td></tr><tr><td><b>Passcode</b></td><td>---------</td></tr><td><b>Special Instructions</b></td><td></td></tr><td><b>Callback Number</b></td><td>---------</td></tr></table><br><p><b><font color="#6B0667">Regards<br>Call Scheduler</b></font></p></font>'
mail(to, subject, body);
}
}
How do i get past this error ?
Update : Still not entirely sure what was wrong here. But resetting all the tcp/ip connections (from the mail server) resolved the issue.

You probably need to authenticate.
I don't know why it works from the command line.

Related

Initialize Audit Trial Plugin in Jenkins using Groovy

My approach:
import hudson.plugins.audit_trail.AuditTrailPlugin
import hudson.plugins.jobConfigHistory.JobConfigHistory
import net.sf.json.JSONObject
def auditTrialPlugin = Jenkins.getInstance().getPlugin(AuditTrailPlugin.class)
// println(auditTrialPlugin.getConfigXml().asString())
println("Going to configure...")
def logger = new JSONObject()
logger.put("log", "Vibin")
logger.put("limit", "1")
logger.put("count", "2")
logger.put("stapler-class", "hudson.plugins.audit_trail.LogFileAuditLogger")
logger.put("\$class", "hudson.plugins.audit_trail.LogFileAuditLogger")
def plugin = new JSONObject()
plugin.put("name", "audit-trail")
plugin.put("pattern", "")
plugin.put("logBuildCause", true)
plugin.put("loggers", logger)
auditTrialPlugin.configure(null, plugin)
Error happening:
java.lang.NoSuchMethodException: hudson.plugins.audit_trail.LogFileAuditLogger.<init>()
at java.lang.Class.getConstructor0(Class.java:3082)
at java.lang.Class.newInstance(Class.java:412)
Caused: java.lang.InstantiationException: hudson.plugins.audit_trail.LogFileAuditLogger
at java.lang.Class.newInstance(Class.java:427)
at hudson.model.Descriptor.newInstance(Descriptor.java:578)
Caused: java.lang.Error: Failed to instantiate class hudson.plugins.audit_trail.LogFileAuditLogger from {"log":"Vibin","limit":"1","count":"2","stapler-class":"hudson.plugins.audit_trail.LogFileAuditLogger","$class":"hudson.plugins.audit_trail.LogFileAuditLogger"}
at hudson.model.Descriptor.newInstance(Descriptor.java:600)
at hudson.model.Descriptor.newInstancesFromHeteroList(Descriptor.java:1055)
at hudson.model.Descriptor.newInstancesFromHeteroList(Descriptor.java:1017)
at hudson.plugins.audit_trail.AuditTrailPlugin.configure(AuditTrailPlugin.java:78)
at hudson.plugins.audit_trail.AuditTrailPlugin$configure$1.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:133)
at Script1.run(Script1.groovy:24)
I tried to follow the code base of the plugin which I found on GitHub. There is a 'configure' function for the plugin which I tried to use which isn't working.
Codebase of plugin: GitHub link
Try this:
import jenkins.model.*;
import hudson.plugins.audit_trail.AuditTrailPlugin;
import hudson.plugins.audit_trail.LogFileAuditLogger;
def log = "Vibin"
def limit = 1
def count = 2
LogFileAuditLogger logFileAuditLogger = new LogFileAuditLogger(log, limit, count)
Jenkins j = Jenkins.getInstance();
AuditTrailPlugin plugin = j.getPlugin(AuditTrailPlugin.class);
plugin.loggers.clear()
plugin.loggers.add(logFileAuditLogger)
plugin.pattern = "" // empty pattern?
plugin.save()
plugin.start()
I think using LogFileAuditLogger class is more clear than 'configure' function.

Sending email via JWebServices for Exchange and JAVA

import com.independentsoft.exchange.Body;
import com.independentsoft.exchange.ItemInfoResponse;
import com.independentsoft.exchange.Mailbox;
import com.independentsoft.exchange.Message;
import com.independentsoft.exchange.Service;
import com.independentsoft.exchange.ServiceException;
public class Example {
public static void main(String[] args)
{
try
{
Service service = new Service("https://myserver/ews/Exchange.asmx", "user", "password");
Message message = new Message();
message.setSubject("Test");
message.setBody(new Body("Body text"));
message.getToRecipients().add(new Mailbox("John#mydomain.com"));
message.getCcRecipients().add(new Mailbox("Mark#mydomain.com"));
ItemInfoResponse response = service.send(message);
}
catch (ServiceException e)
{
System.out.println(e.getMessage());
System.out.println(e.getXmlMessage());
e.printStackTrace();
}
}
}
Hello! I tried to send an email, but did not work.
I'ved used a valid user and password, at message.getToRecipients I used my yahoo email address.
At output on eclipse this is my result. Where is my mistake ?
JWebServices for Exchange 2.0 evaluation version, www.independentsoft.com.
myserver
null
myserver
at com.independentsoft.exchange.Service.createItemImplementation(Unknown Source)
at com.independentsoft.exchange.Service.send(Unknown Source)
at com.independentsoft.exchange.Service.send(Unknown Source)
at com.independentsoft.exchange.Service.send(Unknown Source)
at com.independentsoft.exchange.Service.send(Unknown Source)
at Example.main(Example.java:26)
Caused by: java.net.UnknownHostException: myserver
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(InetAddress.java:901)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1293)
at java.net.InetAddress.getAllByName0(InetAddress.java:1246)
at java.net.InetAddress.getAllByName(InetAddress.java:1162)
at java.net.InetAddress.getAllByName(InetAddress.java:1098)
at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:44)
at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:101)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:318)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
at com.independentsoft.exchange.Service.a(Unknown Source)
... 6 more
Replace "myserver" with real name of your Exchange server.
try to AutoDiscover your service url first:
Sample here

Expired activiti jobs throwing exception while server startup - Grails

This is with regard to activiti workflow timer jobs in grails application.
While starting the grails app with expired jobs, exception is thrown for normal grails features such as log and methods of domain classes.
For eg:
Caused by: groovy.lang.MissingPropertyException: No such property: log for class: com.service.common.UtilityService
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:49)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassGetPropertySite.getProperty(PogoMetaClassGetPropertySite.java:50)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGroovyObjectGetProperty(AbstractCallSite.java:239)
at com.service.common.UtilityService.insertToQueue(UtilityService.groovy:370)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.activiti.engine.impl.javax.el.BeanELResolver.invoke(BeanELResolver.java:479)
... 71 more
This happens in dev environment running the app from Spring STS. We are using activiti plugin 5.8.2 for grails (1.3.6)
After the web-app is started up completely, the jobs (schedule to a time after startup) run properly and no missing property exception is thrown.
Even though we can fix the of missing property issue for log by using private static final log = LogFactory.getLog(this) instead, then any reference to domain classes throw an error, like using get or find method.
eg:
Caused by: groovy.lang.MissingMethodException: No signature of method: static com.domain.wr.WorkRequest.read() is applicable for argument types: (java.lang.String) values: [44700]
Possible solutions: getId(), getAt(java.lang.String), setId(java.lang.Long), grep(java.lang.Object), each(groovy.lang.Closure), find(groovy.lang.Closure)
at groovy.lang.MetaClassImpl.invokeStaticMissingMethod(MetaClassImpl.java:1357)
at groovy.lang.MetaClassImpl.invokeStaticMethod(MetaClassImpl.java:1343)
at groovy.lang.ExpandoMetaClass.invokeStaticMethod(ExpandoMetaClass.java:1082)
at org.codehaus.groovy.runtime.callsite.StaticMetaClassSite.call(StaticMetaClassSite.java:50)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:40)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:124)
at com.service.common.UtilityService.insertToQueue(UtilityService.groovy:373)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.activiti.engine.impl.javax.el.BeanELResolver.invoke(BeanELResolver.java:479)
... 71 more
Activiti Configuration
Config.groovy
// Added by the Grails Activiti plugin:
activiti {
processEngineName = "activiti-engine-default"
databaseType = "oracle"
deploymentName = appName
history = "audit" // "none", "activity", "audit" or "full"
sessionUsernameKey = "username"
useFormKey = true
deploymentResources = ["classpath:activiti/escalation/WorkRequest.bpmn20.xml"]
}
Config.properties
activiti.processEngineName =activiti-engine-default
activiti.databaseSchemaUpdate =true
activiti.jobExecutorActivate =true
activiti.mailServerHost = "mail1.net"
activiti.mailServerPort = 25
activiti.mailServerUsername = ""
activiti.mailServerPassword = ""
activiti.mailServerDefaultFrom = ""
This is killing my application as a downtime makes the workflow unusable with timer tasks.
I had more or less the same problem, and in our case was caused by Activiti starting jobs execution before Spring injection being finished. That's why it only happens at startup: the job is accessing properties that are not there yet.
You can confirm that you are in the same situation by increasing the RETRIES_ in the ACT_RU_JOB table after the app has finished bootstraping and see if the jobs execute successfully.
If this is your case, I think the only option is to upgrade the plugin and if still fails, create a bug.
This issue got solved.
1) Edit Config.groovy and disable activiti during startup
activiti {
processEngineName = "activiti-engine-default"
databaseType = "oracle"
disabled = true
deploymentName = appName
sessionUsernameKey = "username"
useFormKey = true
deploymentResources = []
}
2) add the initialization of Activiti Objects in the init method of User BootStrap
def init = { servletContext ->
org.springframework.context.ApplicationContext ctx = ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
def bb = new grails.spring.BeanBuilder(ctx)
bb.beans {
//println "Activiti Process Engine Initialization..."
customDbIdGenerator(com.mycompany.activiti.customDbIdGenerator){
idBlockSize=CH.config.activiti.idBlockSize?:100
}
processEngineConfiguration(org.activiti.spring.SpringProcessEngineConfiguration) {
processEngineName = CH.config.activiti.processEngineName?:ActivitiConstants.DEFAULT_PROCESS_ENGINE_NAME
databaseType = CH.config.activiti.databaseType?:ActivitiConstants.DEFAULT_DATABASE_TYPE
databaseSchemaUpdate = CH.config.activiti.databaseSchemaUpdate ? CH.config.activiti.databaseSchemaUpdate.toString() : ActivitiConstants.DEFAULT_DATABASE_SCHEMA_UPDATE
deploymentName = CH.config.activiti.deploymentName?:ActivitiConstants.DEFAULT_DEPLOYMENT_NAME
deploymentResources = CH.config.activiti.deploymentResources?:ActivitiConstants.DEFAULT_DEPLOYMENT_RESOURCES
jobExecutorActivate = CH.config.activiti.jobExecutorActivate?:ActivitiConstants.DEFAULT_JOB_EXECUTOR_ACTIVATE
history = CH.config.activiti.history?:ActivitiConstants.DEFAULT_HISTORY
mailServerHost = CH.config.activiti.mailServerHost?:ActivitiConstants.DEFAULT_MAIL_SERVER_HOST
mailServerPort = CH.config.activiti.mailServerPort?:ActivitiConstants.DEFAULT_MAIL_SERVER_PORT
mailServerUsername = CH.config.activiti.mailServerUsername
mailServerPassword = CH.config.activiti.mailServerPassword
mailServerDefaultFrom = CH.config.activiti.mailServerDefaultFrom?:ActivitiConstants.DEFAULT_MAIL_SERVER_FROM
dataSource = ref("dataSource")
transactionManager = ref("transactionManager")
idGenerator= ref("customDbIdGenerator")
}
processEngine(org.activiti.spring.ProcessEngineFactoryBean) {
processEngineConfiguration = ref("processEngineConfiguration")
}
runtimeService(processEngine:"getRuntimeService")
repositoryService(processEngine:"getRepositoryService")
taskService(processEngine:"getTaskService")
managementService(processEngine:"getManagementService")
identityService(processEngine:"getIdentityService")
historyService(processEngine:"getHistoryService")
formService(processEngine:"getFormService")
activitiService(org.grails.activiti.ActivitiService) {
runtimeService = ref("runtimeService")
taskService = ref("taskService")
identityService = ref("identityService")
formService = ref("formService")
}
}
println "## Registering Beans ##";
bb.registerBeans(ctx);
ctx.getBean("processEngine");
println "Bean Count2 "+ctx.getBeanDefinitionCount();
}
Please note that DB Id Generator used is custom and can be replaced by the default one.

GRAILS: groovy.lang.MissingPropertyException: No such property.

I'm trying to debug a Grails application. Unfortunately, I have no prior experience in said language.
When I do grails generate-all org.example.Book, I get back a vague error:
Generating controller for domain class org.example.Book ...
groovy.lang.MissingPropertyException: No such property: Event for class: SimpleTemplateScript6
at SimpleTemplateScript6.run(SimpleTemplateScript6.groovy:22)
at _GrailsGenerate_groovy.generateForDomainClass(_GrailsGenerate_groovy:88)
at _GrailsGenerate_groovy$_run_closure1.doCall(_GrailsGenerate_groovy:48)
at GenerateAll$_run_closure1.doCall(GenerateAll.groovy:42)
at gant.Gant$_dispatch_closure5.doCall(Gant.groovy:381)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy:415)
at gant.Gant$_dispatch_closure7.doCall(Gant.groovy)
at gant.Gant.withBuildListeners(Gant.groovy:427)
at gant.Gant.this$2$withBuildListeners(Gant.groovy)
at gant.Gant$this$2$withBuildListeners.callCurrent(Unknown Source)
at gant.Gant.dispatch(Gant.groovy:415)
at gant.Gant.this$2$dispatch(Gant.groovy)
at gant.Gant.invokeMethod(Gant.groovy)
at gant.Gant.executeTargets(Gant.groovy:590)
at gant.Gant.executeTargets(Gant.groovy:589)
Error running generate-all: No such property: Event for class: SimpleTemplateScript6
After looking at the generated org.example.BookController.groovy source, I noticed that it was not fully generated (stopped at List fields = []):
package org.example
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class BookController {
...
def exportService
def export = {attrs ->
def response = attrs.response
List fields = []
This error appears to be caused by the following code in templates/scaffolding/Controller.groovy:
<%=packageName ? "package ${packageName}\n\n" : ''%>
// import needed for export plugin
import org.codehaus.groovy.grails.commons.ConfigurationHolder
class ${className}Controller {
static allowedMethods = [save: "POST", update: "POST", delete: "POST"]^M
def exportService
...
def export = {attrs ->
def response = attrs.response
List fields = []
<% excludedProps = Event.allEvents.toList() << 'version'
allowedNames = domainClass.persistentProperties*.name << 'id' << 'dateCreated' << 'lastUpdated'
props = domainClass.properties.findAll { allowedNames.contains(it.name) && !excludedProps.contains(it.name) && !Collection.isAssignableFrom(it.type) }
Collections.sort(props, comparator.constructors[0].newInstance([domainClass] as Object[]))
props.eachWithIndex {p, i -> %>fields.push("${p.name}"<%="\n"%><% } %>
Map labels = [:]
<% props.eachWithIndex { p, i -> %>labels.putAt("\${p.name}", "\${p.naturalName}")<%="\n "%><% } %>
Map formatters = [:]
Map parameters = [:]
response.setHeader("Content-disposition", "attachment; filename=${domainClass.propertyName}s.\${attrs.extension}")
if("\${attrs.extension}" == "xml") {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, [:], formatters, parameters)
} else {
exportService.export(attrs.format, response.outputStream, attrs.exportList, fields, labels, formatters, parameters)
}
}
...
}
It appears that the def export {} block seems to be causing problems. Is there something wrong with the above code?
What is the Event class? Is there an import for it?
Check your domain class for syntax errors. Make sure that in your domain class, you've included necessary packages, in your case, package org.example.

Could not open Hibernate Session for transaction

I am developing an grails application(server) to track the mobile device which are in the Wi-Fi network. The users will send a request to the webservice which is running on grails applicion(server) along with Mobileid and Wi-Fi IP address.
In my grails application i am staring multiple external java threads, each thread will be pinging the Wi-Fi IP address of each mobile device(one thread per one device to track). If any device IP is not reachable then i will update mobile status as "Disconnected" in the database from the external thread. Here only i am facing the issue, if more than one device is in not reachable then multiple threads are going to update the status of each device in the same table using domain.withTransaction method while i am getting the following exception
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is java.lang.NullPointerException
at org.springframework.orm.hibernate3.HibernateTransactionManager.doBegin(HibernateTransactionManager.java:596)
at org.codehaus.groovy.grails.orm.hibernate.GrailsHibernateTransactionManager.super$3$doBegin(GrailsHibernateTransactionManager.groovy)
at sun.reflect.GeneratedMethodAccessor492.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:88)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1058)
at groovy.lang.ExpandoMetaClass.invokeMethod(ExpandoMetaClass.java:1070)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodOnSuperN(ScriptBytecodeAdapter.java:127)
My Code:
Pinging device in thread
try {
final InetAddress inet = InetAddress.getByName(ipAddress);
boolean status = inet.isReachable(5000);
if (status) {
pool.run(MobileDeviceTracker.deviceMap.get(mobileId));
} else {
// Calling service to update the status of device as disconnected
getUserMobileService().deviceDisconnected(mobileId, ipAddress);
}
} catch (Exception e) { }
Updating Status in Database
class DisconnectionService implements UserMobileServiceInt{
static transactional = true
def void deviceDisconnected(String mobileId, String wifiIp){
try{
def mobile = Mobile.findByMobileId(mobileId)
def userMobile = UserMobile.findByMobileAndWifiIp(mobile, wifiIp)
userMobile.withTransaction {tx ->
userMobile.action = Constants.MOBILE_STATUS_DISCONNECTED
userMobile.alarmStatus = Constants.ALARM_STATUS_TURNED_ON
userMobile.modifiedDate = new Date()
userMobile.save(flush: true)
}
}catch(Exception e){
e.printStackTrace()
}
I am trying last 4 days but i am not able solve this.
Move the reads into the transaction, otherwise they'll be in a disconnected session and not the one that the transaction creates. Also, it's best to call static methods on the class, not an instance (in both Groovy and Java):
void deviceDisconnected(String mobileId, String wifiIp){
try {
UserMobile.withTransaction { tx ->
def mobile = Mobile.findByMobileId(mobileId)
def userMobile = UserMobile.findByMobileAndWifiIp(mobile, wifiIp)
userMobile.action = Constants.MOBILE_STATUS_DISCONNECTED
userMobile.alarmStatus = Constants.ALARM_STATUS_TURNED_ON
userMobile.modifiedDate = new Date()
userMobile.save(flush: true)
}
}
catch(e) {
e.printStackTrace()
}
}
Rather than using the verbose binding code suggested by Tiggerizzy. It is better to use the built in withNewSession method on domain classes:
Mobile.withNewSession {
// your code here
}
No need for me to spread mis-information and bad ways of doing things. Both the answers from Burt and Graeme will work. I just wrote a quick test app to prove this.

Resources