return not working in service - grails

I am getting a wierd problem and i am stuck on it for atleast 4 hours now. Actually i had written my code in a controller for testing but when i have moved the code to service i am getting a strange behaviour that the methods in service are not returning or may be methods that are calling them in the service only are not receiving .
class FacebookService implements InitializingBean, GroovyInterceptable {
def getUserLikes(def at){
List<String> listOfUrls = []
String basicFbUrl = "https://graph.facebook.com/"
String likeUrl = basicFbUrl + "me/likes?access_token=${at}"
URL url = new URL(likeUrl)
String jsonResponse = getResponseFromUrl(url)
println "JSON RESPONSE IS ${jsonResponse}" // this is showing null
}
String getResponseFromUrl() {
String something
String resp = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
int respCode = conn.responseCode
if (respCode == 400) {
log.error("COULD NOT MAKE CONNECTION")
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
def jsonResp = JSON.parse(br.text)
} else {
resp = conn.getInputStream().getText()
}
} finally {
conn.disconnect()
}
println("RETURNIG RESPONSE ${resp}") // This returns me a map as expected
return resp;
}
Dont know where does resp goes ?? any suggestions please ??
OK i know the culprit , i am posting the code of invokeMethod
def invokeMethod(String name, args){
System.out.println("IN INVOKE METHOD NAME ${name}")
if(facebookPalsCache==null)
facebookPalsCache = new FacebookPalsCache(1000)
System.out.println("time before ${name} called: ${new Date()}")
//Get the method that was originally called.
def calledMethod = metaClass.getMetaMethod(name, args)
System.out.println("CALLED METHOD IS ${calledMethod}")
//The "?" operator first checks to see that the "calledMethod" is not
//null (i.e. it exists).
if(name.equals("getFriends")){
println "getFriends..."
def session = RequestContextHolder.currentRequestAttributes().getSession()
def friends = facebookPalsCache.get(session.facebook.uid)
if(!friends){
def getFriends = facebookGraphService.invokeMethod (name, args)
println "Saving FBFRIENDS in CACHE"
facebookPalsCache.put(session.facebook.uid, getFriends)
return getFriends
}
else return friends
}
else {
if(calledMethod){
System.out.println("IN IF AND INVOKING METHOD ${calledMethod}")
calledMethod.invoke(this, args)
}
else {
return facebookGraphService.invokeMethod(name, args)
}
}
System.out.println "RETURNING FROM INVOKE METHOD FOR NAME ${name}"
System.out.println("time after ${name} called: ${new Date()}\n")
}
OK SOMETHING IS WRONG ABOVE I DONT KNOW WHAT CAN ANYONE PLEASE HELP ??

