How do I associate all logs with their request in grails? - grails

In our grails application we're logging a lot, but need a mechanism to associate all of those messages with the request/response being processed. It has proven easy enough to generate a request UUID, but now I'd like that id appended to each log message generated within a request context without passing that id within each log message. Has anybody implemented such a system so that you can associate all of your log statements together?

A rather obscure feature of log4j, called MDC seems to be exactly what you need.
Something like http://gustlik.wordpress.com/2008/07/05/user-context-tracking-in-log4j/
It will work fine in Grails as well if you use a custom AppFilter to set the request-unique value.

you could try utilizing the RequestContextHolder
http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/context/request/RequestContextHolder.html
ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
log.debug attr.getRequest().getSession()
Once you get the session object, you can get whatever identifier you have stashed away?

Related

How to add extra components to HL7 message using Java Hapi?

I am working on building a replacement to MIRTH and it looks like we are sending out non-standard HL7 ORU_R01 messages. OBR.5 should be just a single field but looks like we are sending a bunch of other data in this section.
<OBR.5>
<OBR.5.1>XXXX</OBR.5.1>
<OBR.5.2>XXXX</OBR.5.2>
<OBR.5.3>XXXXX</OBR.5.3>
<OBR.5.5>XXXXX</OBR.5.5>
<OBR.5.6>XXXX</OBR.5.6>
<OBR.5.7/>
<OBR.5.8>XXXXXXXXXX</OBR.5.8>
<OBR.5.10>XXXXXXX</OBR.5.10>
<OBR.5.11>X</OBR.5.11>
<OBR.5.12>X</OBR.5.12>
<OBR.5.13>XXXXX</OBR.5.13>
<OBR.5.15>XXXXXXX</OBR.5.15>
</OBR.5>
It seems like I should be able to something like the following.
obr.getObr5_Priority().getExtraComponents().getComponent(2).setData(...)
But I am having issues trying to find the correct way to set the different segments. All the fields are Strings.
Found something that I think has ended up working for us.
ID expirationDate = new ID(obr.getMessage(), 502);
expirationDate.setValue(format2.format(date));
obr.getObr5_Priority().getExtraComponents().getComponent(0).setData(expirationDate);
Where 503 refers to which element you want to set. In this case I am trying to set OBR-5.2. getComponent(0) because it's the first extra component I am adding for this particular segment. I am not sure entirely if my explanation here is correct but it creates a message we need and parses as I'd expect so its my best guess.
Dereived the answer from this old email thread https://sourceforge.net/p/hl7api/mailman/hl7api-devel/thread/0C32A03544668145A925DD2C339F2BED017924D8%40FFX-INF-EX-V1.cgifederal.com/#msg19632481

How to properly save updates to domain objects in Groovy/Grails

I'm starting to touch the Groovy/Grails backend of my organization and am tasked with updating the User on our Document domain object. The problem is, after hitting the update endpoint from the frontend with the correct params attached, the backend responds with an unchanged Document object.
Here is the code:
if (requestParams.userEmail) {
def contact = User.findByEmail(requestParams.userEmail)
log.debug('Reading user found by passed email contact={} error={}',contact, contact.errors.allErrors.inspect())
if (!contact) {
response.status = 400
render WebserviceError.badInput as JSON
return
}
document.user = contact
document.user.save(flush: true)
}
document.save(flush: true)
render survey as JSON
The frontend returns a promise and I'm logging the promise response, and it shows an unchanged Document object with the same exact user attached. I don't receive a 400 so it looks like the contact is successfully found.
I tried adding flush:true to the user.save call and the document.save call and that did not help.
Are there any obvious wrongdoings in my code?
Well db operations should be in a service, not in a controller, using #Transactional, preferably the gorm version not the spring version. You shouldn't need to use flush: true. Then fron the service you can return to the controller, andrender as JSON.
You don’t state that you see the debug statement on the server indicating a found user, perhaps it’s never actually getting to this section?
I assume that the code provided is incomplete, as we don’t see that the survey being returned contains the document that’s being updated. And also the braces look unbalanced, as if there’s a control flow issue. (i.e. why are there 2 opening braces but 3 closing braces?)
I’d suggest that you use a debugger on your code to see how control is actually flowing. Most Java IDEs support easy debugging, essentially clicking the debug button rather than the run button. Set a number of breakpoints sprinkled through this code to catch requests and call the API endpoint from your frontend.
is Document the parent? User a child?
User.addTodocument(someUser)
then Document.merge()

How can I retrieve deleted objects from Active Directory with Ruby?

