It is my pleasure to inform you that Diplomatic Agent Terry has arrive in yournearest Airport today with your package worthy $5.5million you have to contacthim at this email address (diplomaticagentfredjames33@gmail.com)
Code Snippets, Ideas and Rants from a Tech Lead interested primarily in server side web development and leading teams who build web apps.
Monday, October 31, 2016
Spam email
Sometime spam email is so bad it is pure comedy genius. The amount of things wrong with this opening statement.
Wednesday, October 26, 2016
Side effects with not having decent UNIT tests
This is not Grails/Groovy specific but in general.
Grails/Groovy is certainly more reliant on tests, as it is dynamically typed, so code needs to be executed to pickup errors. The Java world seems to rely on static typing while Groovy on tests. Tests are always better than typing, period.
Besides the obvious, if it is not tested how do you know it works? There are some interesting side effects I see with poorly unit tested code.
Makes your Code Better
Documents Code
Makes changing existing code possible
Quicker to Change and Safer to Change
Grails/Groovy is certainly more reliant on tests, as it is dynamically typed, so code needs to be executed to pickup errors. The Java world seems to rely on static typing while Groovy on tests. Tests are always better than typing, period.
Besides the obvious, if it is not tested how do you know it works? There are some interesting side effects I see with poorly unit tested code.
Makes your Code Better
- Having to write unit tests for a class/method makes your code structurally better.
- It leads to better separation of concerns.
- Starts enforcing the law of Demeter.
- Easily tested code is generally easier to understand.
Documents Code
- Documentation falls out of date and quickly becomes irrelevant. Properly written tests (Spock helps) is a great way to document code.
Makes changing existing code possible
- I cannot change existing if I have no idea if it works, or how it works.
- In larger systems knowing if existing code works without tests becomes increasingly difficult.
- It can be very difficult to execute see what code is doing if you need to stand up the whole system just to test a method.
Quicker to Change and Safer to Change
- If your code has a unit test you can execute it immediately.
- You can see changes, and what they do to existing tests immediately
- 100's of times an hour.
Tuesday, October 25, 2016
Intellij Color Schemes
Found a neat little site with colour schemes for Intellij
http://color-themes.com/?view=index
Once you have downloaded the jar, just go to File->import settings and load that jar.
http://color-themes.com/?view=index
Once you have downloaded the jar, just go to File->import settings and load that jar.
Friday, October 14, 2016
Grails3 GORM running MongoDB
Had some issues getting Mongo to work with Grails3 based on this doc, ended up creating an example project of it all working
Feel free to download, have a look
Feel free to download, have a look
Spock data driven testing with interactions (Mocks)
You can do data driven testing with Mocks and interactions, the key is that your interaction should be in the setup: block
For Example
@Unroll def "createOtherField test to see if label override works #fieldName override(#fieldLabel) == #resultName"() { setup: FormFieldMapManager formFieldMapManager = Mock() String onlineFormId = '1' List<LabelValue> otherFields = [] 1*formFieldMapManager.getMappedFields(onlineFormId, false) >> [new FormFieldMap()] expect: List<LabelValue> result = ProcessorUtil.createOtherField(formFieldMapManager, onlineFormId, otherFields, fieldName, 'fieldValue') result[0].label == resultName where: fieldName | fieldLabel || resultName 'fieldName' | null || 'fieldName' 'fieldName' | '' || 'fieldName' '' | null || '' 'fieldName' | 'OVERRIDE' || 'OVERRIDE' }
Tuesday, October 11, 2016
Intellij H2 Database viewer
For some reason to be able to see you tables in the Intellij H2 DB viewer you have append the following mv_store=false in your application.yml so the connection string looks like so:
jdbc:h2:file:./devDb;MVCC=TRUE;LOCK_TIMEOUT=10000;DB_CLOSE_ON_EXIT=FALSE;mv_store=false
Monday, September 12, 2016
Flatten a Map of Maps
A question came up that interested me, someone had a map that contains children of possibly lists of other maps, and they wanted to flatten all these maps to count all the values contained in this map of lists of maps.
I just used a recursive closure to collect all the values of the maps and lists, flatten that into a list and then an inject (fold) to count up the values.
def collector collector = {item -> item.collect {element -> element.value instanceof Map ? collector(element.value) : element.value}} assert 4 == collector([a: [q:1, w:1], b: [e:1], c: 1]).flatten().inject(0) { temp, val -> temp + val.value} assert 3 == collector([a: [q:1, w:[z:1, x:1]]]).flatten().inject(0) { temp, val -> temp + val.value}
Sunday, September 11, 2016
Grails logging debug from your controller logback.groovy
To get your controllers and services logging debug messages edit your logback.groovy. Just add your package structure, for instance if your package structure was com.myapp
root(ERROR, ['STDOUT']) // Sets log level of all logger('grails.app.controllers.com.myapp', DEBUG, ['STDOUT'], false) // Turn on debug for all your controllers logger('grails.app.services.com.myapp', DEBUG, ['STDOUT'], false) // Turn on debug for all your services
Tuesday, June 28, 2016
Rest API Docs Swagger
I had a lot of problems trying to get swagger to work, finally found this resource which sort of worked for me.
First I started getting
The test UserController, User domain worked. But when I added a very simple class of my won it would render on the http://localhost:8080/api page but clicking it did not bring down it operations.
Okay found the reason. For Swaggy to work you need a few crucial things:
First I started getting
Error creating bean with name 'com.github.rahulsom.swaggydoc.ApiController': Injection of autowired dependencies failed;This was fixed by adding the following to depenedencies
compile "org.grails:grails-dependencies"
The test UserController, User domain worked. But when I added a very simple class of my won it would render on the http://localhost:8080/api page but clicking it did not bring down it operations.
Okay found the reason. For Swaggy to work you need a few crucial things:
- Your controller needs the @Api annotation
@Api(value = 'ApiFile', description = 'Anything') class ApiFileTypeController extends RestfulController { static responseFormats = ['json', 'xml'] ApiFileTypeController() { super(ApiFileType) } }
- Your UrlMapping needs the url for the resource
class UrlMappings { static mappings = { "/$controller/$action?/$id?(.$format)?"{ constraints { // apply constraints here } } "/filetypes"(resource: 'apiFileType') "/"(view:"/index") "500"(view:'/error') "404"(view:'/notFound') } }
Monday, June 27, 2016
Slack channel for Grails
Join the slack channel for Grails
here
here
Sunday, June 26, 2016
Grails3 Twitter Bootstrap installing a theme
So Grails 3 and twitter boostrap, where is the bootstrap plugin and how do I install a theme?
First there is no plugin (well there are some plugins that seem to modify your scaffoldin, fields plugin) but Grails 3 has bootstrap as standard really.
But you have bought a theme like Material and want to get it into your app.
Lets say we want to install the jQuery light theme your theme directory should have a structure similar to:
Copy the entire light directory into your grails directory at the assets location [app]/grails-app/assets
Rename it to material.
If you run the app, you should be able to access your theme material, with the urls like
http://localhost:8080/assets/index.html
http://localhost:8080/assets/css/demo.css
Now lets edit the material.gsp to take out content and render our grails app in there. Find the
And replace all the content in it so it looks like this. Basically nothing but including a body
Replace all links to css and js includes directories to point to the new assets directory in material.gsp so these links
Become these
Now your index.gsp page should render in this new theme
First there is no plugin (well there are some plugins that seem to modify your scaffoldin, fields plugin) but Grails 3 has bootstrap as standard really.
But you have bought a theme like Material and want to get it into your app.
Get Theme
So download the Material theme unpack it and run the setup (npm install).Lets say we want to install the jQuery light theme your theme directory should have a structure similar to:
--Export | +--AngularJs | +--Documenation | +--jQuery | +--dark | +--light | +--css | +--fonts | +--img | +--js | +--less | +--media | +--node_modules | +--vendors | Loads html
Copy the entire light directory into your grails directory at the assets location [app]/grails-app/assets
Rename it to material.
If you run the app, you should be able to access your theme material, with the urls like
http://localhost:8080/assets/index.html
http://localhost:8080/assets/css/demo.css
Material.gsp
Now take a material theme html page, like index.html and copy it into your [app]grails-app/views/layouts directory calling it something like material.gsp.Now lets edit the material.gsp to take out content and render our grails app in there. Find the
<section id="content">
And replace all the content in it so it looks like this. Basically nothing but including a body
<section id="content"> <g:layoutBody/> </section>
Replace all links to css and js includes directories to point to the new assets directory in material.gsp so these links
<link href="vendors/bower_components/fullcalendar/dist/fullcalendar.min.css" rel="stylesheet"> <script src="vendors/bower_components/jquery/dist/jquery.min.js"></script>
Become these
<link href="/assets/vendors/bower_components/fullcalendar/dist/fullcalendar.min.css" rel="stylesheet"> <script src="/assets/vendors/bower_components/jquery/dist/jquery.min.js"></script>
Use
Now we just need tell our page to use this new layout so go to your index.gsp and make the head look as follows (change the content)<head> <meta name="layout" content="material"/>
Next Steps
This just quickly shows you how to get a theme in, you still need to change the navigation and add whatever content you want, but it is a start
Sunday, June 19, 2016
Grails fiels f:table f:all
Grails uses the field plugin to generate templates for your GSP.
So for instance your gsp with
And the following will show a table view
But where do you start, it took me a while to find the default templates that are used, you can find them in the plugin.
So right here is the tables one:
So for instance your gsp with
Will show a form for all the fields on a Bean.<fieldset class="form"> <f:all bean="project"/> </fieldset>
And the following will show a table view
But what if you want to override the styling, that is easy!<f:table collection="${projectList}" />
But where do you start, it took me a while to find the default templates that are used, you can find them in the plugin.
So right here is the tables one:
<table> <thead> <tr> <g:each in="${domainProperties}" var="p" status="i"> <g:set var="propTitle">${domainClass.propertyName}.${p.name}.label</g:set> <g:sortableColumn property="${p.name}" title="${message(code: propTitle, default: p.naturalName)}" /> </g:each> </tr> </thead> <tbody> <g:each in="${collection}" var="bean" status="i"> <tr class="${(i % 2) == 0 ? 'even' : 'odd'}"> <g:each in="${domainProperties}" var="p" status="j"> <g:if test="${j==0}"> <td><g:link method="GET" resource="${bean}"><f:display bean="${bean}" property="${p.name}" displayStyle="${displayStyle?:'table'}" /></g:link></td> </g:if> <g:else> <td><f:display bean="${bean}" property="${p.name}" displayStyle="${displayStyle?:'table'}" /></td> </g:else> </g:each> </tr> </g:each> </tbody> </table>
Wednesday, June 15, 2016
Debugging Grails 3 in Intellij 2016
I got stuck trying to edit run/debug configuration in Intellij to get my Grails project to debug. There where lots of posts about forks etc, etc.
But it is much simpler than that.
Just go to
There we go
Intellij will remember these and you can get to them quick in the Build menu
But it is much simpler than that.
Just go to
grails-app/init/webtracker.api/Application
and right click on Application and select Debug 'Application.main()'
There we go
Intellij will remember these and you can get to them quick in the Build menu
Tuesday, June 14, 2016
Grails log your hibernate queries
To log the Hibernate queries that your app is making merely add these to your logback.groovy
logger('org.hibernate.SQL', DEBUG, ['STDOUT'], false) logger('org.hibernate.type', TRACE, ['STDOUT'], false)The false eliminated duplicate entries
Legacy DB, Grails & Domain Classes
When having to build Grails apps around a legacy DB, this plugin is a great start.
The DB reverse engineer plugin (works with Grails 3)
It is a good idea to create a Integration test to just check you can access these tables. The integration test will be run on your development envrionment and you will need to have some data in there. Be careful obviously as it is bad practise to rely on existing data, but this helped me get all the mappings properly wired up.
Start with something as simple as:
I ran into a few stumbling blocks, all easily overcome
In my case the auto timestamping did not work out the box (as column names where different), but that was incredibly easy to fix.
Here is my Domain Class snippet
I started getting this error
The DB reverse engineer plugin (works with Grails 3)
It is a good idea to create a Integration test to just check you can access these tables. The integration test will be run on your development envrionment and you will need to have some data in there. Be careful obviously as it is bad practise to rely on existing data, but this helped me get all the mappings properly wired up.
Start with something as simple as:
package com.webtracker.api.prodcat import com.webtracker.api.Company import com.webtracker.api.Project import com.webtracker.api.WpActivationKey import grails.test.mixin.integration.Integration import grails.transaction.Rollback import spock.lang.Specification /** * Sanity domain Integration tests, uses development DB * * Created by demian on 14/06/16. */ @Integration @Rollback class DomainSpec extends Specification{ def setup() { } def cleanup() { } void "Can we list and load an activation key"() { when: def keys = WpActivationKey.list() def key1 = WpActivationKey.get keys[0].id def key2 = WpActivationKey.findByActivationKey keys[0].activationKey then: keys.size() > 0 key1 == key2 } void "Can we list and load a company"() { when: def companies = Company.list() def company1 = Company.get companies[0].id def company2 = Company.findByName companies[0].name then: companies.size() > 0 company1 == company2 } void "Can we list and load a project"() { when: def projects = Project.list() then: projects.size() > 0 } }
I ran into a few stumbling blocks, all easily overcome
In my case the auto timestamping did not work out the box (as column names where different), but that was incredibly easy to fix.
Here is my Domain Class snippet
Date dateCreated Long projectId static mapping = { version false } static constraints = { activationKey maxSize: 100, unique: true dateCreated column: 'created_date' }
I started getting this error
Caused by: java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.TimestampThis is because that is a valid SQL date but not in Gorm, this was fixed by appending the following to application.yml datasource:url: connection string
?zeroDateTimeBehavior=convertToNull
Intellij YES
After years of working in Eclipse and Sublime 3 I decided to give Intellij a chance.
I am very impressed.
I am not much of a fan of IDE's that do a lot of magic as I find it leads to lazy programming, and Intellij does a LOT of magic. But it is very very good at it's magic.
The plugins are of superb quality.
So impressed I bought it.
It even has groovy repl debugging
I also find it faster than eclipse (though I did recently change to an SSD, but I also used it on a regular HD) It also works great in Ubuntu
I am not much of a fan of IDE's that do a lot of magic as I find it leads to lazy programming, and Intellij does a LOT of magic. But it is very very good at it's magic.
The plugins are of superb quality.
So impressed I bought it.
It even has groovy repl debugging
I also find it faster than eclipse (though I did recently change to an SSD, but I also used it on a regular HD) It also works great in Ubuntu
Back in Grails World and So Happy (Interceptor)
I have the opportunity to develop some in Grails again and I am just so happy. Just a breath of fresh air.
Had to build a simple token authentication for a restful web service.
Ended up with this code using the Grails 3 Interceptor.
I find it readable, concise and clear. (By the way generated this code below with hilite.me great tool)
Just remember to make your Domain class cacheable so you do not have to query all the time
Had to build a simple token authentication for a restful web service.
Ended up with this code using the Grails 3 Interceptor.
I find it readable, concise and clear. (By the way generated this code below with hilite.me great tool)
package com.webtracker.api.prodcat import grails.compiler.GrailsCompileStatic import grails.converters.JSON import org.apache.catalina.connector.Response /** * This method is expensive as it can be called before every controller */ @GrailsCompileStatic class TokenInterceptor { TokenInterceptor() { matchAll() } boolean before() { if (params?.apikey) { WpActivationKey key = WpActivationKey.findByActivationKey(params?.apikey) if (key) { true } else { response.status = Response.SC_FORBIDDEN render([errors: ['api key not valid']] as JSON) false } } else { response.status = Response.SC_FORBIDDEN render([errors: ['no api key specified']] as JSON) false } } boolean after() { true } void afterView() { // no-op } }
Just remember to make your Domain class cacheable so you do not have to query all the time
@Cacheable("activationKeys")
Subscribe to:
Posts (Atom)