com.formkiq.server.api.AbstractRestController Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of formkiq-server Show documentation
Show all versions of formkiq-server Show documentation
Server-side integration for the FormKiQ ios application
package com.formkiq.server.api;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.util.StringUtils;
import com.formkiq.server.service.PreconditionFailedException;
import javassist.bytecode.stackmap.TypeData.ClassName;
/**
* Abstract Rest Services controller.
*
*/
public abstract class AbstractRestController {
/** Valid Accept Header. */
public static final MediaType ACCEPT_HEADER_V1
= MediaType.valueOf("application/vnd.formkiq.v1+json");
/** Logger. */
protected static final Logger LOG = Logger.getLogger(ClassName.class
.getName());
/**
* Converts Token to Int.
* @param token {@link String}
* @return int
*/
protected int convertToken(final String token) {
int next = -1;
if (!StringUtils.isEmpty(token)) {
try {
next = Integer.parseInt(token);
} catch (NumberFormatException e) {
throw new PreconditionFailedException("invalid next token");
}
}
return next;
}
/**
* @param request HttpServletRequest
* @return int
*/
protected int getApiVersion(final HttpServletRequest request) {
String accept = request.getHeader("Accept");
if (accept.equals(ACCEPT_HEADER_V1.toString())) {
return 1;
}
throw new InvalidMediaTypeException(
"invalid accept header, must be " + ACCEPT_HEADER_V1);
}
/**
* @return Authentication
*/
protected Authentication getAuthentication() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
return auth;
}
/**
* @return UserDetails
*/
protected UserDetails getUserDetails() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
if (auth instanceof OAuth2Authentication) {
OAuth2Authentication oauth = (OAuth2Authentication) auth;
return (UserDetails) oauth.getUserAuthentication().getPrincipal();
}
if (auth instanceof UsernamePasswordAuthenticationToken) {
return (UserDetails) ((UsernamePasswordAuthenticationToken) auth)
.getPrincipal();
}
return null;
}
}