Access Denied Error when using XHR PUT and DELETE
Late one night, I was attempting to wire up a delete button on a Rails app using XHR. However, every time I attempted to make the XHR call, I saw AccessDenied in the server log and my session was un authenticated. Since it was late, I remapped it to a different URL and moved on.
However, the fact that this did not work still bothered me and when I revisited it after a good night’s sleep, the answer was quite obvious. My Ajax setup (copied from many Rails projects ago) looked like:
I was only setting the X-CSRF-Token on a POST. Therefore, when the server received the DELETE verb, it killed the session, thinking that something was afoul.
Changing that line to:
fixed the issue in the correct way.
Access Denied Error when using XHR PUT and DELETE
Late one night, I was attempting to wire up a delete button on a Rails app using XHR. However, every time I attempted to make the XHR call, I saw AccessDenied in the server log and my session was un authenticated. Since it was late, I remapped it to a different URL and moved on.
However, the fact that this did not work still bothered me and when I revisited it after a good night’s sleep, the answer was quite obvious. My Ajax setup (copied from many Rails projects ago) looked like:
I was only setting the X-CSRF-Token on a POST. Therefore, when the server received the DELETE verb, it killed the session, thinking that something was afoul.
Changing that line to:
fixed the issue in the correct way.
@Autowire with AOP Proxy Classes in Spring
This is an issue that gets me once every blue moon. Lets say that I have two classes DependencyClass and MainClass:
DependencyClass makes use of Spring’s @Transactional support, which is provided through AOP Proxies. This code works when I fire it up. However, if I add another implementation, and want to change the code to the following:
I get this nasty on the application startup:
NoSuchBeanDefinitionException: No matching bean of type [DependencyClass] found for dependency
The reason for this is simple. Within the Spring container, the concrete class DependencyClass has been replaced by a proxy. Therefore, as far as the system is concerned, there is no matching bean of type DependencyClass.
Inevitably, when this occurs, I spend too much time looking to other issues with my application context setup. However, the solution is easy and straightforward, once you realize what the problem is:
Basically, one needs to change the type back to an interface, then use named services and the @Qualifer annotation to inject the desired dependency.
Can Vertical Acuity Stop Your Site Losing Visitors?
It’s always fun to wake up in the morning and see Mashable do a write up on your company.
Vertical Acuity Quick Pitch: Vertical Acuity is a self-serve content syndication…
(Trying to) Sanely Deal with Maven Dependency Versions
One challenge of the maven way is how to sensibly version dependencies in a large, but constantly changing, project.
In the ideal maven world, each module is a highly defined project, with a highly structured team and releases only occur once the contract has been fully defined, tested, and whatever else enterprise teams do. In many realities, projects are simply logical constructs that don’t have strict contracts between the other module. The production environment is a mix of highly stable and rigorously tested products and experimental, pushed-constantly projects.
In this environment, automatic versioning of dependencies is both unnecessary and costly, and the dependencies need to be frozen at branch time of the stable, top-level projects. The other requirement is that the changes to the poms need to be minimal, so that any merge conflicts can be easily resolved.
The approach I’ve used, combining a few different ideas from the internet, is to remove any version numbers referencing internal projects from child modules. The versions are then included as properties in the parent project.
Freezing the set of dependencies for the module tree is then a three part process of: - Change the version number in the parent pom - Change the version properties of the parent pom - Change the parent version number in the child poms
To illustrate how this works, consider a project that has com.tejusparikh.web with a parent pom com.tejusparikh.
If you wanted to freeze the poms at 1.0.RELEASE then the poms would look like the following:
The point is that every child pom would have a property as it’s version number, making it easy to manage an arbitrary number of children.
Of course, you don’t want to have to update everything manually. The only method I’ve found to effectively use maven is to wrap it all in rake. Therefore, I’ve created a rake task to recurse the directories and change the version numbers.
Freezing all of your poms is as simple as calling rake mvn:version[/path/to/parent/dir,VERSION].
Getting Rid of My Personal Server