The code for invokeMethod and the service don't seem to be the same unless there's a separate FacebookGraphService. Assuming that's the case, then the resp is being caught in the part of your invokeMethod that's inside the if (calledMethod) { block, but since it's not the last line of the method it's not being returned from the call to invokeMethod and therefore is being gobbled up.
Try adding a return to calledMethod.invoke(this, args):
if(calledMethod){
System.out.println("IN IF AND INVOKING METHOD ${calledMethod}")
return calledMethod.invoke(this, args)
}

Related

Calling an ASP.Net web api from a ASP.Net MVC web app. MVC web client is not building the URL properly so getting not found

When I run my web api method using Postman passing in my URL, it works fine - it returns the value of '5' which I expect since the call returns just a single integer. Also at the very bottom I include another method of my web api that I run using Postman and it too works just fine.
http://localhost:56224/api/profileandblog/validatelogin/DemoUser1/DemoUser1Password/169.254.102.60/
However, in the client - an Asp.Net MVC method, when building the URL, it is DROPPING the "/api/profileandblog" part. Note: I'm using "attribute routing" in the web api.
Here is the Asp.Net MVC method to call the web api:
I stop it on this line so I can see the error details: if (result1.IsSuccessStatusCode)
It's INCORRECTLY building the URL as: http://localhost:56224/validatelogin/DemoUser1/DemoUser1Password/169.254.102.60/
It's dropping the: "/api/profileandblog" part that should follow 56224.
So it give's me the Not found.
Why does it drop it? It has the localhost:56224 correct.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignIn(SignInViewModel signInViewModel)
{
int returnedApiValue = 0;
User returnedApiUser = new User();
DateTime currentDateTime = DateTime.Now;
string hostName = Dns.GetHostName();
string myIpAddress = Dns.GetHostEntry(hostName).AddressList[2].ToString();
try
{
if (!this.IsCaptchaValid("Captcha is not valid"))
{
ViewBag.errormessage = "Error: captcha entered is not valid.";
}
else
{
if (!string.IsNullOrEmpty(signInViewModel.Username) && !string.IsNullOrEmpty(signInViewModel.Password))
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56224/api/profileandblog");
string restOfUrl = "/validatelogin/" + signInViewModel.Username + "/" + signInViewModel.Password + "/" + myIpAddress + "/";
// Call the web api to validate the sign in.
// Sends back a -1(failure), -2(validation issue) or the UserId(success) via an OUTPUT parameter.
var responseTask1 = client.GetAsync(restOfUrl);
responseTask1.Wait();
var result1 = responseTask1.Result;
if (result1.IsSuccessStatusCode)
{
var readTask1 = result1.Content.ReadAsAsync<string>();
readTask1.Wait();
returnedApiValue = Convert.ToInt32(readTask1.Result);
if (returnedApiValue == -2)
{
ViewBag.errormessage = "You entered an invalid user name and/or password";
}
else
{
// I have the 'user id'.
// Continue processing...
}
}
else
{
ModelState.AddModelError(string.Empty, "Server error on signing in. 'validatelogin'. Please contact the administrator.");
}
}
}
}
return View(signInViewModel);
}
catch (Exception)
{
throw;
}
}
Per the suggestion about not having headers, I used another tutorial (https://www.c-sharpcorner.com/article/consuming-asp-net-web-api-rest-service-in-asp-net-mvc-using-http-client/) and it has the code for defining the headers. But it is coded slightly different - using async Task<> on the method definition. I was not using async in my prior version.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SignIn(SignInViewModel signInViewModel)
{
int returnedApiValue = 0;
User returnedApiUser = new User();
DateTime currentDateTime = DateTime.Now;
string hostName = Dns.GetHostName();
string myIpAddress = Dns.GetHostEntry(hostName).AddressList[2].ToString();
try
{
if (!this.IsCaptchaValid("Captcha is not valid"))
{
ViewBag.errormessage = "Error: captcha entered is not valid.";
}
else
{
if (!string.IsNullOrEmpty(signInViewModel.Username) && !string.IsNullOrEmpty(signInViewModel.Password))
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56224/api/profileandblog");
string restOfUrl = "/validatelogin/" + signInViewModel.Username + "/" + signInViewModel.Password + "/" + myIpAddress + "/";
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Call the web api to validate the sign in.
// Sends back a -1(failure), -2(validation issue) or the UserId(success) via an OUTPUT parameter.
HttpResponseMessage result1 = await client.GetAsync(restOfUrl);
if (result1.IsSuccessStatusCode)
{
var readTask1 = result1.Content.ReadAsAsync<string>();
readTask1.Wait();
returnedApiValue = Convert.ToInt32(readTask1.Result);
if (returnedApiValue == -2)
{
ViewBag.errormessage = "You entered an invalid user name and/or password";
}
else
{
// I have the 'user id'.
// Do other processing....
}
}
else
{
ModelState.AddModelError(string.Empty, "Server error on signing in. 'validatelogin'. Please contact the administrator.");
}
}
}
}
return View(signInViewModel);
}
catch (Exception)
{
throw;
}
}
It now has a header but still NOT building the URL properly as it is not including the "/api/profileandblog" part.
Here is the web api and the method being called:
namespace GbngWebApi2.Controllers
{
[RoutePrefix("api/profileandblog")]
public class WebApi2Controller : ApiController
{
[HttpGet]
[Route("validatelogin/{userName}/{userPassword}/{ipAddress}/")]
public IHttpActionResult ValidateLogin(string userName, string userPassword, string ipAddress)
{
try
{
IHttpActionResult httpActionResult;
HttpResponseMessage httpResponseMessage;
int returnValue = 0;
// Will either be a valid 'user id" or a -2 indicating a validation issue.
returnValue = dataaccesslayer.ValidateLogin(userName, userPassword, ipAddress);
httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, returnValue);
httpActionResult = ResponseMessage(httpResponseMessage);
return httpActionResult;
}
catch (Exception)
{
throw;
}
}
}
}
Here's the network tab of the client browser before I hit the button to fire of the Asp.Net MVC method.
The network tab of the client browser after I hit the button to fire of the Asp.Net MVC method and it fails.
Here's another example of Postman executing another method of my api just fine.
I got it to work by setting this as: client.BaseAddress = new Uri("localhost:56224"); and setting the string restOfUrl = "/api/profileandblog/validatesignin/" + signInViewModel.Username + "/" + signInViewModel.Password + "/" + myIpAddress + "/";

