Fork me on GitHub

Sunday, 3 February 2013

Presents from DZone

,

Few days ago I've received awesome present from DZone.com team for contribution. Not sure if there are anything that can motivates more to contribute and write. Presents are really nice but I would say the most valuable for me was such interest and acknowledgment. From the letter it is seen that currently there are 650K members and audience over 3 millions visitors. I am reading DZone for years and always was exited about quality of content, but now I am exited to be part of contributors team. With all my respect I want to say thank you to DZone team for creating, maintaining and making better such great resource.














One of the most interesting presents can not be pictured. It is discount from amazing publisher Manning for their Early Access Program.

Read more

Wednesday, 24 October 2012

Deleting grails domain entity without fetching it

,

So many times I've seen how people working with Hibernate and complaining how slow it is. What I actually see, is how people do not care about tools that they are using. They have strange assumption if tool supposed to their life easier then it supposes to 100% easier and no reason to read posts about such tool or investigate how it can be configured.

Here is only on tip how to avoid useless selects hibernate or Grails GORM. Imaging you have an application that manipulates some data, lets say Comments. There is also controller or some API to delete one comment. If request comes from somewhere outside you application usually it looks like delete something with id=1.
http://localhost/comments/delete/1

Implementation of controller usually looks like
    def deleteComment() {
        def commentId = params.long('id')
        def comment = Comment.findById(commentId)
        comment?.delete()
    }
So bad part on this example is that we fetch from database entity that we do not need at all. We want to delete it. Hibernate and so GORM are working objects and not with parts of its fields. But it doesn't mean that you cannot do it, just use HQL. Here is simple HQL that will generates pure delete SQL query.
Comments.executeUpdate("delete from Comments where id = :id", [id:commentId])
Of cause you would like to write such code whenever you will need to delete entity, so we will add dynamic method to each Domain class in our application. Please add next code to your BootStrap.groovy
    def grailsApplication

    def init = { servletContext ->
        grailsApplication.domainClasses.each {def domain ->
            domain.metaClass.static.deleteById = {def id ->
                executeUpdate("delete from ${domain.name} where id = :id", [id:id])
            }
        }
    }
Now each of your domain class has the method deleteById, and our example became
    def deleteComment() {
        def commentId = params.long('id')
        Comment.deleteById(commentId)
    }
You can use this Grails plugin https://github.com/grygoriy/grails_gorm_utils that adds this method for you. Enjoy!
Read more

Saturday, 6 October 2012

Prevent brute force attack with Spring Security

,
Spring Security can do lot of stuff for you. Account blocking, password salt. But what about brute force blocker. That what you have to do by yourself. Fortunately spring is quite flexible framework so it is not a big deal to configure it.

Let me show you little guide how to do this for Grails application.

First you have to enable springSecurityEventListener in your Config.groovy
grails.plugins.springsecurity.useSecurityEventListener = true

then implement listeners
in /src/bruteforce create classes
/**
Registers all failed attempts to login. Main purpose to count attempts for particular account ant block user

*/
class AuthenticationFailureListener implements ApplicationListener {

    LoginAttemptCacheService loginAttemptCacheService

    @Override
    void onApplicationEvent(AuthenticationFailureBadCredentialsEvent e) {
        loginAttemptCacheService.failLogin(e.authentication.name)
    }
}

next we have to create listener for successful logins 
in same package
/**
 Listener for successfull logins. Used for reseting number on unsuccessfull logins for specific account
*/
class AuthenticationSuccessEventListener implements ApplicationListener{

    LoginAttemptCacheService loginAttemptCacheService

    @Override
    void onApplicationEvent(AuthenticationSuccessEvent e) {
        loginAttemptCacheService.loginSuccess(e.authentication.name)
    }
}
We were not putting them in our grails-app folder so we need to register these classes as spring beans.
Add next lines into grails-app/conf/spring/resources.groovy
beans = {
    authenticationFailureListener(AuthenticationFailureListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')
    }

    authenticationSuccessEventListener(AuthenticationSuccessEventListener) {
        loginAttemptCacheService = ref('loginAttemptCacheService')
    }
}
You've probably notice usage of LoginAttemptCacheService loginAttemptCacheService
Let's implement it. This would be typical grails service 
package com.grygoriy

import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.google.common.cache.LoadingCache

import java.util.concurrent.TimeUnit
import org.apache.commons.lang.math.NumberUtils
import javax.annotation.PostConstruct

class LoginAttemptCacheService {

    private LoadingCache attempts;
    private int allowedNumberOfAttempts
    def grailsApplication

    @PostConstruct
    void init() {
        allowedNumberOfAttempts = grailsApplication.config.brutforce.loginAttempts.allowedNumberOfAttempts
        int time = grailsApplication.config.brutforce.loginAttempts.time

        log.info "account block configured for $time minutes"
        attempts = CacheBuilder.newBuilder()
                   .expireAfterWrite(time, TimeUnit.MINUTES)
                   .build({0} as CacheLoader);
    }

