BaseController.java
/**
* Copyright 2014 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.mvc;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
public abstract class BaseController {
protected Logger LOG = LoggerFactory.getLogger(getClass());
protected static final String ANONYMOUS_USER = "anonymousUser";
protected static final String EXCEPTION_NOT_AUTHORIZED = "User is not authorized.";
protected static final String EXCEPTION_NOT_ORGANIZATION_MEMBER = "User is not a member of organization.";
@Autowired
protected MessageSource messageSource;
protected HttpServletRequest getRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
protected Locale getLocale() {
return LocaleContextHolder.getLocale();
}
protected boolean hasRole(String role) {
final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
for (final GrantedAuthority grantedRole : authentication.getAuthorities()) {
if (grantedRole.getAuthority().equals(role)) {
return true;
}
}
}
return false;
}
// logs exception and returns it's message
protected String simpleExceptionHandler(Throwable th) {
LOG.error(th.getMessage(), th);
return th.getMessage();
}
}