package com.a.re.services.common.springmvc.converters;
import java.io.IOException;
import javax.xml.XMLConstants;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.log4j.Logger;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.oxm.MarshallingFailureException;
import org.springframework.oxm.UnmarshallingFailureException;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.stereotype.Component;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
@Configurable
@Component("xmlMessageConverter")
public class XmlMessageConverter extends AbstractHttpMessageConverter<Object> {
//=================================================
// Class Variables
//=================================================
private static final Logger _logger = Logger.getLogger(XmlMessageConverter.class);
//=================================================
// Instance Variables
//=================================================
@Autowired
private Jaxb2Marshaller _jaxb2Marshaller;
//=================================================
// Constructors
//=================================================
public XmlMessageConverter() {
super(MediaType.APPLICATION_XML, MediaType.TEXT_XML, new MediaType("application", "*+xml"), MediaType.parseMediaType("text/xml;charset=UTF-8"));
}
//=================================================
// Overridden Methods
//=================================================
@Override
public boolean supports(Class<?> iClazz) {
boolean isSupported = false;
if (!iClazz.getName().equals(String.class.getName())) {
isSupported = _jaxb2Marshaller.supports(iClazz);
}
return isSupported;
}
@Override
protected Object readInternal(Class<? extends Object> iClazz, HttpInputMessage iInputMessage) throws IOException, HttpMessageNotReadableException {
try {
SAXParserFactory aSAXFactory = SAXParserFactory.newInstance();
XMLReader anXmlReader = null;
try {
// security configuration
// limits on XML constructs to avoid conditions such as DOS attacks
aSAXFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
// do not include external entities and external parameter entities
aSAXFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
aSAXFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
// an error is thrown if request has DOCTYPE
aSAXFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
SAXParser aSAXParser = aSAXFactory.newSAXParser();
// prevent DOS attack by limiting the number of content model nodes
aSAXParser.setProperty("http://apache.org/xml/properties/security-manager", new org.apache.xerces.util.SecurityManager());
anXmlReader = aSAXParser.getXMLReader();
// prevent resolving external entities
EntityResolver aResolver = new EntityResolver() {
@Override
public InputSource resolveEntity(String iPublicId, String iSystemId) throws SAXException, IOException {
// always return empty input stream
return null;
}
};
anXmlReader.setEntityResolver(aResolver);
} catch (ParserConfigurationException anException) {
_logger.error("ERR_MSG=\"Failed to configure SAX parser\" EXCEPTION=", anException);
} catch (SAXException anException) {
_logger.error("ERR_MSG=\"Failed to configure SAX parser\" EXCEPTION=", anException);
}
SAXSource aSource = new SAXSource(new InputSource(iInputMessage.getBody()));
Object aResult = _jaxb2Marshaller.unmarshal(aSource);
if (!iClazz.isInstance(aResult)) {
throw new TypeMismatchException(aResult, iClazz);
}
return aResult;
} catch (UnmarshallingFailureException anException) {
throw new HttpMessageNotReadableException("Could not read [" + iClazz + "]", anException);
}
}
@Override
protected void writeInternal(Object iObject, HttpOutputMessage iOutputMessage) throws IOException, HttpMessageNotWritableException {
try {
_jaxb2Marshaller.marshal(iObject, new StreamResult(iOutputMessage.getBody()));
} catch (MarshallingFailureException ex) {
throw new HttpMessageNotWritableException("Could not write [" + iObject + "]", ex);
}
}
}
---------------------
package com.a.re.services.common.springmvc.converters;
import com.a.re.services.common.constants.DateFormatters;
import java.io.IOException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.stereotype.Component;
@Configurable
@Component("jsonMessageConverter")
public class JsonMessageConverter extends MappingJacksonHttpMessageConverter {
//=================================================
// Instance Variables
//=================================================
private ObjectMapper _objectMapper;
//=================================================
// Constructors
//=================================================
public JsonMessageConverter() {
// The intial assumption is to keep date formats consistent with web objects rest services
// we are using "MM-dd-yyyy'T'HH:mm:ss'Z'" from RERest which is DateFormatters.SQL_DATE_TIME_FORMATTER_SERVICES_TIMESTAMP
// turn's out web objects services return "yyyy-MM-dd'T'HH:mm:ss'Z'" and not the one used here
// we cannot consume dates in web objects sevices with this configuration
// need to decide the correct format or better use milliseconds
_objectMapper = new ObjectMapper();
// jaxb annotations
AnnotationIntrospector aJaxbIntrospector = new JaxbAnnotationIntrospector();
_objectMapper.setAnnotationIntrospector(aJaxbIntrospector);
// avoid writing null values in response
SerializationConfig aSerializationConfig = _objectMapper.getSerializationConfig();
aSerializationConfig.setSerializationInclusion(Inclusion.NON_NULL);
// write timestamps as milli seconds
aSerializationConfig.set(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, true);
_objectMapper.setSerializationConfig(aSerializationConfig);
DeserializationConfig aDeserializationConfig = _objectMapper.getDeserializationConfig();
DateFormat aDeserializerDateFormatter = DateFormatters.SQL_DATE_TIME_FORMATTER_SERVICES_TIMESTAMP;
aDeserializationConfig = aDeserializationConfig.withDateFormat(aDeserializerDateFormatter);
_objectMapper.setDeserializationConfig(aDeserializationConfig);
_objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
setObjectMapper(_objectMapper);
}
//=================================================
// Overridden Methods
//=================================================
/**
* (non-Javadoc)
* @see org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#writeInternal(java.lang.Object, org.springframework.http.HttpOutputMessage)
*/
@Override
public void writeInternal(Object iObject, HttpOutputMessage iOutputMessage) throws IOException, HttpMessageNotWritableException {
JsonGenerator aJsonGenerator = _objectMapper.getJsonFactory().createJsonGenerator(iOutputMessage.getBody(), JsonEncoding.UTF8);
aJsonGenerator.useDefaultPrettyPrinter();
try {
_objectMapper.writeValue(aJsonGenerator, iObject);
} catch (JsonGenerationException ex) {
throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
}
}
/**
* (non-Javadoc)
* @see org.springframework.http.converter.AbstractHttpMessageConverter#getSupportedMediaTypes()
*/
@Override
public List<MediaType> getSupportedMediaTypes() {
List<MediaType> aMediaTypes = new ArrayList<MediaType>();
aMediaTypes.add(new MediaType("application", "json", DEFAULT_CHARSET));
aMediaTypes.add(MediaType.APPLICATION_JSON);
return aMediaTypes;
}
/**
* (non-Javadoc)
* @see org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#canRead(java.lang.Class, org.springframework.http.MediaType)
*/
@Override
public boolean canRead(Class<?> iClazz, MediaType iMediaType) {
boolean isReadable = false;
if (!iClazz.getName().equals(String.class.getName())) {
isReadable = super.canRead(iClazz, iMediaType);
}
return isReadable;
}
/**
* (non-Javadoc)
* @see org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#canWrite(java.lang.Class, org.springframework.http.MediaType)
*/
@Override
public boolean canWrite(Class<?> iClazz, MediaType iMediaType) {
boolean isWritable = false;
if (!iClazz.getName().equals(String.class.getName())) {
isWritable = super.canRead(iClazz, iMediaType);
}
return isWritable;
}
//=================================================
// Accessors
//=================================================
}
-----------------------------
<!--ApplicationContext converters --> class="com.apple.re.services.common.springmvc.converters.UrlEncodedMessageConverter" />
<bean id="jsonConverter" class="com.apple.re.services.common.springmvc.converters.JsonMessageConverter" />
<bean id="xmlConverter" class="com.apple.re.services.common.springmvc.converters.XmlMessageConverter"/>
------------------------------------
package com.a.re.services.common.springmvc.handler;
import com.a.re.services.common.util.RRSRequestWrapper;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
/**
* Custom handler adapter
*
*/
@Configurable
public class RRSServicesHandlerAdapter extends AnnotationMethodHandlerAdapter {
//=================================================
// Class Variables
//=================================================
public static final String ACCEPT_ATTRIBUTE = "AcceptMediaType";
public static final String SUFFIX_XML = ".xml";
public static final String SUFFIX_JSON = ".json";
public static final String SUFFIX_PLIST = ".plist";
private static final Logger _logger = Logger.getLogger(RRSServicesHandlerAdapter.class);
//=================================================
// Overridden Methods
//=================================================
/* (non-Javadoc)
* @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#invokeHandlerMethod(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
*/
@Override
public ModelAndView invokeHandlerMethod(HttpServletRequest iRequest, HttpServletResponse iResponse, Object iHandler) throws Exception {
return super.invokeHandlerMethod(iRequest, iResponse, iHandler);
}
/**
* (non-Javadoc)
* @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#createHttpInputMessage(javax.servlet.http.HttpServletRequest)
*/
@Override
public HttpInputMessage createHttpInputMessage(HttpServletRequest iRequest) throws Exception {
List<MediaType> anAcceptedMediaTypes = getHeaders(iRequest).getAccept();
if (anAcceptedMediaTypes.isEmpty()) {
_logger.debug("MSG=\"No Accept header found\"" + "DEFAULT=xml" );
List<MediaType> aMediaTypeList = new ArrayList<MediaType>();
aMediaTypeList.add(MediaType.APPLICATION_XML);
anAcceptedMediaTypes = aMediaTypeList;
}
iRequest.setAttribute(ACCEPT_ATTRIBUTE, anAcceptedMediaTypes);
return new RRSRequestWrapper(iRequest, anAcceptedMediaTypes);
}
@SuppressWarnings("rawtypes")
public org.springframework.http.HttpHeaders getHeaders(HttpServletRequest iRequest) {
org.springframework.http.HttpHeaders aHeaders = new org.springframework.http.HttpHeaders();
for (Enumeration aHeaderNames = iRequest.getHeaderNames(); aHeaderNames.hasMoreElements();) {
String aHeaderName = (String) aHeaderNames.nextElement();
for (Enumeration aHeaderValues = iRequest.getHeaders(aHeaderName); aHeaderValues.hasMoreElements();) {
String aHeaderValue = (String) aHeaderValues.nextElement();
aHeaders.add(aHeaderName, aHeaderValue);
}
}
return aHeaders;
}
}
-------------------------------
package com.a.acp.security.dao;
import java.util.List;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import com.a.acp.core.base.das.jdbc.AbstractJdbcDao;
import com.a.acp.core.exception.DaoException;
import com.a.acp.security.vo.OauthClientServiceVO;
/**
*
*/
public interface OauthDAO extends AbstractJdbcDao{
/**
* @param serviceName
* @return
* @throws DaoException
*/
public List<OauthClientServiceVO> getClientServiceByName(String serviceName) throws DaoException;
/**
* @param clientServiceId
* @return
* @throws DaoException
*/
public Integer updateClientService(OauthClientServiceVO clientServiceVO) throws DaoException;
/**
* @param clientServiceVO
* @return
* @throws DaoException
*/
public Integer insertClientService(OauthClientServiceVO clientServiceVO) throws DaoException;
/**
* @param clientServiceId
* @return
* @throws DaoException
*/
public OauthClientServiceVO getClientServiceById(int clientServiceId) throws DaoException;
/**
* @return
* @throws DaoException
*/
public List<OauthClientServiceVO> getAllClientService() throws DaoException;
/**
* @return
* @throws DaoException
*/
public List<String> getAllServiceNames() throws DaoException;
/**
* @param clientServiceId
* @return
* @throws DaoException
*/
public Integer deleteClientService(int clientServiceId) throws DaoException;
/**
* @param accessTokenStr
* @return
* @throws DaoException
*/
public OAuth2AccessToken getAccessToken(String accessTokenStr) throws DaoException;
}
________________________________
package com.a.acp.security.dao.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.util.SerializationUtils;
import com.a.acp.core.base.das.jdbc.impl.AbstractJdbcDaoImpl;
import com.a.acp.core.constant.ErrorDescription;
import com.a.acp.core.constant.ExceptionType;
import com.a.acp.core.exception.DaoException;
import com.a.acp.core.util.MessageFormattor;
import com.a.acp.core.vo.json.ErrorVO;
import com.a.acp.security.dao.OauthDAO;
import com.a.acp.security.vo.OauthClientServiceVO;
/**
* OAUTH Security related database operations.
*
*/
public class OauthDAOImpl extends AbstractJdbcDaoImpl implements OauthDAO{
private static Logger logger = LoggerFactory.getLogger(OauthDAOImpl.class.getName());
/* (non-Javadoc)
* @see com.a.acp.security.dao.OauthDAO#getClientServiceByName(java.lang.String)
*/
public List<OauthClientServiceVO> getClientServiceByName(String serviceName) throws DaoException{
String queryStr = "SELECT * FROM oauth_clientservice WHERE service_name=:SERVICE_NAME";
List<Map<String, Object>> resultMapList = null;
try {
Map<String,Object> valueMap = new HashMap<String,Object>();
valueMap.put("SERVICE_NAME", serviceName);
resultMapList = executeJdbcQuery(queryStr,valueMap);
} catch (DaoException e) {
throw new DaoException(ExceptionType.EXCEPTION_SERVICE,e.getErrorVO());
}
if(resultMapList==null || resultMapList.size()==0){
return null;
} else{
List<OauthClientServiceVO> clientServiceList = new ArrayList<OauthClientServiceVO>();
for(Map<String, Object> resultMap : resultMapList ){
clientServiceList.add(createOauthClientServiceVO(resultMap));
}
return clientServiceList;
}
}
/* (non-Javadoc)
* @see com.a.acp.security.dao.OauthDAO#getAllService()
*/
public List<OauthClientServiceVO> getAllClientService() throws DaoException{
String queryStr = "SELECT * FROM oauth_clientservice ORDER BY service_name";
List<Map<String, Object>> resultMapList = null;
try {
resultMapList = executeJdbcQuery(queryStr,null);
} catch (DaoException e) {
throw new DaoException(ExceptionType.EXCEPTION_SERVICE,e.getErrorVO());
}
if(resultMapList==null || resultMapList.size()==0){
return null;
} else{
List<OauthClientServiceVO> clientServiceList = new ArrayList<OauthClientServiceVO>();
for(Map<String, Object> resultMap : resultMapList ){
clientServiceList.add(createOauthClientServiceVO(resultMap));
}
return clientServiceList;
}
}
/* (non-Javadoc)
* @see com.a.acp.security.dao.OauthDAO#getClientServiceById(int)
*/
public OauthClientServiceVO getClientServiceById(int clientServiceId) throws DaoException{
String queryStr = "SELECT * FROM oauth_clientservice WHERE clientservice_id=:clientservice_id";
List<Map<String, Object>> resultMapList = null;
try {
Map<String,Object> valueMap = new HashMap<String,Object>();
valueMap.put("clientservice_id", clientServiceId);
resultMapList = executeJdbcQuery(queryStr,valueMap);
} catch (DaoException e) {
throw new DaoException(ExceptionType.EXCEPTION_SERVICE,e.getErrorVO());
}
if(resultMapList==null || resultMapList.size()==0){
return null;
} else{
return createOauthClientServiceVO(resultMapList.get(0));
}
}
/* (non-Javadoc)
* @see com.a.acp.security.dao.OauthDAO#insertClientService(com.a.acp.security.vo.OauthClientServiceVO)
*/
public Integer insertClientService(OauthClientServiceVO clientServiceVO) throws DaoException{
String errorDescription = "";
if(clientServiceVO==null){
errorDescription = "Failed to insert to ACP_OAUTH_CLIENTSERVICE table because clientServiceVO is null. " ;
logger.error(MessageFormattor.errorFormat(this.getClass().getName(), "insertClientService", ExceptionType.EXCEPTION_DAO, errorDescription));
throw new DaoException(ExceptionType.EXCEPTION_DAO,
new ErrorVO(ErrorDescription.ERR_CD_DAO_INSERT,ErrorDescription.ERR_MSG_DAO_INSERT, errorDescription));
}
String queryStr = "INSERT INTO oauth_clientservice (created_date,updated_date,version, service_name, service_url, usertoken_required, url_filter_enable, service_description ) " +
"VALUES (:created_date,:updated_date,:version,:service_name,:service_url,:usertoken_required,:url_filter_enable,:service_description ) ";
Map<String,Object> valueMap = new HashMap<String,Object>();
Date currentDate = new Date();
valueMap.put("created_date", currentDate);
valueMap.put("updated_date", currentDate);
valueMap.put("version", 1);
valueMap.put("service_name", clientServiceVO.getServiceName());
valueMap.put("service_url", clientServiceVO.getServiceURL());
valueMap.put("usertoken_required", clientServiceVO.isUserTokenRequired());
valueMap.put("url_filter_enable", clientServiceVO.isUrlFilterFlag());
valueMap.put("service_description", clientServiceVO.getServiceDescription());
return executeJdbcUpdate(queryStr,valueMap);
}
public Integer deleteClientService(int clientServiceId) throws DaoException{
String queryStr = "DELETE FROM oauth_clientservice WHERE clientservice_id=:clientservice_id";
Map<String,Object> valueMap = new HashMap<String,Object>();
valueMap.put("clientservice_id", clientServiceId);
return executeJdbcUpdate(queryStr,valueMap);
}
public Integer updateClientService(OauthClientServiceVO clientServiceVO) throws DaoException{
String errorDescription = "";
if(clientServiceVO==null){
errorDescription = "Failed to update to oauth_clientservice table because clientServiceVO is null :";
logger.error(MessageFormattor.errorFormat(this.getClass().getName(), "insertClientService", ExceptionType.EXCEPTION_DAO, errorDescription));
throw new DaoException(ExceptionType.EXCEPTION_DAO,
new ErrorVO(ErrorDescription.ERR_CD_DAO_INSERT,ErrorDescription.ERR_MSG_DAO_INSERT, errorDescription));
}
String queryStr = "UPDATE oauth_clientservice SET updated_date=:updated_date,version=:version+1,service_name=:service_name,service_url=:service_url,usertoken_required=:usertoken_required" +
", url_filter_enable=:url_filter_enable, service_description=:service_description WHERE clientservice_id=:clientservice_id AND version=:version";
Map<String,Object> valueMap = new HashMap<String,Object>();
valueMap.put("updated_date", new Date());
valueMap.put("version", clientServiceVO.getVersion());
valueMap.put("service_name", clientServiceVO.getServiceName());
valueMap.put("service_url", clientServiceVO.getServiceURL());
valueMap.put("usertoken_required", clientServiceVO.isUserTokenRequired());
valueMap.put("url_filter_enable", clientServiceVO.isUrlFilterFlag());
valueMap.put("service_description", clientServiceVO.getServiceDescription());
valueMap.put("clientservice_id", clientServiceVO.getClientServiceId());
int i = executeJdbcUpdate(queryStr,valueMap);
return i;
}
public List<String> getAllServiceNames() throws DaoException{
String queryStr = "SELECT service_name FROM oauth_clientservice GROUP BY service_Name ORDER BY clientservice_ID";
List<Map<String, Object>> resultMapList = null;
try {
resultMapList = executeJdbcQuery(queryStr,null);
} catch (DaoException e) {
throw new DaoException(ExceptionType.EXCEPTION_SERVICE,e.getErrorVO());
}
if(resultMapList==null || resultMapList.size()==0){
return null;
} else{
List<String> serviceNameList = new ArrayList<String>();
for(Map<String, Object> resultMap : resultMapList ){
Object serviceNameObject = resultMap.get("service_name");
serviceNameList.add(serviceNameObject==null?"":(String)serviceNameObject);
}
return serviceNameList;
}
}
public OAuth2AccessToken getAccessToken(String accessTokenStr) throws DaoException{
String queryStr = "SELECT token FROM oauth_access_token where token_id=:access_token and token_status=1";
List<Map<String, Object>> resultMapList = null;
try {
Map<String,Object> valueMap = new HashMap<String,Object>();
valueMap.put("access_token", accessTokenStr);
resultMapList = executeJdbcQuery(queryStr,valueMap);
if(resultMapList==null || resultMapList.size()==0){
return null;
} else{
Map<String, Object> resultMap = resultMapList.get(0);
Object tokenObj = resultMap.get("token");
if(tokenObj==null){
return null;
}
byte[] tokenBytes = (byte[])tokenObj;
OAuth2AccessToken accessToken = SerializationUtils.deserialize(tokenBytes);
if(accessToken==null){
return null;
}
return accessToken;
}
} catch (DaoException e) {
throw new DaoException(ExceptionType.EXCEPTION_SERVICE,e.getErrorVO());
} catch (Exception e) {
String errorDescription = "Failed to get the access token from database. The error is : "+e.getMessage();
logger.error(MessageFormattor.errorFormat(this.getClass().getName(),
"executeNamedQuery", ExceptionType.EXCEPTION_DAO, errorDescription));
throw new DaoException(ExceptionType.EXCEPTION_DAO,
new ErrorVO(ErrorDescription.ERR_CD_DAO_QUERY,ErrorDescription.ERR_MSG_DAO_QUERY, errorDescription));
}
}
protected OAuth2AccessToken deserializeAccessToken(byte[] token) {
return SerializationUtils.deserialize(token);
}
private OauthClientServiceVO createOauthClientServiceVO(Map<String, Object> resultMap){
OauthClientServiceVO o = new OauthClientServiceVO();
Object clientServiceIdObject = resultMap.get("clientservice_id");
Object versionObject = resultMap.get("version");
Object serviceNameObject = resultMap.get("service_name");
Object serviceURLObject = resultMap.get("service_url");
Object tokenRequiredObject = resultMap.get("usertoken_required");
Object urlFilterFlagObject = resultMap.get("url_filter_enable");
Object descriptionObject = resultMap.get("service_description");
o.setClientServiceId(clientServiceIdObject==null?0:((Long)clientServiceIdObject).intValue());
o.setVersion(versionObject==null?0:(Integer)versionObject);
o.setServiceName(serviceNameObject==null?"":(String)serviceNameObject);
o.setServiceURL(serviceURLObject==null?"":(String)serviceURLObject);
o.setUserTokenRequired(tokenRequiredObject==null?false:((Integer)tokenRequiredObject)==1);
o.setUrlFilterFlag(urlFilterFlagObject==null?false:((Integer)urlFilterFlagObject)==1);
o.setServiceDescription(descriptionObject==null?"":(String)descriptionObject);
return o;
}
}
_______________________________________________
package com.a.acp.security.service;
import java.util.List;
import javax.annotation.Resource;
import javax.inject.Named;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.transaction.annotation.Transactional;
import com.a.acp.caching.service.CachingService;
import com.a.acp.core.constant.ErrorDescription;
import com.a.acp.core.constant.ExceptionType;
import com.a.acp.core.constant.RestConst;
import com.a.acp.core.exception.DaoException;
import com.a.acp.core.exception.ServiceException;
import com.a.acp.core.util.StringUtil;
import com.a.acp.core.vo.json.ErrorVO;
import com.a.acp.security.dao.OauthDAO;
import com.a.acp.security.vo.OauthClientServiceVO;
import com.a.acp.security.vo.UserRequestVO;
@Named
public class OauthService {
private static final ThreadLocal<UserRequestVO> userRequestVO_local = new ThreadLocal<UserRequestVO>();
@Resource
private CachingService cachingService;
@Resource
private OauthDAO oauthDAO;
private static Logger logger = LoggerFactory.getLogger(OauthService.class.getName());
/**
* @param authorizationStr
* @return
* @throws ServiceException
*/
public void validateToken(String authorizationStr) throws ServiceException {
OAuth2AccessToken token = null;
if (StringUtils.isBlank(authorizationStr)) {
String errorMSG = ErrorDescription.ERR_MSG_SECURITY_NO_TOKEN;
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_NO_TOKEN, ErrorDescription.ERR_MSG_SECURITY_NO_TOKEN, errorMSG);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION, errorVO);
} else {
String tokenValue = null;
if (authorizationStr.toLowerCase().startsWith(RestConst.REQ_PARAM_AUTHORIZATION_BEARER)) {
tokenValue = authorizationStr.substring(authorizationStr.indexOf(" ")).trim();
} else {
String errorMSG = ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN;
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_INVALID_TOKEN, ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN, errorMSG);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION, errorVO);
}
if(tokenValue==null){
String errorMSG = ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN;
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_INVALID_TOKEN, ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN, errorMSG);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION, errorVO);
}
boolean isFromDBFlag = false;
try {
token = (OAuth2AccessToken)cachingService.getMemcacheObject(tokenValue);
} catch (ServiceException e) {
String errorMSG = ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN+". Failed to get token from storage. Error detail: "+e.getErrorVO().getErrMsg()+" "+e.getErrorVO().getErrDescription();
logger.error(errorMSG);
//If the memecached has issue, we go to database to check the token.
token = getAccessTokenFromDB(tokenValue);
isFromDBFlag = true;
}
if (token == null) {
//If the token is null and it is retrieved from memcached, we also go to database and double check if the token is valid.
//In case the memecached is not working properly for some reasons.
if(!isFromDBFlag){
token = getAccessTokenFromDB(tokenValue);
}
if (token == null){
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_INVALID_TOKEN,ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN, ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}else{
try{
cachingService.setMemcacheObject(token.getValue(), 3600, token);
}catch(ServiceException e){
logger.error("Failed to set token to memcached. Error: "+e.getErrorVO().getErrDescription());
}
}
}
if (token.isExpired()) {
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_EXPIRED_TOKEN,ErrorDescription.ERR_MSG_SECURITY_EXPIRED_TOKEN, ErrorDescription.ERR_MSG_SECURITY_EXPIRED_TOKEN);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
} else {
UserRequestVO userRequest = new UserRequestVO(token);
Object grantTypeObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_GRANT_TYPE);
Object userNameObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_USERNAME);
Object emailObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_EMAIL);
Object userIdObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_USERID);
Object firstNameObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_FIRST_NAME);
Object lastNameObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_LAST_NAME);
Object clientIdObject = token.getAdditionalInformation().get(RestConst.TOKEN_REQUEST_CLIENT_ID);
Object resourceIdObject = token.getAdditionalInformation().get(RestConst.TOKEN_REQUEST_RESOURCE_ID);
Object vipSellerAllowedObject = token.getAdditionalInformation().get(RestConst.SECURITY_NAME_VIP_SELLER_ALLOWED);
userRequest.setGrantType(grantTypeObject==null?null:grantTypeObject.toString());
userRequest.setUsername(userNameObject==null?null:userNameObject.toString());
userRequest.setEmail(emailObject==null?null:emailObject.toString());
userRequest.setUserId(userIdObject==null?null:userIdObject.toString());
userRequest.setFirstName(firstNameObject==null?null:firstNameObject.toString());
userRequest.setLastName(lastNameObject==null?null:lastNameObject.toString());
userRequest.setClientId(clientIdObject==null?null:clientIdObject.toString());
userRequest.setAuthResource(resourceIdObject==null?null:resourceIdObject.toString());
userRequest.setVipSellerAllowed(vipSellerAllowedObject==null?null:vipSellerAllowedObject.toString());
userRequestVO_local.set(userRequest);
}
}
}
/**
* @param serviceName
* @param org_accessUri
* @param isAnonymousToken
* @return
* @throws ServiceException
*/
@Transactional(value="jdbc_appauthorize")
@SuppressWarnings("unchecked")
public void authorizeService(String path, String accessUri, boolean isAnonymousToken) throws ServiceException {
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_UNKNOWN_SERVICE_ENDPOINT,ErrorDescription.ERR_MSG_SECURITY_UNKNOWN_SERVICE_ENDPOINT,
ErrorDescription.ERR_MSG_SECURITY_UNKNOWN_SERVICE_ENDPOINT);
String serviceName = getServiceNameFromPath(path);
if(StringUtils.isEmpty(serviceName)){
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}
UserRequestVO userRequest = userRequestVO_local.get();
if(userRequest!=null){
userRequest.setSeviceName(serviceName);
}
if(StringUtil.isBlank(accessUri)){
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}else{
accessUri = accessUri.trim();
}
List<OauthClientServiceVO> clientServiceList = null;
Object cachedObject = null;
try{
cachedObject = cachingService.getMemcacheObject(RestConst.PRE_SERVICE_ENDPOINT_FLITER+serviceName);
}catch(ServiceException e){
logger.error("Failed to get service endpoint list from memcached. Error: "+e.getErrorVO().getErrDescription());
}
if(cachedObject!=null){
clientServiceList = (List<OauthClientServiceVO>)cachedObject;
}else{
try {
clientServiceList = oauthDAO.getClientServiceByName(serviceName);
} catch (DaoException e) {
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}
if(clientServiceList==null || clientServiceList.size()==0){
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}
try{
cachingService.setMemcacheObject(RestConst.PRE_SERVICE_ENDPOINT_FLITER+serviceName, 7200, clientServiceList);
}catch(ServiceException e){
logger.error("Failed to set service endpoint list to memcached. Error: "+e.getErrorVO().getErrDescription());
}
}
for(OauthClientServiceVO o : clientServiceList){
String serviceURL = o.getServiceURL()!=null?o.getServiceURL().trim():"";
if(accessUri.equalsIgnoreCase(serviceURL)|| accessUri.startsWith(serviceURL+"/") ||
accessUri.startsWith(serviceURL+"?")){
if(!o.isUrlFilterFlag()){
ErrorVO errorVO2 = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_DISABLED_SERVICE_ENDPOINT,ErrorDescription.ERR_MSG_SECURITY_DISABLED_SERVICE_ENDPOINT,
ErrorDescription.ERR_MSG_SECURITY_DISABLED_SERVICE_ENDPOINT);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO2);
}else{
if(isAnonymousToken && o.isUserTokenRequired()){
ErrorVO errorVO2 = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_UNAUTHORIZED_TOKEN,ErrorDescription.ERR_MSG_SECURITY_UNAUTHORIZED_TOKEN,
ErrorDescription.ERR_MSG_SECURITY_UNAUTHORIZED_TOKEN);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO2);
}else{
return;
}
}
}
}
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}
private OAuth2AccessToken getAccessTokenFromDB(String tokenValue) throws ServiceException{
OAuth2AccessToken token = null;
try {
token = oauthDAO.getAccessToken(tokenValue);
} catch (DaoException e1) {
String errorMSG = ErrorDescription.ERR_MSG_SECURITY_INVALID_TOKEN+". Failed to get token from database. Error detail: "+e1.getErrorVO().getErrMsg()+" "+e1.getErrorVO().getErrDescription();
ErrorVO errorVO = new ErrorVO(ErrorDescription.ERR_CD_SECURITY_INTENAL,ErrorDescription.ERR_MSG_SECURITY_INTENAL, errorMSG);
throw new ServiceException(ExceptionType.EXCEPTION_AUTHENTICATION,errorVO);
}
return token;
}
/**
* @param path
* @return
*/
private String getServiceNameFromPath(String path){
if(StringUtils.isEmpty(path)){
return null;
}
if(path.startsWith("/")){
path = path.substring(1);
}
int index = path.indexOf("/");
if(index==-1){
return null;
}else{
String serviceName = path.substring(0, index);
return serviceName;
}
}
/**
* @return
*/
public static UserRequestVO getUserRequest(){
return userRequestVO_local.get();
}
/**
* @param userRequestVO
*/
public static void setUserRequest(UserRequestVO userRequestVO){
userRequestVO_local.set(userRequestVO);
}
public CachingService getCachingService() {
return cachingService;
}
public void setCachingService(CachingService cachingService) {
this.cachingService = cachingService;
}
}
---------------------------------------------------------
package com.a.acp.security.vo;
public class OauthClientServiceVO implements java.io.Serializable {
private static final long serialVersionUID = -4897574397263215226L;
private Integer clientServiceId;
private Integer version;
private String serviceName;
private String serviceURL;
private boolean userTokenRequired;
private boolean urlFilterFlag;
private String serviceDescription;
public Integer getClientServiceId() {
return clientServiceId;
}
public void setClientServiceId(Integer clientServiceId) {
this.clientServiceId = clientServiceId;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String getServiceURL() {
return serviceURL;
}
public void setServiceURL(String serviceURL) {
this.serviceURL = serviceURL;
}
public boolean isUserTokenRequired() {
return userTokenRequired;
}
public void setUserTokenRequired(boolean userTokenRequired) {
this.userTokenRequired = userTokenRequired;
}
public boolean isUrlFilterFlag() {
return urlFilterFlag;
}
public void setUrlFilterFlag(boolean urlFilterFlag) {
this.urlFilterFlag = urlFilterFlag;
}
public String getServiceDescription() {
return serviceDescription;
}
public void setServiceDescription(String serviceDescription) {
this.serviceDescription = serviceDescription;
}
}
---------------------------------------
package com.a.acp.external;
import com.a.acp.analytics.external.salesforce.request.LeadFeedRequestVO;
import com.a.acp.core.exception.ServiceException;
import com.a.acp.external.json.response.PDPDetailVO;
public interface ExternalService {
public String submitLead(LeadFeedRequestVO leadFeedRequestVO) throws ServiceException;
public PDPDetailVO getPropertyDetails(String propertyId) throws ServiceException;
}
----------------------------------
package com.a.acp.external.impl;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import com.a.acp.analytics.external.salesforce.LeadFeedResponse;
import com.a.acp.analytics.external.salesforce.SalesforceRestClient;
import com.a.acp.analytics.external.salesforce.request.LeadFeedRequestVO;
import com.a.acp.core.exception.ServiceException;
import com.a.acp.core.util.PropertyUtil;
import com.a.acp.external.ExternalService;
import com.a.acp.external.json.response.PDPDetailVO;
import com.a.acp.rest.ResponseMapper;
import com.a.acp.rest.RestEasyService;
import com.a.acp.rest.impl.RestEasyServiceImpl;
import com.a.acp.security.service.OauthService;
import com.a.acp.security.vo.UserRequestVO;
@Named
public class ExternalServiceImpl implements ExternalService {
private static Logger logger = LoggerFactory
.getLogger(ExternalServiceImpl.class.getName());
@Inject
private RestEasyService restEasyService;
@Inject
private SalesforceRestClient salesforceRestClient;
@Value("${acpPlatform.propertyServiceUrl}")
private String propertyServiceUrl;
/** The response mapper. */
@Inject
private ResponseMapper responseMapper = new ResponseMapper();
@Override
public String submitLead(LeadFeedRequestVO leadFeedRequestVO)
throws ServiceException {
String appender=(String)PropertyUtil.get("action.analytics.salesforce.appender");
Logger logger = LoggerFactory.getLogger(appender);
try{
//salesforceRestClient = new SalesforceRestClient();
Map<String,String> authHeaders = new HashMap<String, String>();
authHeaders.put("Content-Type", "application/json");
authHeaders.put("Accept", "application/json");
//authHeaders.put("Authorization", "Bearer 00DJ0000002iWu3!ARUAQLuQZeSeKxD03Tc11cwMs0V32JkV0Z409iBbDmPbrBh0NLLQTVyAkwY9Pqv4WIkzqxmRFArCf4QdAC7TZ5GDAtgQV4AB");
if(StringUtils.isNotBlank(salesforceRestClient.getSalesForceToken())){
int diffInMins = (int) ( (new Date().getTime() - salesforceRestClient.getSalesForceTokenGenerateTime().getTime())/(1000*60) );
if(diffInMins > 50){
logger.info("Calling refresh token for "+leadFeedRequestVO.getFirstName());
authHeaders.put("Authorization", "Bearer "+salesforceRestClient.getNewTokenByRefreshToken());
}else{
logger.info("Using existing token for "+leadFeedRequestVO.getFirstName());
authHeaders.put("Authorization", "Bearer "+salesforceRestClient.getSalesForceToken());
}
}else{
logger.info("new token for "+leadFeedRequestVO.getFirstName());
authHeaders.put("Authorization", "Bearer "+salesforceRestClient.getNewToken());
}
authHeaders.put("Cookie", " IS3_History=1367405442-1-26_0--1+1--1+5--1+7--1+10--1+18--1+25--1__0-1-5-7-10-18-25_; IS3_GSV=DPL-2_TES-1372116324_PCT-1372116324_GeoIP-50.196.161.146_GeoCo-US_GeoRg-CA_GeoCt-Santa%20Clara_GeoNs-_GeoDm-; rememberUn=true; login=integrationuser@a.com.full; com.salesforce.LocaleInfo=us; oinfo=\"c3RhdHVzPURFTU8mdHlwZT02Jm9pZD0wMERKMDAwMDAwMmlXdTM=\"; sfdc_lv2=\"KxG83HOZikaVREMvgS+fjH0fQpvG9uvcSutuMZbLvYqLQFggTLKk0V2IEvRc2tMOE=\"; autocomplete=1; inst=APPJ; HTPortal=%22%7B%27HTVersion%27%3A%20%272.0%27%7D%22; webact=%7B%22l_vdays%22%3A1%2C%22l_visit%22%3A1372692515259%2C%22session%22%3A1372698213678%2C%22l_search%22%3A%22%22%2C%22l_dtype%22%3A%22Typed%2FBookmarked%22%2C%22l_page%22%3A%22HELP%3Aus%3Aunauth%3Ahtviewhelpdoc%22%2C%22counter%22%3A17%2C%22pv%22%3A15%2C%22f_visit%22%3A1372097566011%2C%22version%22%3A%22w172.1%22%2C%22l_cloud%22%3A%22No%20Cloud%22%2C%22seg%22%3A%22customer%3Aus%22%2C%22customer%22%3A1372097795237%2C%22d%22%3A%2270130000000sUVq%22%2C%22db%22%3A%7B%22name%22%3A%22%22%2C%22size%22%3A%22%22%2C%22ind%22%3A%22%22%2C%22cmp%22%3A%22%22%2C%22aud%22%3A%22%22%7D%2C%22elq%22%3A%22cfbfacda-4bf6-4af1-a678-9b20eded6603%22%7D; s_vi=[CS]v1|28E4460E8501124A-4000010F401C6D9F[CE]");
//LeadFeedResponse response = salesforceRestClient.post("https://www.cs10.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8", leadFeedRequestVO, null, authHeaders, LeadFeedResponse.class, 5000, 5000);
LeadFeedResponse response = salesforceRestClient.post("https://cs10.salesforce.com/services/data/v28.0/sobjects/Lead/", leadFeedRequestVO, null, authHeaders, LeadFeedResponse.class, 5000, 5000);
logger.info("Request Lead submited for "+leadFeedRequestVO.getFirstName());
// if(response.getStatus()==200){
return "SUCCESS";
// }
// return "UN-SUCCESS";
}catch(Exception exception){
exception.printStackTrace();
logger.info("Lead submit request failed for "+leadFeedRequestVO.getFirstName());
}
return null;
}
@Override
public PDPDetailVO getPropertyDetails(String propertyId)
throws ServiceException {
Map<String, String> httpHeaders = new HashMap<String, String>();
httpHeaders.put("Authorization", "Bearer "+getCurrentTokenValue() );
PDPDetailVO pdpDetailVO = restEasyService.get(propertyServiceUrl+propertyId
, null, PDPDetailVO.class, MediaType.APPLICATION_JSON_TYPE, MediaType.APPLICATION_JSON_TYPE, httpHeaders, 5000, 5000);
return pdpDetailVO;
}
public String getCurrentTokenValue(){
UserRequestVO userRequestVO=OauthService.getUserRequest();
String tokenValue =null;
if(userRequestVO!=null)
tokenValue =userRequestVO.getTokenValue();
return tokenValue;
}
public static void main(String[] args){
ExternalService externalService = new ExternalServiceImpl();
try {
System.out.println(externalService.submitLead(new LeadFeedRequestVO()));
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
----------------------------------------
package com.a.acp.analytics.external.salesforce;
import static com.a.acp.core.constant.ErrorDescription.ERR_MSG_EXTERNAL_SERVICE;
import static com.a.acp.core.constant.ErrorDescription.EXTERNAL_SERVICE_EXCEPTION;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Named;
import javax.ws.rs.core.MediaType;
import org.apache.commons.lang.StringUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParamBean;
import org.apache.http.params.HttpParams;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.jboss.resteasy.client.ClientExecutor;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.client.core.executors.ApacheHttpClient4Executor;
import org.springframework.beans.factory.annotation.Value;
import com.a.acp.core.constant.ExceptionType;
import com.a.acp.core.exception.ServiceException;
import com.a.acp.core.vo.json.ErrorVO;
import com.a.acp.rest.client.ACPRestClient;
import com.sun.jersey.core.util.MultivaluedMapImpl;
@Named
public class SalesforceRestClient {
private static String salesForceToken;
private static Timestamp salesForceTokenGenerateTime;
@Value("${salesforce.username}")
private String userName;
@Value("${salesforce.password}")
private String password;
@Value("${salesforce.clientid}")
private String clientId;
@Value("${salesforce.clientsecret}")
private String clientSecret;
@Value("${salesforce.tokenURL}")
private String tokenURL;
public String getNewToken() throws ServiceException{
javax.ws.rs.core.MultivaluedMap forceLoginRequestVO = new MultivaluedMapImpl();
forceLoginRequestVO.add("username", userName);
forceLoginRequestVO.add("password", password);
forceLoginRequestVO.add("grant_type", "password");
forceLoginRequestVO.add("client_id", clientId);
forceLoginRequestVO.add("client_secret",clientSecret);
Map authHeaders = new HashMap<>();
authHeaders.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
SalesForceTokenResponse salesForceTokenResponse = post( tokenURL, forceLoginRequestVO, null, authHeaders
, SalesForceTokenResponse.class, new Integer(5000),new Integer(5000));
salesForceToken = salesForceTokenResponse.getAccess_token();
salesForceTokenGenerateTime = new Timestamp((new Date()).getTime());
return salesForceToken;
}
public String getNewTokenByRefreshToken() throws ServiceException{
javax.ws.rs.core.MultivaluedMap forceLoginRequestVO = new MultivaluedMapImpl();
forceLoginRequestVO.add("username", userName);
forceLoginRequestVO.add("password",password);
//TODO refresh token
//forceLoginRequestVO.add("grant_type", "refresh_token");
forceLoginRequestVO.add("grant_type", "password");
forceLoginRequestVO.add("client_id", clientId);
forceLoginRequestVO.add("client_secret", clientSecret);
forceLoginRequestVO.add("refresh_token", salesForceToken);
Map authHeaders = new HashMap<>();
authHeaders.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
SalesForceTokenResponse salesForceTokenResponse = post( tokenURL, forceLoginRequestVO, null, authHeaders
, SalesForceTokenResponse.class, new Integer(5000),new Integer(5000));
salesForceToken = salesForceTokenResponse.getAccess_token();
salesForceTokenGenerateTime = new Timestamp((new Date()).getTime());
return salesForceToken;
}
//=================================================
// Private Methods
//=================================================
/**
* Assign header values.
*
* @param clientRequest the client request
* @param authHeaders the auth headers
* @return the client request
*/
private ACPRestClient assignHeaderValues(ACPRestClient clientRequest, Map<String,String> authHeaders){
if(authHeaders != null && authHeaders.size() != 0){
for(String key : authHeaders.keySet()){
clientRequest.header(key,authHeaders.get(key));
}
}
return clientRequest;
}
private ACPRestClient getClientRequest(ACPRestClient clientRequest, String serviceEndPointUrl, Object requestBean, Map<String,String> authHeaders
, MediaType contentType, MediaType accept,
Integer connectionTimeoutMillis, Integer socketTimeoutMillis) throws ServiceException{
if(StringUtils.isNotEmpty(serviceEndPointUrl)){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParamBean httpConnectionParams = new HttpConnectionParamBean(params);
if(connectionTimeoutMillis != null){
httpConnectionParams.setConnectionTimeout(connectionTimeoutMillis.intValue());
}
if(socketTimeoutMillis != null){
httpConnectionParams.setSoTimeout( socketTimeoutMillis);
}
if(authHeaders==null || authHeaders.size()==0)
authHeaders = new HashMap<String, String>();
//RedirectStrategy redirectStrategy = new RedirectStrategy(new HttpsRedirectStratergy()) ;
httpClient.setRedirectStrategy(new HttpsRedirectStratergy());
ClientExecutor executor = new ApacheHttpClient4Executor(httpClient);
try {
clientRequest.assignValues(serviceEndPointUrl, executor);
clientRequest = assignHeaderValues(clientRequest,authHeaders);
if (contentType == null && authHeaders.get("Content-Type") == null) {
//contentType = DEFAULT_CONTENT_TYPE;
contentType = MediaType.APPLICATION_JSON_TYPE;
authHeaders.put("Content-Type", contentType.toString());
}
if (accept == null && authHeaders.get("Accept") == null) {
//accept = DEFAULT_ACCEPT;
accept = MediaType.APPLICATION_JSON_TYPE;//"application/json";
clientRequest.accept(accept);
}
if(requestBean != null)
if(null != authHeaders.get("Content-Type"))
clientRequest.body(authHeaders.get("Content-Type"), requestBean);
else
clientRequest.body(contentType, requestBean);
}catch (Exception exception) {
exception.printStackTrace();
ErrorVO errorVO = new ErrorVO(EXTERNAL_SERVICE_EXCEPTION, ERR_MSG_EXTERNAL_SERVICE, exception.getMessage());
throw new ServiceException(ExceptionType.EXCEPTION_SERVICE, errorVO);
}
}else{
ErrorVO errorVO = new ErrorVO(EXTERNAL_SERVICE_EXCEPTION, ERR_MSG_EXTERNAL_SERVICE, "No url defined");
throw new ServiceException(ExceptionType.EXCEPTION_SERVICE, errorVO);
}
return clientRequest;
}
/**
* Post.
*
* @param <T> the generic type
* @param serviceEndPointUrl the service end point url
* @param requestBean the request bean
* @param pathVariables the path variables
* @param authHeaders the auth headers
* @param responseType the response type
* @param contentType the content type
* @param accept the accept
* @return the t
* @throws ServiceException the service exception
*/
@SuppressWarnings("unchecked")
public <T> T post(String serviceEndPointUrl, Object requestBean, Object[] pathVariables, Map<String,String> authHeaders
, Class<T> responseType, Integer socketTimeout, Integer connectionTimeoutMillis) throws ServiceException {
ClientResponse<String> responseEntity = null;
LeadFeedResponse responseValue = null;
SalesForceTokenResponse responseValue2 = null;
Object returnObject = null;
System.out.println("serviceEndPointUrl "+serviceEndPointUrl+" requestBean "+requestBean);
try {
if(socketTimeout == null){
socketTimeout = new Integer("50000");
}
if(connectionTimeoutMillis == null){
connectionTimeoutMillis = new Integer("50000");
}
ACPRestClient clientRequest = new ACPRestClient();
clientRequest = getClientRequest(clientRequest, serviceEndPointUrl, requestBean, authHeaders
, null, null, socketTimeout,connectionTimeoutMillis);
clientRequest.setHttpMethod("Post");
if (pathVariables == null) {
//responseEntity = super.postForEntity(serviceEndPointUrl, aRequestEntity, responseType);.
responseEntity = (ClientResponse<String>)clientRequest.post();
} else {
clientRequest.pathParameters(pathVariables);
responseEntity = (ClientResponse<String>)clientRequest.post(String.class);
}
} catch (ServiceException serviceException) {
} catch (Exception exception) {
exception.printStackTrace();
}
ObjectMapper jacksonObjectMapper = new ObjectMapper();
if(responseEntity.getStatus()==201){
TypeReference<LeadFeedResponse> typeRef = new TypeReference<LeadFeedResponse>(){};
try {
//responseJsonVO = jacksonObjectMapper.readValue(jacksonObjectMapper.writeValueAsString(responseEntity.getEntity(responseType.getClass())), typeRef);
//responseValue = jacksonObjectMapper.readValue(jacksonObjectMapper.writeValueAsString(responseEntity.getEntity()), ACPResponse.class);
responseValue = jacksonObjectMapper.readValue(responseEntity.getEntity(String.class),typeRef);
return (T) responseValue;
}catch(Exception e){e.printStackTrace();}
}
if(responseEntity.getStatus()==200){
TypeReference<SalesForceTokenResponse> typeRef = new TypeReference<SalesForceTokenResponse>(){};
try {
//responseJsonVO = jacksonObjectMapper.readValue(jacksonObjectMapper.writeValueAsString(responseEntity.getEntity(responseType.getClass())), typeRef);
//responseValue = jacksonObjectMapper.readValue(jacksonObjectMapper.writeValueAsString(responseEntity.getEntity()), ACPResponse.class);
responseValue2 = responseEntity.getEntity(SalesForceTokenResponse.class);
return (T) responseValue2;
}catch(Exception e){e.printStackTrace();}
}
if(responseEntity.getStatus()==400){
System.out.println(responseEntity.getEntity(String.class));
}
if(responseEntity.getStatus()==401){
getNewTokenByRefreshToken();
}
if(responseValue!= null){
boolean oResult = responseValue.isSuccess();
String responseClassName = responseType.getName();
if(responseValue.isSuccess()){
return (T) responseValue;
}else{
String[] errors = responseValue.getErrors();
if(errors!=null && errors.length > 0){
for(String error : errors)
System.out.println(error);
}
}
}
return (T) null;
}
/* (non-Javadoc)
* @see com.a.acp.restEasy.RestEasyService#get(java.lang.String, java.lang.Object[], java.lang.Class, javax.ws.rs.core.MediaType, javax.ws.rs.core.MediaType, java.util.Map)
*/
@SuppressWarnings("unchecked")
public <T> T get(String serviceEndPointUrl, Object[] pathVariables,
Class<T> responseType, Map<String,String> authHeaders,Integer socketTimeout
, Integer connectionTimeoutMillis)
throws ServiceException {
ClientResponse<T> responseEntity = null;
try {
if(socketTimeout == null){
socketTimeout = new Integer("5000");
}
if(connectionTimeoutMillis == null){
connectionTimeoutMillis = new Integer("5000");
}
ACPRestClient clientRequest = new ACPRestClient();
clientRequest = getClientRequest(clientRequest, serviceEndPointUrl, null,authHeaders
, null, null, socketTimeout,connectionTimeoutMillis);
clientRequest.setHttpMethod("Get");
System.out.println(clientRequest.followRedirects(true));
if (pathVariables == null) {
//responseEntity = super.postForEntity(serviceEndPointUrl, aRequestEntity, responseType);.
responseEntity = (ClientResponse<T>) clientRequest.get(responseType);
} else {
clientRequest.pathParameters(pathVariables);
responseEntity = (ClientResponse<T>) clientRequest.get(responseType);
}
if(responseEntity.getStatus() == 302 && responseEntity.getLocation() != null){
String redirectUrl = responseEntity.getLocation().getHref();
responseEntity = null;
System.out.println(redirectUrl);
//String configuredRedirectUrl = "<https://test.salesforce.com/setup/secur/RemoteAccessAuthorizationPage.apexp?source=l86Hcy6qEKtWNqzXVErZDlmcRQs0D_HBE55MLVuP3x8t5wXkyHYyrVx2Xb5JoWzyVOJrnTqMMaWy_Sfomv.j1xklSQ67NPiEbdAN93_XyFPi1fxRQaEh6AqyCckTs3KjNphB_WQTO3eE.jZDMsWl3OimE9rFjGEO_EXCSxn3Og.5HyJIvTVdvP9hmZwerUnQYtVXGt5B8oY.7Azu85GA8G0G5DyTpmp8yQ8mtbJ0.R8AzUHghba4ydlMHbkba_IbrB2Z7myMIJcwu51tB6parh8P.R2fgdU73pTJ_3oGiaCD4lU2cAmAgICH9z0ImGcn7FEhZfmCA0uXj9WTKyrlbFoV6bueunkIq1LdDN4icYg%3D%3D&sdtd=1>";
//if(StringUtils.equals(configuredRedirectUrl,responseEntity.getLocation().toString())){
SalesForceLoginRequestVO salesForceLoginRequestVO = new SalesForceLoginRequestVO();
salesForceLoginRequestVO.setUsername(userName);
salesForceLoginRequestVO.setPassword(password);
clientRequest = new ACPRestClient();
clientRequest = getClientRequest(clientRequest, redirectUrl, salesForceLoginRequestVO,null
, null, null, socketTimeout,connectionTimeoutMillis);
clientRequest.setHttpMethod("Post");
clientRequest.followRedirects(true);
responseEntity = (ClientResponse<T>) clientRequest.post(responseType);
System.out.println(responseEntity.getEntity(String.class));
//}
//https://www.google.com/?code=aPrxBLRflqd7xyKWa.MOfe0XOpwiNMcuLaMWxnz4HPX92mDf2gb2czxImuZpkCFla6cGzj1zHA%3D%3D
}
} catch (ServiceException serviceException) {
} catch (Exception exception) {
exception.printStackTrace();
}
return (T) responseEntity;
}
public static String getSalesForceToken() {
return salesForceToken;
}
public static void setSalesForceToken(String salesForceToken) {
SalesforceRestClient.salesForceToken = salesForceToken;
}
public static Timestamp getSalesForceTokenGenerateTime() {
return salesForceTokenGenerateTime;
}
public static void setSalesForceTokenGenerateTime(
Timestamp salesForceTokenGenerateTime) {
SalesforceRestClient.salesForceTokenGenerateTime = salesForceTokenGenerateTime;
}
}
No comments:
Post a Comment