From the research I've done, it appears I need to send a special OID with my request (1.2.840.113556.1.4.417) in order to access the Deleted Objects container.
I couldn't find a way to send a specific control with a request using the "net-ldap" gem. Does anyone know if this is possible?
There is another gem, ruby-ldap, which appears to be more flexible and it seems I can send controls with my request (e.g. using the search_ext2() method).
However, no matter what I try, I am not getting back any objects, even though I know they haven't been garbage collected yet.
I'm including the filter "isDeleted=TRUE" with my requests as well.
OK, I finally figured it out. One will need to use the ruby-ldap gem. The reason my controls were not being sent was because the LDAP Protocol Version (LDAP::LDAP_OPT_PROTOCOL_VERSION) had defaulted to v2 and apparently it must be v3.
The following is a snippet that works:
require 'ldap'
conn = LDAP::Conn.new('yourserver.example.com', 389)
conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)
conn.bind("CN=Administrator,CN=Users,DC=example,DC=com", "sekritpass")
# controlType: 1.2.840.113556.1.4.417 (LDAP_SERVER_SHOW_DELETED_OID)
control = LDAP::Control.new('1.2.840.113556.1.4.417')
conn.search_ext2('CN=Deleted Objects,DC=example,DC=com', LDAP::LDAP_SCOPE_SUBTREE, "(isDeleted=*)", nil, false, [control], nil)
The filter (isDeleted=*) isn't necessarily required, you could also simply use (objectClass=*). You can also use the scope LDAP::LDAP_SCOPE_ONELEVEL if desired.
Have you tried isDeleted=* instead?
https://technet.microsoft.com/en-us/library/cc978013.aspx

How to GET a read-only vs editable resource in REST style?