HttpClient.PostAsync returning Null on A Web API POST

I am trying to get response from an API on few GET and POST calls, whenever i try to get Response from a web API POST it gives an System.NullReferenceException: Object reference not set to an instance of an object.. I am using PostAsync to get response. It works absolutely fine on my local machine but is returning NULL response on deployment machine.
#region API_CALL
System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient();
string CompleteURL = URL.Trim() + URL_FromJSON.Trim();
#region URL Construct For GET Requests
CompleteURL = GetURL(ParameterValue, CallType_FromJSON, CompleteURL);
#endregion URL Construct For GET Requests
string URLContent = string.Empty;
Client.BaseAddress = new System.Uri(CompleteURL);
byte[] cred = UTF8Encoding.UTF8.GetBytes(ClientID.Trim() + Constants.APIConstants.ColonConnector + ClientPass.Trim());
string Encoded = Convert.ToBase64String(cred);
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Constants.APIConstants.AuthTypeBearer, accessToken);
Client.DefaultRequestHeaders.Host = IPAddress.Trim();
CacheControlHeaderValue val = new CacheControlHeaderValue();
val.NoCache = true;
Client.DefaultRequestHeaders.CacheControl = val;
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(Constants.APIConstants.ContentType));
Client.DefaultRequestHeaders.Add(Constants.APIConstants.LicenseKey, LiscenseKEY);
Client.DefaultRequestHeaders.Add(Constants.APIConstants.PostmanToken, PostmanToken);
//client.DefaultRequestHeaders.Add(Constants.APIConstants.AccessToken, accessToken);
System.Net.Http.HttpContent Content = new StringContent(JSONData, UTF8Encoding.UTF8, Constants.APIConstants.ContentType);
// Only for debug purpos:
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Request to API: " + JSONData, Request.ActorID);
HttpResponseMessage Message = new HttpResponseMessage();
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
#region Response Logging
try
{
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Response from API: " + Message.Content.ReadAsStringAsync().Result, Request.ActorID);
}
catch(Exception EX)
{
LogManager.Logger.Invoke(LogLevels.TraceError, Source, "Exception while logging response from API" + EX.ToString()+"Stack: "+EX.StackTrace, Request.ActorID);
}
#endregion Response Logging
if (Message.IsSuccessStatusCode)
{
string Result = Message.Content.ReadAsStringAsync().Result;
ResponseJson = Result;
Description = Result;
}
else
{
try
{
string Result1 = Message.Content.ReadAsStringAsync().Result;
LogManager.Logger.Invoke(LogLevels.TraceInfo, Source, "Failed: ... Recieved JSON: " + Result1, Request.ActorID);
}
catch { }
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
#endregion API_CALL
break;
}
TransactionResponse Response = new TransactionResponse();
Response.Response = ResponseJson;
return Response;
}
catch (Exception Ex)
{
LogManager.ExpLogger.Invoke(Source, Ex, Request.ActorID);
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
the object : Message is null after execution of Message = Client.PostAsync(CompleteURL, Content).Result
Try reading as string asynch with the in the reach of postasynch, use it with the same block of code it works,
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
example:
var = httpresult.content.readasstringasyhnc();
You can also typecast to any model you want her.

calling a webservice from scheduled task agent class in windows phone 7.1

Can we call a webservice from the scheduled periodic task class firstly, if yes,
Am trying to call a webservice method with parameters in scheduled periodic task agent class in windows phone 7.1. am getting a null reference exception while calling the method though am passing the expected values to the parameters for the webmethod.
am retrieving the id from the isolated storage.
the following is my code.
protected override void OnInvoke(ScheduledTask task)
{
if (task is PeriodicTask)
{
string Name = IName;
string Desc = IDesc;
updateinfo(Name, Desc);
}
}
public void updateinfo(string name, string desc)
{
AppSettings tmpSettings = Tr.AppSettings.Load();
id = tmpSettings.myString;
if (name == "" && desc == "")
{
name = "No Data";
desc = "No Data";
}
tservice.UpdateLogAsync(id, name,desc);
tservice.UpdateLogCompleted += new EventHandler<STservice.UpdateLogCompletedEventArgs>(t_UpdateLogCompleted);
}
Someone please help me resolve the above issue.
I've done this before without a problem. The one thing you need to make sure of is that you wait until your async read processes have completed before you call NotifyComplete();.
Here's an example from one of my apps. I had to remove much of the logic, but it should show you how the flow goes. This uses a slightly modified version of WebClient where I added a Timeout, but the principles are the same with the service that you're calling... Don't call NotifyComplete() until the end of t_UpdateLogCompleted
Here's the example code:
private void UpdateTiles(ShellTile appTile)
{
try
{
var wc = new WebClientWithTimeout(new Uri("URI Removed")) { Timeout = TimeSpan.FromSeconds(30) };
wc.DownloadAsyncCompleted += (src, e) =>
{
try
{
//process response
}
catch (Exception ex)
{
// Handle exception
}
finally
{
FinishUp();
}
};
wc.StartReadRequestAsync();
}
private void FinishUp()
{
#if DEBUG
try
{
ScheduledActionService.LaunchForTest(_taskName, TimeSpan.FromSeconds(30));
System.Diagnostics.Debug.WriteLine("relaunching in 30 seconds");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
#endif
NotifyComplete();
}

entered values are being cleared in gsp

I am entering values(URLs) in the text box and when I click the next button, validation runs whether the entered url values are valid or not.
if the urls are not valid then i display the error as below
if(valid == false){
this.errors.reject("Incorrect URL is entered for "+countries.get(countryCode)+" - please ensure to use a correct URL for More Games.")
return [];
}
Once the error is shown, its clearing the entered values and need to enter the values again. How can I restrict clearing the values(i think the page is getting loaded again) or to restrict the page to load again.
here is the command -
class DeliveryMoreGamesURLCommand implements Command {
private static final LOG = LogFactory.getLog(DeliveryController.class)
def wrapperService = ApplicationHolder.application.getMainContext().getBean("wrapperService");
def customerService = ApplicationHolder.application.getMainContext().getBean("customerService");
def countryService = ApplicationHolder.application.getMainContext().getBean("countryService");
def helperService = ApplicationHolder.application.getMainContext().getBean("helperService");
def ascService = ApplicationHolder.application.getMainContext().getBean("ascService");
Hashtable<String, String> countries;
public LinkedHashMap<String, Object> preProcess(sessionObject, params, request) {
Delivery delivery = (Delivery) sessionObject;
def customer = Customer.get(delivery.customerId);
def contentProvider = ContentProvider.get(delivery.contentProviderId);
def deployment = Deployment.get(delivery.deploymentId);
def operatingSystem = OperatingSystem.get(delivery.operatingSystemId);
countries = wrapperService.getCountries(deployment, operatingSystem);
def sortedCountries = countries.sort { a, b -> a.value <=> b.value };
def urls = ascService.getMoreGamesUrlsPerTemplates(deployment, operatingSystem);
def moreGamesUrls = new Hashtable<String,String>();
countries.each { country ->
String countryCode = countryService.getTwoLetterCountryAbbreviation(country.key);
String url = customerService.getMoreGamesUrl(customer, contentProvider, countryCode);
if ("".equals(url)) {
url = urls.get(country.key);
if (url == null) {
url = "";
}
}
moreGamesUrls.put(country.key, url); // We need to use the existing country code if the channels are deployed with three letter country codes
}
return [command: this, countries: sortedCountries, moreGamesUrls: moreGamesUrls]
}
public LinkedHashMap<String, Object> postProcess(sessionObject, params, request) {
Delivery delivery = (Delivery) sessionObject;
def urls = params.gamesUrls;
LOG.debug("urls from gsp :"+urls)
try{
urls.eachWithIndex { u, i ->
String countryCode = u.key;
String url = urls["${u.key}"]
if(url != ""){
Boolean valid = helperService.isURLValid(url)
if(valid == false){
this.errors.reject("Incorrect URL is entered for "+countries.get(countryCode)+" - please ensure to use a correct URL for More Games.")
return [];
}
}
}
}catch (Exception ex) {
logger.warn("Incorrect URL is entered", ex)
return [];
}
def moreGamesUrls = new Hashtable<String, String>();
urls.eachWithIndex { u, i ->
String countryCode = u.key;
String url = urls["${u.key}"]
moreGamesUrls.put(countryCode, url);
}
delivery.countries = countries;
delivery.moreGamesUrls = moreGamesUrls;
LOG.debug("moreGamesUrls after edit=${delivery.moreGamesUrls}");
return null;
}
}
from the command preprocess the data will be rendered and after clicking the next button, the postprocess will be invoked and the validation for the url...
Resolved this issue by implementing moreGamesUrls as a global variable(which stored the values even after the error is thrown)

removeFrom* not working and with no errors

I have what I think is a simple problem but have been unable to solve...
For some reason I have a controller that uses removeFrom*.save() which throws no errors but does not do anything.
Running
Grails 1.2
Linux/Ubuntu
The following application is stripped down to reproduce the problem...
I have two domain objects via create-domain-class
- Job (which has many notes)
- Note (which belongs to Job)
I have 3 controllers via create-controller
- JobController (running scaffold)
- NoteController (running scaffold)
- JSONNoteController
JSONNoteController has one primary method deleteItem which aims to remove/delete a note.
It does the following
some request validation
removes the note from the job - jobInstance.removeFromNotes(noteInstance).save()
deletes the note - noteInstance.delete()
return a status and remaining data set as a json response.
When I run this request - I get no errors but it appears that jobInstance.removeFromNotes(noteInstance).save() does nothing and does not throw any exception etc.
How can I track down why??
I've attached a sample application that adds some data via BootStrap.groovy.
Just run it - you can view the data via the default scaffold views.
If you run linux, from a command line you can run the following
GET "http://localhost:8080/gespm/JSONNote/deleteItem?job.id=1&note.id=2"
You can run it over and over again and nothing different happens. You could also paste the URL into your webbrowser if you're running windows.
Please help - I'm stuck!!!
Code is here link text
Note Domain
package beachit
class Note
{
Date dateCreated
Date lastUpdated
String note
static belongsTo = Job
static constraints =
{
}
String toString()
{
return note
}
}
Job Domain
package beachit
class Job
{
Date dateCreated
Date lastUpdated
Date createDate
Date startDate
Date completionDate
List notes
static hasMany = [notes : Note]
static constraints =
{
}
String toString()
{
return createDate.toString() + " " + startDate.toString();
}
}
JSONNoteController
package beachit
import grails.converters.*
import java.text.*
class JSONNoteController
{
def test = { render "foobar test" }
def index = { redirect(action:listAll,params:params) }
// the delete, save and update actions only accept POST requests
//static allowedMethods = [delete:'POST', save:'POST', update:'POST']
def getListService =
{
def message
def status
def all = Note.list()
return all
}
def getListByJobService(jobId)
{
def message
def status
def jobInstance = Job.get(jobId)
def all
if(jobInstance)
{
all = jobInstance.notes
}
else
{
log.debug("getListByJobService job not found for jobId " + jobId)
}
return all
}
def listAll =
{
def message
def status
def listView
listView = getListService()
message = "Done"
status = 0
def response = ['message': message, 'status':status, 'list': listView]
render response as JSON
}
def deleteItem =
{
def jobInstance
def noteInstance
def message
def status
def jobId = 0
def noteId = 0
def instance
def listView
def response
try
{
jobId = Integer.parseInt(params.job?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in jobId " + params.job?.id)
log.debug(ex.getMessage())
}
if (jobId && jobId > 0 )
{
jobInstance = Job.get(jobId)
if(jobInstance)
{
if (jobInstance.notes)
{
try
{
noteId = Integer.parseInt(params.note?.id)
}
catch (NumberFormatException ex)
{
log.debug("deleteItem error in noteId " + params.note?.id)
log.debug(ex.getMessage())
}
log.debug("note id =" + params.note.id)
if (noteId && noteId > 0 )
{
noteInstance = Note.get(noteId)
if (noteInstance)
{
try
{
jobInstance.removeFromNotes(noteInstance).save()
noteInstance.delete()
message = "note ${noteId} deleted"
status = 0
}
catch(org.springframework.dao.DataIntegrityViolationException e)
{
message = "Note ${noteId} could not be deleted - references to it exist"
status = 1
}
/*
catch(Exception e)
{
message = "Some New Error!!!"
status = 10
}
*/
}
else
{
message = "Note not found with id ${noteId}"
status = 2
}
}
else
{
message = "Couldn't recognise Note id : ${params.note?.id}"
status = 3
}
}
else
{
message = "No Notes found for Job : ${jobId}"
status = 4
}
}
else
{
message = "Job not found with id ${jobId}"
status = 5
}
listView = getListByJobService(jobId)
} // if (jobId)
else
{
message = "Couldn't recognise Job id : ${params.job?.id}"
status = 6
}
response = ['message': message, 'status':status, 'list' : listView]
render response as JSON
} // deleteNote
}
I got it working... though I cannot explain why.
I replaced the following line in deleteItem
noteInstance = Note.get(noteId)
with the following
noteInstance = jobInstance.notes.find { it.id == noteId }
For some reason the jobInstance.removeFromNotes works with the object returned by that method instead of .get
What makes it stranger is that all other gorm functions (not sure about the dynamic ones actually) work against the noteInstance.get(noteId) method.
At least it's working though!!
See this thread: http://grails.1312388.n4.nabble.com/GORM-doesn-t-inject-hashCode-and-equals-td1370512.html
I would recommend using a base class for your domain objects like this:
abstract class BaseDomain {
#Override
boolean equals(o) {
if(this.is(o)) return true
if(o == null) return false
// hibernate creates dynamic subclasses, so
// checking o.class == class would fail most of the time
if(!o.getClass().isAssignableFrom(getClass()) &&
!getClass().isAssignableFrom(o.getClass())) return false
if(ident() != null) {
ident() == o.ident()
} else {
false
}
}
#Override
int hashCode() {
ident()?.hashCode() ?: 0
}
}
That way, any two objects with the same non-null database id will be considered equal.
I just had this same issue come up. The removeFrom function succeeded, the save succeeded but the physical record in the database wasn't deleted. Here's what worked for me:
class BasicProfile {
static hasMany = [
post:Post
]
}
class Post {
static belongsTo = [basicProfile:BasicProfile]
}
class BasicProfileController {
...
def someFunction
...
BasicProfile profile = BasicProfile.findByUser(user)
Post post = profile.post?.find{it.postType == command.postType && it.postStatus == command.postStatus}
if (post) {
profile.removeFromPost(post)
post.delete()
}
profile.save()
}
So it was the combination of the removeFrom, followed by a delete on the associated domain, and then a save on the domain object.

Resources