DownloadLogAspect.java

/*
 * Copyright 2021 Global Crop Diversity Trust
 *
 * 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 org.genesys.server.component.aspect;

import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.genesys.server.model.impl.DownloadLog;
import org.genesys.server.service.DownloadLogService;
import org.genesys.spring.TransactionHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class DownloadLogAspect {

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private DownloadLogService downloadLogService;

	@Around(value = "@annotation(org.genesys.server.component.aspect.DownloadEndpoint) && (execution(* org.genesys.server.api.*.*.*(..)) || execution(* org.genesys.server.api.*.*.*.*(..)))", argNames = "pjp")
	public Object aroundDownloading(ProceedingJoinPoint pjp) throws Throwable {
		Object proceed = pjp.proceed();

		String controllerName = pjp.getSignature().getDeclaringType().getSimpleName();
		String methodName = pjp.getSignature().getName();

		addLog(controllerName, methodName, request.getRequestURI());

		return proceed;
	}

	private DownloadLog addLog(String controllerName, String methodName, String url) {
		DownloadLog downloadLog = new DownloadLog();
		downloadLog.setController(controllerName);
		downloadLog.setMethod(methodName);
		downloadLog.setClientIp(getClientIp(request));
		downloadLog.setUrl(url);

		return TransactionHelper.executeInTransaction(false, () -> downloadLogService.create(downloadLog));
	}

	private String getClientIp(final HttpServletRequest request) {
		String remoteAddr = "";
		if (request != null) {
			remoteAddr = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(remoteAddr)) {
				remoteAddr = request.getRemoteAddr();
			}
		}
		return remoteAddr;
	}
}