I'm fairly familiar with REST principles, and have read the relevant dissertation, Wikipedia entry, a bunch of blog posts and StackOverflow questions on the subject, but still haven't found a straightforward answer to a common case:
I need to request a resource to display. Depending on the resource's state, I need to render either a read-only or an editable representation. In both cases, I need to GET the resource. How do I construct a URL to get the read-only or editable version?
If my user follows a link to GET /resource/<id>, that should suffice to indicate to me that s/he needs the read-only representation. But if I need to server up an editable form, what does that URL look like? GET /resource/<id>/edit is obvious, but it contains a verb in the URL. Changing that to GET /resource/<id>/editable solves that problem, but at a seemingly superficial level. Is that all there is to it -- change verbs to adjectives?
If instead I use POST to retrieve the editable version, then how do I distinguish between the POST that initially retrieves it, vs the POST that saves it? My (weak) excuse for using POST would be that retrieving an editable version would cause a change of state on the server: locking the resource. But that only holds if my requirements are to implement such a lock, which is not always the case. PUT fails for the same reason, plus PUT is not enabled by default on the Web servers I'm running, so there are practical reasons not to use it (and DELETE).
Note that even in the editable state, I haven't made any changes yet; presumably when I submit the resource to the Web server again, I'd POST it. But to get something that I can later POST, the server has to first serve up a particular representation.
I guess another approach would be to have separate resources at the collection level:
GET /read-only/resource/<id> and GET /editable/resource/<id> or GET /resource/read-only/<id> and GET /resource/editable/<id> ... but that looks pretty ugly to me.
Thoughts?
1) It is perfectly valid to have two distinct resources, one for viewing and one for editing some domain concept. Just be aware that because they are two different URIs from REST's perspective they are two different resources. Too often people conflate resource with domain object. That's why they end up being stuck only doing CRUD.
2) Don't get too hung up on the name of the resource. The important thing is that you realize that what the URI points to is a "thing", "a resource". If that's more obvious to you with editable instead of edit then use that. Having a verb in your URL doesn't make your application wrong, it just makes it a bit less readable to the human developer. Using a verb in the URL to try and redefine the semantics of the HTTP method, now that's a violation of the uniform interface constraint.
In REST, editing an existing resource is accomplished by a client GET-ing a representation of that resource, making changes to the representation, and then doing a PUT of the new representation back to the server.
So to just read a resource your REST client program would do a:
GET http://www.example.com/SomeResource
And to edit that resource:
GET http://www.example.com/SomeResource
... edit it ...
PUT http://www.example.com/SomeResource
Normally simultaneous updates are handled by letting the last PUT arriving at the server overwrite the earlier ones, on the assumption that it represents a newer state. But in your case you want to guard against this.
Carefully consider #Jason's suggestion to maintain an optional parallel lock resource for each main resource. Your client would first create the lock, do the edit, then delete the lock. Your system would need to release a lock automatically if the user making the lock subsequently never saves any changes. This would look like:
GET http://www.example.com/SomeResource
... user presses an edit button ...
PUT http://www.example.com/SomeResource/lock
... user edits the resource's representation ...
PUT http://www.example.com/SomeResource
DELETE http://www.example.com/SomeResource/lock
You'd need to do some appropriate error handling if the user is trying to edit a resource that's locked by someone else.
It sounds like you feel you're constrained by the current limitations of HTML. If you use a server-side REST framework like Restlet (for Java), it supports the notion of "overloaded POST", where you can use POST but tack on a query string argument like method=PUT or method=DELETE. If you're writing your own server-side components they can use this trick too.
There are tricks you can play at the HTML level too. For instance your page can have a read-only part that's initially displayed, and an input form that's initially not shown. When the user presses the edit button, your JavaScript hides the read-only part and shows the input form.
Be sure to read Richardson and Ruby's Restful Web Services (O'Reilly) too. It's extremely helpful.
I don't think returning a form or just values is up to a REST server, but the responsibility of the client. Whether a resource is editable is a property of the resource, and not something defined by the URL.
In other words: The URL for getting the resource is GET /resource/<id>. This has a property editable. If a user wants a form it can retrieve the resource from the same URL and populate the form. The client can than PUT/POST changes.
How do I construct a URL to get the read-only or editable version?
There's an underlying problem here, which is that you are constructing URLs in the first place - appending IDs to hard-coded URLs is not REST. Roy Fielding has written about this very mistake. Whichever document prompts you to edit the resource should contain the URI to the editable variant of that resource. You follow that URI, whether that's /resource/editable or /editable/resource is outside the scope of REST.
If instead I use POST to retrieve the editable version, then how do I distinguish between the POST that initially retrieves it, vs the POST that saves it?
You perform a GET (not a POST) to read the resource, and POST (or PUT) to write the resource.
If you want to create a lock on the resource in question, use POST to write to the resource (or the resource's container, with the resource ID encoded in the body of the POST), and have the server create a lock as a new resource, and return an ID of that resource as the response to the POST. (with authentication issues beyond the scope of your question or this answer)
Then to unlock the lock, either use a DELETE on the lock resource, or POST to the lock's container.
I guess your question could be "how to identify the readonly representation that return with GET action in PUT action?". You could do this:
<Root>
<readonly>
<p1><p1>
...
<readonly>
<others>
...
<others>
<Root>
After parsing the request XML from PUT you can ignore the readonly part and process others. In Response, return 200 status and leave a message saying the part in readonly is ignored.
Is it your expected?

Symfony: question about a piece of code of sfDoctrineGuardPlugin

there is this code below in sfDoctrineGuardPlugin.
$a = sfConfig::get('app_sf_guard_plugin_success_signin_url');
var_dump($a);
$signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user->getReferer($request->getReferer()));
var_dump($signinUrl);
var_dump($user->getReferer($request->getReferer()));
It prints this:
null
string
'http://rs3.localhost/frontend_dev.php/'
(length=38)
string
'http://rs3.localhost/frontend_dev.php/miembros' (length=46)
I don't know why the the second and the third lines are different..any idea?
Regards
Javi
Weird. Spooky.
I wonder if maybe the two calls to getReferer() are in different contexts? Maybe the first (as the second arg to sfConfig::get()) implicitly uses __toString() whereas when you use var_dump(), maybe it's printing the raw value of the referer object?
Hrmm... the API says getReferer() returns a string, so that's probably not it.
What are you trying to do, BTW? Is it not honoring your app_sf_guard_plugin_success_signin_url setting from app.yml?
sfDoctrineGuardPlugin sets a referer attribute in the user, so that it can redirect back to the page originally requested. When you call getReferer it removes the attribute. (This is causing bugs for me, which is what brought me here.)
yitznewton pointed me towards a solution. The sfGuardSecurityUser class uses a method setReferer that saves a referer attribute but only if one is not yet set.
If somehow you manage to get to the executeSignin method in the sfGuard actions twice only the first referer attribute will be saved, this means that the second time the referer in the request and the referer in the user attribute can be different.
The getReferer method removes that attribute, and falls back to the request referer when the attribute is not set. this explains why calling $user->getReferer($request->getReferer()) twice returns different values sometimes.
The solution i found was to overwrite the setReferer method of the sfGuardSecurityUser in the myUser class:
public function setReferer($referer) {
$this->setAttribute('referer', $referer);
}
So far i have not found any side effects, this change ensures the user attribute will allways be the most recent, however there has to be a reason to explain why the symfony folk chose to implement this as it was.
Ive tested this by switching between apps on the login screen, allowing the session to die, killing the session manually and normally using the application and so far i have not found any side effects.

Resources