A few years ago, I stopped hosting my site on physical hardware and got a VPS from Linode. This worked really well for a few years, but I’ve gotten busy with other things and linux server administration really doesn’t interest me anymore.
Since I blog so infrequently, every time I was tempted to write a blog, Wordpress begged me to update it. By the time I installed the patches, updated the plugins, I blew the window and desire to write a blog post.
Therefore, through no real fault of Linode, I’m shutting down my VPS and moving to strictly to SaaS solutions.
The most important and challenging was moving the blogs to Tumblr. I wrote a small post for the tool I wrote.
The other challenge old SVN repositories off the machine. Since these are really just projects that I created years ago for very specific people and purposes, the cost of Github didn’t make sense. Instead I opted for the free plan on Bitbucket.
Finally, I am using Linode to handle some of my DNS. Since I moved my domains to namecheap, I just use their free domain service for most things. For anything that requires more, there’s always Amazon’s Route 53.
Just for kicks, I created my own “about-me” style page and tossed it out there with Amazon’s S3 for static websites.
Unless you are hosting a real application, there’s almost no reason to manage one’s own server. There are simply too many free or cheap alternatives that handle the administration overhead.
Using Noah to Configure Properties in your Spring Container
On a recent trip through our code base, I realized that there were multiple projects that used identical properties defined in files that sat on the file system. I find DRY is a superior pattern to copy and paste I wanted to consolidate these into a single location.
One approach would be to move them up a level in the source stack, and either rely on the properties being included in a jar or included via the build process. Both of these approaches suffer from some drawbacks and require rebuilds on a config change. Also the properties are still located all over the place, making it difficult to recover from mistakes or handle changes to the environment.
One of my co-workers, John Vincent, is currently developing Noah which is a lightweight node/service registry. However, there’s nothing that says you couldn’t use it as a centralized location for properties files.
I uploaded my properties file using Noah’s Ephemeral API. From there, it was a very trivial to make the properties available to Spring:
However, I didn’t like the url hardcoded in the configuration file. I’d prefer to have them configured through some properties that do live on the filesystem. In effect, each server would just need to know where to go to configure themselves. This required more advanced Spring trickery. Since all PropertyPlaceholderConfigurer instances implement PriorityOrder, they will be implemented before any property expansion has become. Therefore, you have to create your own Ordered bean that wraps a PropertyPlaceholderConfigurer. The following code is adapted from this discussion forum.
Then you configure it in your applicationContext.xml file like the following:
Now, you just have to manage one file on the filesystem that points to where the rest of the application’s configs can be found.
Import your wordpress blog into Tumblr
Last week, I searched rather fruitlessly for a way to import my wordpress blog into Tumblr. There were a few snippets and examples out on the web, but they all used the older API or required email addresses and passwords for authentication.
Since I couldn’t find what I was looking for, I opened up my IDE, fought with OAuth, and created a Wordpress to Tumblr importer.
Using the importer is pretty easy, you just need ruby and bundlr. The script is a sinatra application so you should will only need normal Tumblr OAuth access and not require XAuth approval.
Source: github.com
Re-evaluating Vaadin : A Difficult Framework for Building Web Applications
I just had to make the rather painful (well painful for my free time) decision to re-write the project that I and a team member had written in Vaadin with the old standby’s of JQuery, JSP’s, and Spring MVC. There was a lot of frustration that went into maintaining the project over the last year and it simply became very difficult to deliver what the product team wanted in a timely manner. The point of the post is not to bash the framework, but present the difficulties I encountered that made it unusable for us. I described the reasons we picked Vaadin in a previous post Vaadin. Many of the benefits still exist, but some of our core assumptions lead to major headaches down the line.
Integration with Spring
The vast majority of what we do and where we spend our time is on the server. We’ve built large libraries of internal functions that are exposed to other aspects of our application stack through Spring. We use Spring for security, talking to the database, configuring our remoting endpoints, and almost everything else. Unfortunately, you can’t dependency inject the Vaadin Application object.
The most sensible pattern is to create a static singleton that has the beans your application needs to access. However, this is very kludgy and somewhat defeats the purpose of dependency injection. Also, since the Application is one monolithic thing, it is impossible to make use of Spring Security filters unless you write the unauthenticated portions of your application outside of Vaadin or in another Vaadin container.
Another problem is most of the advanced DataContainers in Vaadin want to interact directly with the datasource. However, we have services in the middle that abstract access to those systems. Configuring Vaadin to accomplish this was more difficult than it needed to be, leaving the developer with two real choices, hack around Vaadin’s plugins or use basic containers that you initialize yourself.
Very Inconsistent Plugins
To give a specific example, one of the bigger challenges was integrating with the Lazy Query Container. Vaadin defines interfaces to adhere to, but many of them throw UnsupportedApplicationException, which makes it very difficult for the programmer to figure out what actually needs to be implemented for the desired behavior.
Odd Layout Behavior
When we started the project, we found layout to be very easy. Then we tried to make the look more like some of our existing products, which meant changing some of the default padding, margin, and sizes. All of this has to be done inside Vaadin or by overloading a Vaadin theme. Using normal stylesheets will often get you into trouble since it throws off Vaadin’s resize calculations.
In one concrete example, I added a Label with HTML content inside of a table. After making that change, there were nearly 30 empty rows at the bottom of that table. Getting rid of the Label made it work again. It took about 60 lines of Vaadin to accomplish what I had put together in 6 lines of HTML. Also Vaadin sets every DOM element to overflow: hidden so if one is not careful, all the elements will clip. Setting all the elements to have a different overflow value is not trivial due to…
Thousands of HTML elements
Open Firebug on even a simple-looking page in Vaadin and you will discover elements that are nested dozens of levels deep. Therefore, even changing something simple about the box model of a specific element involves changing the elements on the tree above it. Things that are taken for granted in today’s web world, such as adjusting the size of an element in Firebug, are impossible.
The raw number of elements has implications for the user experience as well. Vaadin depends heavily on javascript and javascript interpreters slow down with DOM size. Browsers also have issues rendering very large DOMs. One of our pages is a list of thumbnails with some meta information associated with them. We discovered that even on our Dual Core Macs with Google Chrome, the browser became unusable after 50 elements. Something like Google’s image search would not even be possible.
The other problem is that animations don’t work. The browser can’t re-render the page and move objects out of the way smoothly so any animation looks jerky and odd. I didn’t go through the effort of installing Google Chrome to get a IE6 experience.
Long Cycle Times
In a normal java webapp, you can deploy an exploded war and fix interface issues (JS, CSS, and JSPS) with a reload of a page and firebug. Since it’s impossible to adjust on the fly with firebug and everything in a Vaadin app is written in Java, even a 1px width change requires a rebuild/container restart. What was 3 minutes of firebug fiddling has just turned into 30 minutes of cycling. This would have been less of a problem had we stuck with only Vaadin supplied look and feel, but that is not always an option.
Widgets are Opaque
I had what I thought was a trivial requirement. I need to have a start date and an end date. The dates can only cover a 90-day window and the end date can only be 30 days after the start date. I wanted the date widget to disable any dates outside of this range. This turned out to be unsupported. I almost said “impossible,” but that’s not true. I spent about a day digging through Vaadin’s source to where it interacted with GWT, back to Vaadin’s source and so on until I discovered the small change I had to make to support this feature and wrote a custom widget. However, none of this was documented wasn’t part of the official API.
Whatever success I felt at finding the solution dissipated the when we attempted to upgrade the Vaadin version and discovered the the code that my new fancy date widget depended on had been removed and no substitue was readily available. Of course product didn’t want to drop the requirement, so we stuck with the old version with the working date widget.
Weird Problems with Statefulness
A Vaadin application is stateful, which has all sorts of implications. First, unless you explicitly write a “multi-windowed” application, you cannot have different sections open in different tabs. The state of one tab will update the other tab on a refresh. Also, it is incredibly easy to screw up your error handling so that the app never recovers and the user is forced to clear their cookies before they can use the application again. We’ve even encountered this with Vaadin generated restart dialogs.
The Straw that Broke the Camel’s Back
The point where I hit the “I can’t make this work anymore” button happened when we switched to using Vaadin through SSL. The problem with using Vaadin for authentication is everything is generated through Javascript, which renders the browser’s login manager useless.
Vaadin provides a solution to this problem with the LoginForm widget. Vaadin generates the action for this form not through a relative path, but by reading properties from the container. However, in our case, SSL is handled by NGINX and Jetty is blissfully unaware. This works 99.9% of the time, except for Vaadin’s LoginForm, which happily attempts to send the credentials over HTTP, while the rest of the application was HTTPS giving a very unfriendly dialog in Firefox.
Analysis
I think the primary problem with Vaadin and the challenges I experience was in picking something beyond what I was comfortable with for a relatively time-boxed project. I’m far more experienced with HTML, CSS, and Javascript than I am with Swing or any other thick frameworks.
Much of my early time with Vaadin was spent thinking back to how I used to do it and trying to reconcile it with how I’m used to doing it now. Vaadin is clearly not meant for developers that have even moderate web experience. Going with more native web technologies will be far easier and deliver better results. Vaadin may still be an option if you need a team of Swing (or maybe Android?) developers to build web applications, but I don’t have enough experience with those frameworks to pass judgement.
If you’ve had some experience with Vaadin, I’d love to hear your thoughts as well. It’s a framework that gets mentioned frequently among teams looking to deliver web solutions. Know where it has succeeded would be just as enlightening as me sharing my issues with it.
Logging Standard Exceptions with Spring AOP
One of the challenges of working on a large system with multiple developers is the management and handling of application errors and exceptions. Often, developers get frustrated with managing typed exceptions and all interfaces either throw or catch Exception. Another common approach is to change all exceptions to RuntimeException to avoid cluttering interfaces. An alternative approached is described in this paper by Andy Longshaw. His approach breaks exceptions into two distinct hierarchies, domain and system. Domain errors caused by logical faults in the application, such as a zero being passed as a divisor to a function. System errors are errors caused through the interaction with other components, like a network timeout when attempting to communicate with the database. Both exception types are checked exceptions, which means they must be caught and handled by each layer of the application. He presents guidelines on when and at which layer each type of exception should be logged. If you are using Java the obvious drawback of using checked exceptions everywhere is that each layer will be filled with code that looks like the following:
try {
service.doApiCall();
} catch(DomainException e) {
log.error("Domain exception occurred", e);
} catch(SystemException e) {
log.error("System exception occurred", e);
}
The duplication of handling of api exceptions can easily be handled with a custom annotation and Spring AOP.
The first step is to create the Boundary logging annotation. This annotation describes where exceptions should be logged.
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.METHOD})
public @interface BoundaryLogger {
}
Next, we need to create the interceptor. Along with just logging exceptions, I also choose to log the api calls. There are a few steps to creating an Aspect that can be used by Spring-AOP.
First added the @Aspect annotation to the class declaration.
@Service // make this available as a spring bean
@Aspect // tell spring this class is an aspect
public class BoundaryLoggingInterceptor {
Next, create a method that tells the Aspect to do something before the underlying method, annotated with @BoundaryLogger, is called. In this example, it’s to log the method invocation.
@Before("@annotation(net.vijedi.springlogging.interceptor.BoundaryLogger)")
public void logInvocation(JoinPoint jp) {
Similarly, triggering the aspect at method end can be handled with:
@AfterReturning(
pointcut = "@annotation(net.vijedi.springlogging.interceptor.BoundaryLogger)",
returning = "retVal")
public void logComplete(JoinPoint jp, Object retVal) {
The one we are especially interested in for this purposes of this blog post is exception logging. This is the entire method for logging exceptions:
@AfterThrowing(
pointcut = "@annotation(net.vijedi.springlogging.interceptor.BoundaryLogger)",
throwing = "ex"
)
public void processException(JoinPoint jp, Throwable ex) throws SystemException, DomainException {
if(ex instanceof SystemException) {
// System exceptions were logged at source
// do not log the exception, just the return
logReturn(jp, getLog(jp));
throw (SystemException) ex;
} else if(ex instanceof DomainException) {
logException(jp, ex);
throw (DomainException) ex;
} else {
logException(jp, ex);
throw new DomainException(ex);
}
}
The logException method is very simple:
private void logException(JoinPoint jp, Throwable ex) {
Log log = getLog(jp);
log.error(ex.getMessage(), ex);
logReturn(jp, log);
}
How the logger is obtained is very important for accurate logging. Otherwise, it will appear that all logging messages are coming from the interceptor and not from the underlying method. Along with the confusion this could cause, it will also make it harder to use automatic log analyzers. However, it is very easy to get a logger in the context of the underlying class.
protected Log getLog(JoinPoint jp) {
return LogFactory.getLog(jp.getTarget().getClass());
}
Once the Aspect has been created, the final step is to tell spring what to do when it encounters the annotation @BoundaryLogger.
There are four steps, tell spring to use annotations to configure the environment, to scan the packages the annotations are in, and to create the aop environment.
This is all that’s need to use annotations for logging at the tier boundaries. The complete code for the example is available at my Spring Boundary Logging repo on Github.