Homebrew commands for mac

I had to switch to Homebrew when we got Mavericks OSX 10.9

Update Homebrew

brew update

Upgrade outdated formulas

brew upgrade

To see what old versions of a formula would be removed

brew cleanup -n

To remove old versions of a formula

brew cleanup

Posted in Mac | Leave a comment

Hamcrest matcher – not

Have you ever had the case where you had to test for the negative of something? I was helping a teammate who wanted to test that a collection was not empty. It was pretty hard to track down how to test for that.

We settled on not()

import static org.hamcrest.Matchers.not;
...
...not(hasSize(0))

This was pretty hard to find. There wasn’t much documentation on negation.

Posted in hamcrest, Java, JUnit | Leave a comment

Regex validation with Jquery Validation Plugin

We needed several regex validations. I coded various custom validators with the regex included, so the regex could be re-used instead of typing the regex again and again.

        /**
         * Custom validator for letters (uppercase/lowercase)
         */
        $.validator.addMethod("lettersOnly", function (value, element) {
            return this.optional(element) || /^[a-zA-Z]+$/i.test(value);
        }, "Please enter letters only.");

        /**
         * Custom validator for numbers only (0-9)
         */
        $.validator.addMethod("numbersOnly", function (value, element) {
            return this.optional(element) || /^[0-9]+$/i.test(value);
        }, "Please enter numbers only.");

        /**
         * Custom validator for dates (0-9 and slashes).  Does not check month, day or year.
         */
        $.validator.addMethod("date", function (value, element) {
            return this.optional(element) || /^[0-9/]+$/i.test(value);
        }, "Please enter dates only.");

        /**
         * Custom validator for phone numbers (0-9, (, ) and -).  Does not check number of digits, etc.
         */
        $.validator.addMethod("phone", function (value, element) {
            return this.optional(element) || /^[0-9()-]+$/i.test(value);
        }, "Please enter dates only.");

        /**
         * Custom validators for letters and numbers only.  Uppercase/lowercase letters and numbers (0-9).
         */
        $.validator.addMethod("lettersAndNumbersOnly", function (value, element) {
            return this.optional(element) || /^[a-zA-Z0-9]+$/i.test(value);
        }, "Please enter letters and numbers only.");

