GORM provides Grails developers lots of useful hooks, events, methods, and functionality, very important is domain events that inform you when domain objects are being created, updated, and deleted. Within these events, a common use-case is to determine if a particular domain property has changed, and to act accordingly. Below is a code snippet of how you validate your domain before insert or update. |
package com.pkm class Table1 { Long id String name String roll static mapping = { table("table1") } static hasMany = [ scores: Table2 ] void beforeValidate(){ println("BEFORE VALIDATE") } void beforeInsert(){ println("BEFORE INSERT") } void beforeUpdate(){ println("BEFORE UPDATE") } } |
Now, how can you get the actual value of that object? The actual value is modified and you want to get the persisted value. One “not so good” idea is to call refresh() which will load the object from the database again which might be a huge data retrieval in few cases. To solve this problem, GORM has given a simple method which will do the work for you: Below is a example of how you can see which fields are updating in current transaction using below code snippet |
void beforeUpdate(){ println("BEFORE UPDATE") this.dirtyPropertyNames.each { String fieldName -> def oldValue = this.getPersistentValue(fieldName) def newValue = this.getProperty(fieldName) println("\t> VALUE CHANGED FOR $fieldName FROM $oldValue TO $newValue") } } |
The best place to check for dirty properties is usually in the beforeUpdate event. The beforeInsert and afterUpdate events may also seem like good choices at first, but they may not be depending on the use-case. Before inserting, all properties are dirty because they are new, so they haven't really changed they have just been created. After updating, none of the properties are dirty because the new values have already been persisted in your database. These events provide plenty of value if used correctly, but may not always be the best place to check for dirty domain properties. |
One domain in particular that I always perform dirty property checks on is any User domains that my application requires. For instance, if a User object's password has changed, you may want to be alerted in the beforeUpdate event and encrypt the password before it is inserted into your database. |
You also can check if an existing field is dirty or not using this.isDirty("fieldname") |
Be careful not to perform any saves on the domain within these events, as you will get a StackOverflowException. (The event calls .save(), restarting the whole event cycle, where .save() will be called again, and so on. This infinite loop will never end, and the exception will be raised.) |
Otherhand you can check if entire session (hibernate session) is dirty or not. so below is an example how to check if whole hibernate session is dirty or not. |
package com.pkm import grails.transaction.Transactional import org.springframework.transaction.TransactionStatus import org.hibernate.SessionFactory import grails.util.Holders @Transactional class HomeService { TransactionStatus transactionStatus void callMe() { Table1 table1 = Table1.first() table1.roll = System.currentTimeMillis().toString() table1.save() SessionFactory sessionFactory = Holders.applicationContext.getBean(SessionFactory) Boolean isDirty = sessionFactory.currentSession.isDirty() println("IS SESSION DIRTY=${isDirty.toString().capitalize()}") } } |
Friday, July 6, 2018
Grails on Groovy > GORM dirty checking of instance and properties > grails - tell me if anything is dirty > Checking for Dirty (Updated) Properties on a Grails Domain
Saturday, June 23, 2018
When do I need to call this method Runtime.getRuntime().addShutdownHook() > Java.lang.Runtime.addShutdownHook(Thread hook) Method > Java Shutdown hook – Runtime.addShutdownHook() > Grails on Groovy: Add a ShutdownHook > Runtime: addShutdownHook(Thread hook)
The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.The Java virtual machine shuts down in response to two kinds of events > The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked > The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown |
Below is a example of how shutdown hook can be used: |
package com.pkm; public class RegisterShutDownHook { public static void main(String[] args) { System.out.println("PROGRAM STARTED"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("SHUTDOWN HOOK FIRED"); } }); System.out.println("PROGRAM RUNNING"); } } |
Output of the above code snippet would be like below: |
PROGRAM STARTED PROGRAM RUNNING SHUTDOWN HOOK FIRED |
When you are using Grails application, you can do that various process. Either registering shutdown hook or implementing DisposableBean |
Below is the process using shutdown hook |
class BootStrap { def init = { servletContext -> addShutdownHook { println("Running Shutdown Hook"); } } def destroy = { } } |
Or as below, create another class and registering that from resources.groovy like below: |
package com.pkm import org.springframework.context.ApplicationContextAware import org.springframework.context.ApplicationContext class ShutdownHook implements ApplicationContextAware { void setApplicationContext(ApplicationContext applicationContext) { Runtime.runtime.addShutdownHook { println("Application context shutting down...") applicationContext.close() println("Application context shutdown.") } } } // Adding the following block in grails-app/conf/spring/resources.groovy // Place your Spring DSL code here beans = { myShutdownHook(com.pkm.ShutdownHook) } |
And my last known process is using DisposableBean |
package com.pkm import grails.transaction.Transactional import org.springframework.beans.factory.DisposableBean @Transactional class HomeService implements DisposableBean { @Override void destroy() throws Exception { println("APPLICATION DESTROYED") } } |
How to pass parameters / arguments to your PHP script via the command line
If you want to be able to assign variable names for the values being passed in like php script.php -pvalue1, getopt() is the way to do it. Lets look at a different version of the script now > |
$val = getopt("p:"); |
There are some major differences here. First with getopt() you must specify which command line argument you want to retrieve. In the case of this script, it looks for the "-name" argument, that's specified by the "name:" value passed to getopt(). The colon (:) means that the parameter must have a value. If you're used to doing something like "script.php?name=Name&roll=Roll" this is an equivalent for the command line. |
php script.php --name=test --roll="03 d" |
$val = getopt("name:roll:"); |
Friday, June 22, 2018
Header only retrieval in php via curl | PHP CURL get content type from URL | PHP CURL retrieve headers information from URL
Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata. |
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers: |
The PHP code for the CURL request would look something like this: |
$agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36 X-Client-Data: CIa2yQEIpLbJAQjBtskBCKmdygEIqKPKARiSo8oB"; $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); curl_setopt($curl, CURLOPT_FILETIME, true); curl_setopt($curl, CURLOPT_NOBODY, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_HEADER, true); curl_setopt($curl, CURLOPT_USERAGENT, $agent); $header = curl_exec($curl); $info = curl_getinfo($curl); curl_close($curl); |
Which will output as below: |
HTTP/1.1 200 OK Date: Fri, 22 Jun 2018 06:47:27 GMT Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 Last-Modified: Sun, 11 Feb 2018 16:39:41 GMT ETag: "5ae6f-564f2687e28f8" Accept-Ranges: bytes Content-Length: 372335 Content-Type: application/pdf Array ( [url] => http://localhost/text-finder/download.pdf [content_type] => application/pdf [http_code] => 200 [header_size] => 265 [request_size] => 258 [filetime] => 1518367181 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.016 [namelookup_time] => 0.016 [connect_time] => 0.016 [pretransfer_time] => 0.016 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 372335 [upload_content_length] => -1 [starttransfer_time] => 0.016 [redirect_time] => 0 [redirect_url] => [primary_ip] => ::1 [certinfo] => Array ( ) [primary_port] => 80 [local_ip] => ::1 [local_port] => 51877 ) HTTP/1.1 200 OK Date: Fri, 22 Jun 2018 06:48:11 GMT Server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 Last-Modified: Fri, 22 Jun 2018 04:18:28 GMT ETag: "92-56f3352eebe85" Accept-Ranges: bytes Content-Length: 146 Content-Type: text/html Array ( [url] => http://localhost/text-finder/test2.html [content_type] => text/html [http_code] => 200 [header_size] => 253 [request_size] => 256 [filetime] => 1529641108 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.015 [namelookup_time] => 1.0E-6 [connect_time] => 0.015 [pretransfer_time] => 0.015 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => 146 [upload_content_length] => -1 [starttransfer_time] => 0.015 [redirect_time] => 0 [redirect_url] => [primary_ip] => ::1 [certinfo] => Array ( ) [primary_port] => 80 [local_ip] => ::1 [local_port] => 51944 ) |
jQuery AJAX fetch only headers and decide wheather to get the content | Use jQuery to send a HEAD request with AJAX and get the size of a file | Getting response headers data from an AJAX request with javascript
Response headers can contain valuable information and may help to keep your API responses simpler by separating the actual response data from accessory metadata. |
For instance, when querying the API for a list of posts, the response body includes just the content but there are also some other valualbe information sent as headers: |
The jQuery code for the AJAX request would look something like this: |
$.ajax({ type: 'HEAD', url: 'http://example.com/api.php', complete: function (xhr) { var contentLength = xhr.getResponseHeader('Content-Length'); // OR YOU CAN SEE ALL INFORMATION USING var headers = xhr.getAllResponseHeaders(); } }); |
Which will output as below: |
http://localhost/text-finder/download.pdf >> application/pdf date: Fri, 22 Jun 2018 06:35:52 GMT last-modified: Sun, 11 Feb 2018 16:39:41 GMT server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 etag: "5ae6f-564f2687e28f8" content-type: application/pdf connection: Keep-Alive accept-ranges: bytes keep-alive: timeout=5, max=100 content-length: 372335 http://localhost/text-finder/test2.html/forum >> text/html; charset=utf-8 date: Fri, 22 Jun 2018 06:35:52 GMT server: Apache/2.4.33 (Win32) OpenSSL/1.0.2n PHP/5.6.35 vary: accept-language,accept-charset content-language: en connection: Keep-Alive accept-ranges: bytes content-type: text/html; charset=utf-8 keep-alive: timeout=5, max=97 |
Get URL and URL Parts in JavaScript | Get an Absolute URL with JavaScript | How to get the exact href value only without their domain | How to check if any Link is for some specific domain | Link attribute HOST > PATHNAME > Filter links by domain | host name
I'm having trouble in getting the exact value of href only |
It's a little known (maybe) fact that most browsers convert Anchor node elements into Location objects as well. So you can access all parts available to Location too; |
Suppose consider below html code: |
<body> HELLO '59 IS PRESENT <a href="test2.html">HI</a> <a href="https://stackoverflow.com/questions/domain">Another LINK</a> </body> |
In above html, two link exists, one for self domain and another for stackoverflow, now if I look through them, below output would be generated: |
PROTOCOL=http:, HOST=localhost, PORT= LINK PATH=/test2.html PROTOCOL=https:, HOST=stackoverflow.com, PORT= LINK PATH=/questions/domain |
A regex to match a substring that isn't followed by a certain other substring > Find Any Word Not Followed by a Specific Word > Regex Negative Lookbehind
The problem is I need to match a word say "match" in a string. It is very easy using the expression /(match)/gi |
Above expression is very easy. Now original problem is need to match word "match" not starting with any other word like 10 or 20 or any word. To do so we need to use negative lookbehind. Below is a complete regex that will match word match but not start with 10 or 20 or '. |
/(?<!(10|20))(?<!')(match)/gi |
Meaning of the above regex is will match a word match but not followed by 10 or 20 or ' Output of this regex is as below |
|
Explanation of this regex: |
|
Subscribe to:
Posts (Atom)