    /**
     * Triggers on each unsuccessful login attempt and increases number of attempts in local accumulator
     * @param login - username which is trying to login
     * @return
     */
    def failLogin(String login) {
        def numberOfAttempts = attempts.get(login)
        log.debug "fail login $login previous number for attempts $numberOfAttempts"
        numberOfAttempts++

        if (numberOfAttempts > allowedNumberOfAttempts) {
            blockUser(login)
            attempts.invalidate(login)
        } else {
            attempts.put(login, numberOfAttempts)
        }
    }

    /**
     * Triggers on each successful login attempt and resets number of attempts in local accumulator
     * @param login - username which is login
     */
    def loginSuccess(String login) {
        log.debug "successfull login for $login"
        attempts.invalidate(login)
    }

    /**
     * Disable user account so it would not able to login
     * @param login - username that has to be disabled
     */
    private void blockUser(String login) {
        log.debug "blocking user: $login"
        def user = User.findByUsername(login)
        if (user) {
            user.accountLocked = true;
            user.save(flush: true)
        }
    }
}
We will be using CacheBuilder from google guava library. So please add next lines to BuildConfig.groovy
    dependencies {
        runtime 'com.google.guava:guava:11.0.1'
        }
And the last step we will add service configuration to Config.groovy
brutforce {
    loginAttempts {
        time = 5
        allowedNumberOfAttempts = 3
    }

That is it, you ready to run you application.
For typical java project almost everything will be the same. Same listeners and same services.

More about Spring Security Events
More about caching with Google guava

Grails users can simple use this plugin https://github.com/grygoriy/bruteforcedefender
UPD: Plugin now at http://grails.org/plugin/bruteforce-defender
Enjoy :)
Read more

Thursday, 4 October 2012

how to filter blogger rss

,
At some point when you would like to introduce you blog into some blog aggregators, you may notice that not of your posts matches aggregators topic. That is nice when you can choose posts manually but sometimes rss link will be required.
Few tips how to hack RSS in blogger.com
To get all posts with specific label use http://blog.blogspot.com/feeds/posts/default/-/labelname
Other nice things that can be done with url can be found on official google page
Read more

Sunday, 23 September 2012

Working with more then one grails version on same environment

,
Typically  you have your grails installed into some directory, created environment variable GRAILS_HOME and you are ready to go.

But what if you have few projects with different grails versions? You can have different reasons for that, but nevertheless you need it.

Here is short tip how this process can be simplified, example for Linux (Ubuntu).
Usually I install all applications to /usr/local/. Let's try to work with two grails versions 2.0.0 and 2.1.1(latest for this period)
So after unpacking we have
/usr/local/grails-2.0.0
/usr/local/grails-2.1.1
Let's create link to any version of Grails
ln -s /usr/local/grails-2.1.1 grails
Now we have
/usr/local  $ ls -ld grails*
lrwxrwxrwx  1 root root   23 Sep 23 15:05 grails -> /usr/local/grails-2.1.1
drwxr-xr-x 12 root root 4096 Dec 15  2011 grails-2.0.0
drwxr-xr-x 13 root root 4096 Sep 12 10:30 grails-2.1.1
and variable
echo $GRAILS_HOME
/usr/local/grails
Let's use simple script to change grails version. Mainly the only thing we have to do is to reassign link /usr/local/grails to version we would like to use
#!/bin/bash
#Script for changing grails version

grailsVersion=$1
rootPath="/usr/local"
grailsLinkPath=$rootPath"/grails"
grailsPath=$grailsLinkPath"-"$grailsVersion

echo stitching to version $1
#Check if directory with new grails version exists before doing anything
[ -d $grailsPath ] && rm $grailsLinkPath && ln -s $grailsPath $grailsLinkPath && echo "version switched to "$grailsVersion || echo 'Directory '$grailsPath' not found'
Read more

Monday, 6 February 2012

How to run Grails application on separate port

,
Some times you need to run your Grails app on different port and different context during development. Typical example when you are developing application that is divided into two or more apps (Services or other) So one application will run on 8080 and other for example 8081. That's allows you to run both applications in same time, work with them and debug

So we can change port with command
grails run-app -Dserver.port=8081

But it is not very convenient to do it all the time, so I prefer to change it in BuildConfig.groovy, just put next line somewhere in file
grails.server.port.http="8081"

and to change running context (default is localhost:8080/appname) add app.context= to application.properties. Next line will run Grails application at root context
app.context=/

Read more

Friday, 20 January 2012

How to debug tests maven test via Intellij Idea

,
Not alway you can run tests via IDE. Some time configs are complected and it is much easier just to type
>> mvn test

If you want to debug them, you can connect via remote.

1. run you test
>> mvn test -Dmaven.surefire.debug
maven will prepare environment and will wait for remote connection

2. connect via Idea



3. start debug

4. Now test will stop at your breakpoints. Profit!


Read more
 

Grygoriy Mykhalyuno Copyright © 2011 -- Template created by O Pregador -- Powered by Blogger