Here is an example of how the validation was wired in via the rules section of the Jquery validation plugin

            rules: {
                firstName: {
                    required: true,
                    minlength: 1,
                    maxlength: 32,
                    lettersOnly: true
                },
Posted in javascript, JQuery | Tagged , , , | Leave a comment

Injecting value from Spring Properties in Java

This is so easy, but I rarely use it and always forget how to use it. This is how you define a properties:

<util:properties id="commonProperties" location="classpath:common-dev.properties"/>

The contents of the properties file is:

hostUrl=my.host.com

To inject it into a class:

    @Value("#{commonProperties.hostUrl}")
    private String hostUrl;
Posted in Java, Spring | Tagged , , | Leave a comment

JDK setting on Mac OS X Maverick causing you pain?

I found a very useful link

http://www.jayway.com/2014/01/15/how-to-switch-jdk-version-on-mac-os-x-maverick/

I added the following to my .profile and typed setjdk 1.7 at the command prompt. Problem solved.

function setjdk() {  
  if [ $# -ne 0 ]; then  
   removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'  
   if [ -n "${JAVA_HOME+x}" ]; then  
    removeFromPath $JAVA_HOME  
   fi  
   export JAVA_HOME=`/usr/libexec/java_home -v $@`  
   export PATH=$JAVA_HOME/bin:$PATH  
  fi  
 }  
 function removeFromPath() {  
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")  
 }
setjdk 1.7
Posted in Bash, OS/X | Tagged , , , | Leave a comment

Mirroring Maven Dependencies

The benefit of having a local Maven repository is that only one developer suffers the delay of the network traffic requests to repo1. If you have a local maven repository and your developers have mirrors setup in their settings.xml

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
    <mirrors>
        <mirror>
            <id>artifactory</id>
            <mirrorOf>*</mirrorOf>
            <url>http://artifactory.cdinteractive.com:8080/artifactory/repo</url>
            <name>Artifactory</name>
        </mirror>
    </mirrors>
</settings>
Posted in Maven | 1 Comment

When the Spring Security Principal isn’t enough in a Spring MVC Controller

I had previously made a blog entry to retrieve the spring security principal via @AuthenticationPrincipal in a controller method.
Getting the Spring Security Principal in a Spring MVC Controller method.

That is useful if you need the username or the password. What do you do if you need more?

I made a @PersonPrincipal annotation to do more than @AuthenticationPrincipal

package com.cdi.igs.hub.spring;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation that binds a method parameter or method return value to the
 * {@link com.cdi.igs.dao.person.Person}. This is necessary to signal that the
 * argument should be resolved to the current user rather than a user that might
 * be edited on a form.
 *
 * @author norris.shelton
 * @since 3.2
 */
@Target({ ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PersonPrincipal {
}

I then made a PersonArgumentResolver that can handle the processing required for the @PersonPrincipal annotation. The resolver first looks in the session to see if the Person object is there. If the Person object still isn’t found, the Authentication object will be retrieved from the security context. The SecurityUtil we be used to retrieve the person by username if necessary.

package com.cdi.igs.hub.spring;

import com.cdi.igs.dao.person.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;


/**
 * Allows resolving the {@link com.cdi.igs.dao.person.Person} using the
 * {@link com.cdi.igs.hub.spring.PersonPrincipal} annotation. For example, the following
 * {@link org.springframework.stereotype.Controller}:
 *
 * <pre>
 * @Controller
 * public class MyController {
 *     @RequestMapping("/user/current/show")
 *     public String show(@PersonPrincipal Person person) {
 *         // do something with Person
 *         return "view";
 *     }
 * </pre>
 *
 * <p>
 * Will resolve the Person argument using
 * {@link com.cdi.igs.dao.person.Person} from the {@link javax.servlet.http.HttpSession} if the person is an
 * attribute, else will use the {@link org.springframework.security.core.context.SecurityContextHolder} to get the
 * information to retrieve the person from the {@link com.cdi.igs.dao.person.PersonRepository}.
 * If the {@link org.springframework.security.core.Authentication} or {@link org.springframework.security.core.Authentication#getPrincipal()} is
 * null, it will return null.
 * </p>
 *
 * @author norris.shelton
 * @since 3.2
 */
@Component
public final class PersonArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private SecurityUtil SecurityUtil;

    /** (non-Javadoc)
     * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#supportsParameter(org.springframework.core.MethodParameter)
     */
    public boolean supportsParameter(MethodParameter parameter) {
        return findMethodAnnotation(PersonPrincipal.class, parameter) != null;
    }

    /** (non-Javadoc)
     * @see org.springframework.web.method.support.HandlerMethodArgumentResolver#resolveArgument(org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest, org.springframework.web.bind.support.WebDataBinderFactory)
     */
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest,
                                  WebDataBinderFactory binderFactory)
    throws Exception {
        Person person = null;

        // get "person" out of the session
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        HttpSession session = request.getSession(false);
        if (session != null) {
            person = (Person) session.getAttribute("person");

        }

        // if not found in the session, get by using the authenticated principal
        if (person == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            person = SecurityUtil.getPersonByAuthentication(authentication);

            // if found, store in the session for next time
            if (person != null && session != null) {
                session.setAttribute("person", person);
            }
        }
        return person;
    }

    /**
     * Obtains the specified {@link java.lang.annotation.Annotation} on the specified {@link org.springframework.core.MethodParameter}.
     *
     * @param annotationClass the class of the {@link java.lang.annotation.Annotation} to find on the {@link org.springframework.core.MethodParameter}
     * @param parameter the {@link org.springframework.core.MethodParameter} to search for an {@link java.lang.annotation.Annotation}
     * @return the {@link java.lang.annotation.Annotation} that was found or null.
     */
    private <T extends Annotation> T findMethodAnnotation(Class<T> annotationClass, MethodParameter parameter) {
        T annotation = parameter.getParameterAnnotation(annotationClass);
        if(annotation != null) {
            return annotation;
        }
        Annotation[] annotationsToSearch = parameter.getParameterAnnotations();
        for(Annotation toSearch : annotationsToSearch) {
            annotation = AnnotationUtils.findAnnotation(toSearch.annotationType(), annotationClass);
            if(annotation != null) {
                return annotation;
            }
        }
        return null;
    }
}

The SecurityUtil is pretty simple. Given an Authentication object, retrieve the username property and use that to retrieve a Person object.

package com.cdi.igs.hub.spring;

import com.cdi.igs.dao.person.Person;
import com.cdi.igs.dao.person.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;

/**
 * Spring security related tools.
 * @author norrisshelton
 */
@Component
public class SecurityUtil {

    @Autowired
    private PersonRepository personRepository;

    /**
     * Retrieves the person object associated with the given authentication.
     * @param authentication Represents the token for an authentication request
     * @return person object, if one could be found
     */
    public Person getPersonByAuthentication(Authentication authentication) {
        Person person = null;
        if (authentication != null) {
            User user = (User) authentication.getPrincipal();

            if (user != null) {
                // get the person from the database and store in the session
                person = personRepository.findByUserName(user.getUsername());
            }

        }
        return person;
    }
}

I then registered the PersonArgumentResolver with the other argument resolvers for the Spring MVC framework.

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/mvc      http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- Needed for Spring MVC Mockito tests in addition to the production context-->
    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver"/>
            <bean class="com.cdi.igs.hub.spring.PersonArgumentResolver"/>
        </mvc:argument-resolvers>
    </mvc:annotation-driven>

</beans>
Posted in Java, Spring, Spring MVC, Spring Security | 3 Comments