io.github.autsia.crowly.controllers.aspects.CheckPageSizeAspect.java Source code

Java tutorial

Introduction

Here is the source code for io.github.autsia.crowly.controllers.aspects.CheckPageSizeAspect.java

Source

/*
 * Copyright 2014 Dmytro Titov
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.github.autsia.crowly.controllers.aspects;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * Created by Dmytro on 27.01.14 at 22:11
 * Project: crowly
 */
@Aspect
@Component("checkPageSizeAspect")
public class CheckPageSizeAspect {

    public static final int DEFAULT_PAGE = 0;
    public static final int MIN_SIZE = 10;
    private static final Logger logger = Logger.getLogger(CheckPageSizeAspect.class);
    protected final List<Integer> allowedSizes = Arrays.asList(10, 50, 100);

    @Around("execution(* io.github.autsia.crowly.controllers.rest.UsersController.pages(..)) ||"
            + "execution(* io.github.autsia.crowly.controllers.rest.UsersController.users(..))")
    public Object checkPageSize(ProceedingJoinPoint joinPoint) throws Throwable {

        try {

            Integer page = (Integer) joinPoint.getArgs()[0];
            Integer size = (Integer) joinPoint.getArgs()[1];

            if (!allowedSizes.contains(size)) {
                page = DEFAULT_PAGE;
                size = MIN_SIZE;
            }

            joinPoint.getArgs()[0] = page;
            joinPoint.getArgs()[1] = size;

            return joinPoint.proceed(joinPoint.getArgs());

        } catch (Exception e) {

            logger.error(e);
            return joinPoint.proceed();

        }

    }

}