Monthly Archives: May 2014

Running Spring Boot, Part I

Spring Boot offers a lot of functionality out of the box, but one thing that’s lacking is a standard way to run Spring Boot applications. This is not really the fault of Spring Boot, the question is really a larger one of how to run any Java program. Some people want to run it as a program, some as a service. Some want to run on Windows, some on Linux. There are so many deployment options that it would be impossible to generalize a solution for everybody, so this is the point at which people usually just do a little research and deploy and run the program in a way that they are the most comfortable.

This post will step through setting up a startup script for a spring boot application on Linux. This has been done before, but the aforementioned post example left out a couple steps.

One thing that needs to be done is to store the process id in a file, then the file can be tested to see if the application is running, and the id can be extracted to use a native system command to kill it. Spring Boot gives us a nice way to do this, note that the pid file can be set to be deleted on exit. In this case we are just leaving the pid file in the current directory, it may be more appropriate to place it in /var/run.

@EnableAutoConfiguration
@ComponentScan
public class Application {

    public static void main(String[] args) throws Exception {

        File pid = new File("app.pid");
        pid.deleteOnExit();
        
        SpringApplication app = new SpringApplication(Application.class);
        app.setShowBanner(false);
        app.addListeners(new ApplicationPidListener(pid));
        app.run(args);
    }
}

In the next post we will look at the script to run the application and take advantage of this pid file!

Leave a comment

Filed under Software Engineering

Authorizing the Current User with Spring Security and EL

After authentication, we usually want to authorize the actions of users in our system. Spring Security allows for this to be done with a simple annotation.

Initial Conditions

This presumes that Spring Security is already working and already being used to authenticate users. At this point we also presume that we have an implementation of UserDetails. Our goal is to authorize the currently logged in user using only the @PreAuthorize annotation on a web controller method.

Authorize!

Because @PreAuthorize uses Spring EL, we can use a simple string in the annotation to set authorization rules. Spring Security defines certain methods and objects available via EL. We can leverage these to do the authorization.

Spring Security provides an object called “principal” which – if you are using JPA authentication and have your own implementation of UserDetails – is really the UserDetails object defined in your code. Because the EL string is evaluated using reflection, all of the methods defined on your user details domain object are available in the EL string. For instance, maybe you have a domain object called CustomUserDetails with a method for determining authorization to read another domain object, such as .canReadDomainObject(Long id). We can reference this method directly in the Spring EL.

Observe:

@Controller
public class FooController {
    @PreAuthorize("isAuthenticated and principal.canReadDomainObject(#id")
    @RequestMapping(value="/foo/bar/{id}", method=RequestMethod.GET)
    public @RequestBody DomainObject String fooAction(@PathVariable Long id ) {
        return repository.findById(id);
    }
}

Note that we can reference the method parameter in the EL, but this requires an extra step. The full details are in the documentation for Spring Security EL, but the gist of it is that parameter information is not available via reflection by default, so we need to make that information available somehow. I found it easiest to just compile with the “-parameters” flag since I’m using Java 8. If you’re using an older version of Java, you can use the @P annotation to mark the parameter. The both work, feel free to use the technique that suits your taste.

Happy authorizing!

Leave a comment

Filed under Software Engineering

Accessing The Currently Logged In User With Spring Security/MVC

A common scenario is wanting to access the currently logged in user in the controller layer of a Spring MVC application. There is a way to do it by implementing a custom WebArgumentResolver, but with Spring Security 3.2 there is an easier way.

Initial Conditions

This presumes that Spring Security is already working and already being used to authenticate users. At this point we also presume that we have an implementation of UserDetails. Our goal is to pass the currently logged in user to a Spring MVC web controller method.

Your Secure Free Lunch

As of Spring Security 3.2, a web argument resolver and annotation is provided for specifying the logged-in-user to controller methods. All you have to do is specify the @AuthenticationPrincipal annotation on your method’s User argument, and Spring Security will automatically resolve that argument for you. In the code below, the CustomUserDetails is our own implementation of UserDetails.

Observe:

@Controller
public class FooController {
    @RequestMapping(value="/foo/bar", method=RequestMethod.GET)
    public String fooAction(@AuthenticationPrinciple CustomUserDetails user) {
        System.out.print.println(user.getName());
        return "foo";
    }
}

Happy userdetailing!

Leave a comment

Filed under Software Engineering

Rule 30

Rule 30

There is a cellular automaton rule called rule 30. We leave it as an exercise to the reader to determine why this is called rule 30, and why rules 1 through 29 were not as interesting. 🙂

At first glance, the rule may be hard to interpret. Essentially the values of each group of three cells determine the single value of the cell centered immediately beneath them.

In the test below, the 2D expected value array starts off as zeros and ones and gets converted to booleans… I figured it would be easier to visually inspect the array in that format rather than in “true” “false” format.

In the spirit of test first, here is a test, followed by some working code. Enjoy!

public class Rule30Test {

    private final Rule30 rule = new Rule30();
    private boolean[] initial;

    private boolean[][] expected;

    @Before
    public void setup() throws Exception {
        initial = new boolean[15];
        Arrays.fill(initial, false);
        initial[7] = true;

        int[][] expectedAsInts = new int[][] {
                {0,0,0,0,0,0,0,1,0,0,0,0,0,0,0},
                {0,0,0,0,0,0,1,1,1,0,0,0,0,0,0},
                {0,0,0,0,0,1,1,0,0,1,0,0,0,0,0},
                {0,0,0,0,1,1,0,1,1,1,1,0,0,0,0},
                {0,0,0,1,1,0,0,1,0,0,0,1,0,0,0}
        };

        expected = new boolean[5][15];
        for(int r=0; r < expectedAsInts.length; r++) {
            for(int c=0; c < expectedAsInts[r].length; c++){
                expected[r][c] = (expectedAsInts[r][c] == 1);
            }
        }
    }

    @Test
    public void testRule() throws Exception {

        boolean[] row = initial;

        for(int i=0; i < 5; i++) {
            Assert.assertTrue(Arrays.equals(expected[i], row));
            row = rule.mapRow(row);
        }
    }
}


public class Rule30 {

    public boolean[] mapRow(boolean[] row) {
        boolean[] newRow = new boolean[row.length];
        Arrays.fill(newRow, false);
        for(int i=1; i < newRow.length - 1; i++) {
            newRow[i] = map(row, i);
        }
        return newRow;
    }

    // white == off == false
    // requires boolean of length 3
    // int p is position, the center of what we can think of as a 3-element subarray
    private boolean map(boolean[] t, int p) {
        if( ! t[p-1] && ! t[p] && ! t[p+1]) {
            return false;
        }
        if( ! t[p-1] && ! t[p] &&   t[p+1]) {
            return true;
        }
        if( ! t[p-1] &&   t[p] && ! t[p+1]) {
            return true;
        }
        if( ! t[p-1] &&   t[p] &&   t[p+1]) {
            return true;
        }
        if(   t[p-1] && ! t[p] && ! t[p+1]) {
            return true;
        }
        if(   t[p-1] && ! t[p] &&   t[p+1]) {
            return false;
        }
        if(   t[p-1] &&   t[p] && ! t[p+1]) {
            return false;
        }
        if(   t[p-1] &&   t[p] &&   t[p+1]) {
            return false;
        }
        throw new IllegalArgumentException();
    }
}

1 Comment

Filed under Software Engineering