tv.arte.resteventapi.core.presentation.decoration.ResponseHeadersAspect.java Source code

Java tutorial

Introduction

Here is the source code for tv.arte.resteventapi.core.presentation.decoration.ResponseHeadersAspect.java

Source

package tv.arte.resteventapi.core.presentation.decoration;

/*
 * #%L
 * RestEventAPI
 * %%
 * Copyright (C) 2014 ARTE G.E.I.E
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of The MIT License (MIT) as published by the Open Source 
 * Initiative.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See The 
 * MIT License (MIT) for more details.
 * 
 * You should have received a copy of The MIT License (MIT) 
 * along with this program.  If not, see <http://opensource.org/licenses/MIT>
 * #L%
 */

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * A response header decorator used to inject values in the response header
 * 
 * @author Simeon Petev
 * @since 0.1
 */
@Component
@Aspect
public class ResponseHeadersAspect {

    @SuppressWarnings("unused")
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Around("execution(public * tv.arte.resteventapi.web.controllers.*.*(..)) && @annotation(tv.arte.resteventapi.core.presentation.decoration.HrefedLocationHeader)")
    public Object handleLocationHeaders(ProceedingJoinPoint pjp) throws Throwable {

        Object result = pjp.proceed();

        if (result != null && result instanceof Locationable) {
            String href = RestEventApiDecorationProvider
                    .getLocationUrl(((Locationable) result).getLocationableInstance());
            if (StringUtils.isNotBlank(href)) {

                HttpServletResponse response = null;

                if (pjp.getArgs() != null && pjp.getArgs().length > 0) {
                    for (Object methodArg : pjp.getArgs()) {
                        if (methodArg instanceof HttpServletResponse) {
                            response = (HttpServletResponse) methodArg;
                            break;
                        }
                    }
                }

                if (response != null) {
                    response.addHeader("Location", href);
                }
            }
        }

        return result;
    }

}