Rekognition client keeps rebuilding on each request - java

I am using AWS Rekognition to build an application and I have realized that every time i make a request to the service a connection to aws keep being reestablished which is slowing down performance. Is there any way to make one single connection that persists throughout the session? My code can be seen below:
private static final AmazonRekognition rekognitionClient = RekognitionUtil.setupRekognitionClient();
private static AWSCredentialsProvider setupCredentials(String accessKey, String secretKey) {
AWSCredentialsProvider provider = new AWSCredentialsProvider() {
#Override
public AWSCredentials getCredentials() {
return new AWSCredentials() {
#Override
public String getAWSAccessKeyId() {
LOG.info("Access key: " + ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_ACCESS_KEY,accessKey));
return ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_ACCESS_KEY,accessKey);
}
#Override
public String getAWSSecretKey() {
LOG.info("Secret key: " + ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_SECRET_KEY,secretKey));
return ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_SECRET_KEY,secretKey);
}
};
}
#Override
public void refresh() {
}
};
return provider;
}
private static AmazonRekognition setupRekognitionClient() {
AWSCredentialsProvider provider = setupCredentials("xxxx", "xxxx");
return AmazonRekognitionClientBuilder.standard().withCredentials(provider).withRegion(ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_REGION,"xxx")).build();
}
private static AWSCredentialsProvider setupCredentials(String accessKey, String secretKey) {
AWSCredentialsProvider provider = new AWSCredentialsProvider() {
#Override
public AWSCredentials getCredentials() {
return new AWSCredentials() {
#Override
public String getAWSAccessKeyId() {
LOG.info("Access key: " + ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_ACCESS_KEY,accessKey));
return ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_ACCESS_KEY,accessKey);
}
#Override
public String getAWSSecretKey() {
LOG.info("Secret key: " + ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_SECRET_KEY,secretKey));
return ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_SECRET_KEY,secretKey);
}
};
}
#Override
public void refresh() {
}
};
return provider;
}
private static AmazonRekognition setupRekognitionClient() {
AWSCredentialsProvider provider = setupCredentials("xxxx", "xxx");
return AmazonRekognitionClientBuilder.standard().withCredentials(provider).withRegion(ConfigUtil.getString(ConfigConstants.CONFIG_REKOGNITION_REGION,"xxx")).build();
}
public static String searchCollectionByFace(String collectionId, ByteBuffer sourceByteBuffer) throws Exception {
LOG.info("Searching face collection by face...");
String faceId = "";
try {
ObjectMapper objectMapper = new ObjectMapper();
// Get an image object from S3 bucket.
Image image = new Image().withBytes(sourceByteBuffer);
// Search collection for faces similar to the largest face in the image.
SearchFacesByImageRequest searchFacesByImageRequest = new SearchFacesByImageRequest().withCollectionId(collectionId).withImage(image).withFaceMatchThreshold(70F).withMaxFaces(2);
SearchFacesByImageResult searchFacesByImageResult = rekognitionClient.searchFacesByImage(searchFacesByImageRequest);
List<FaceMatch> faceImageMatches = searchFacesByImageResult.getFaceMatches();
for (FaceMatch face : faceImageMatches) {
LOG.info(face.getFace().getFaceId());
if(face.getFace().getConfidence() > SIMILARITY_LIMIT){
faceId = face.getFace().getFaceId();
}
}
return faceId;
} catch (Exception ex) {
LOG.error("Error has occurred searching for face", ex);
throw new Exception();
}
}

You can try to fine tune:
Max connections
Max connection idle time
in the client configuration you pass to the client.

Related

SMPP java server connect to SMSC or SMPP Client can receive SMS via SMPP?

i have 3rd party smpp connection.
so i created java smpp client and its working fine.
how i can create smpp server connect to 3rd party smpp connection and need to send sms via that created smpp server. my problem is i doesn't know how to connect smpp server to smsc/smpp 3rd party connection
please help to me connect this smpp server to smpp 3rd party server for send sms..
public class SMPPServerSimulator extends ServerResponseDeliveryAdapter implements Runnable, ServerMessageReceiverListener {
private static final Logger log = LoggerFactory.getLogger(SMPPServerSimulator.class);
private static final String QUERYSM_NOT_IMPLEMENTED = "query_sm not implemented";
private static final String CANCELSM_NOT_IMPLEMENTED = "cancel_sm not implemented";
private static final String DATASM_NOT_IMPLEMENTED = "data_sm not implemented";
private static final String REPLACESM_NOT_IMPLEMENTED = "replace_sm not implemented";
private static final String BROADCASTSM_NOT_IMPLEMENTED = "broadcast_sm not implemented";
private static final String CANCELBROADCASTSM_NOT_IMPLEMENTED = "cancel_broadcast_sm not implemented";
private static final String QUERYBROADCASTSM_NOT_IMPLEMENTED = "query_broadcast_sm not implemented";
private static final Integer DEFAULT_PORT = 2775;
private static final String DEFAULT_SYSID = "twtest";
private static final String DEFAULT_PASSWORD = "test123";
private static final String SMSC_SYSTEMID = "sys";
private final ExecutorService execService = Executors.newFixedThreadPool(5);
private final ExecutorService execServiceDelReceipt = Executors.newFixedThreadPool(100);
private final MessageIDGenerator messageIDGenerator = new RandomMessageIDGenerator();
private final boolean useSsl;
private final int port;
private final String systemId;
private final String password;
public SMPPServerSimulator(boolean useSsl, int port, String systemId, String password) {
this.useSsl = useSsl;
this.port = port;
this.systemId = systemId;
this.password = password;
}
#Override
public void run() {
boolean running = true;
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
try (SMPPServerSessionListener sessionListener = useSsl ?
new SMPPServerSessionListener(port, new KeyStoreSSLServerSocketConnectionFactory())
: new SMPPServerSessionListener(port)) {
/*
* for SSL use the SSLServerSocketConnectionFactory() or DefaultSSLServerSocketConnectionFactory()
*/
log.info("Listening on port {}{}", port, useSsl ? " (SSL)" : "");
while (running) {
System.out.println("running");
SMPPServerSession serverSession = sessionListener.accept();
log.info("Accepted connection with session {}", serverSession.getSessionId());
serverSession.setMessageReceiverListener(this);
serverSession.setResponseDeliveryListener(this);
Future<Boolean> bindResult = execService.submit(new WaitBindTask(serverSession, 30000, systemId, password));
try {
boolean bound = bindResult.get();
System.out.println(bound+" sss");
if (bound) {
// Could start deliver_sm to ESME
log.info("The session is now in state {}", serverSession.getSessionState());
serverSession.deliverShortMessage("CMT",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "94712320529",
TypeOfNumber.INTERNATIONAL, NumberingPlanIndicator.ISDN, "TWTEST",
new ESMClass(0), (byte) 0x00, (byte) 0x00, new RegisteredDelivery(), DataCodings.ZERO,
"Hello Worldxxxxxxxxxxx".getBytes());
}
} catch (InterruptedException e){
log.info("Interrupted WaitBind task: {}", e.getMessage());
Thread.currentThread().interrupt();
running = false;
} catch (ExecutionException e){
log.info("Exception on execute WaitBind task: {}", e.getMessage());
running = false;
} catch (NegativeResponseException | ResponseTimeoutException | PDUException | InvalidResponseException e){
log.info("Could not send deliver_sm: {}", e.getMessage());
}
}
} catch (IOException e) {
log.error("IO error occurred", e);
}
}
#Override
public QuerySmResult onAcceptQuerySm(QuerySm querySm, SMPPServerSession source) throws ProcessRequestException {
log.info("QuerySm not implemented");
throw new ProcessRequestException(QUERYSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RINVCMDID);
}
#Override
public SubmitSmResult onAcceptSubmitSm(SubmitSm submitSm,
SMPPServerSession source) throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.info("Receiving submit_sm '{}', and return message id {}", new String(submitSm.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitSm.getRegisteredDelivery()) || SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitSm.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitSm, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitSmResult(messageId, new OptionalParameter[]{ congestionState });
}
return new SubmitSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onSubmitSmRespSent(SubmitSmResult submitSmResult,
SMPPServerSession source) {
log.debug("submit_sm_resp with message_id {} has been sent", submitSmResult.getMessageId());
}
#Override
public SubmitMultiResult onAcceptSubmitMulti(SubmitMulti submitMulti, SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving submit_multi_sm '{}', and return message id {}",
new String(submitMulti.getShortMessage()), messageId);
if (SMSCDeliveryReceipt.FAILURE.containedIn(submitMulti.getRegisteredDelivery())
|| SMSCDeliveryReceipt.SUCCESS_FAILURE.containedIn(submitMulti.getRegisteredDelivery())) {
execServiceDelReceipt.execute(new DeliveryReceiptTask(source, submitMulti, messageId));
}
/*
* SMPP 5.0 allows the following optional parameters (SMPP 5.0 paragraph 4.2.5):
* additional_status_info_text, delivery_failure_reason, dpf_result, network_error_code
* Add the congestionState for SMPP 5.0 connections.
*/
if (source.getInterfaceVersion().value() >= InterfaceVersion.IF_50.value()) {
final int congestionRatio = source.getCongestionRatio();
OptionalParameter.Congestion_state congestionState = new OptionalParameter.Congestion_state((byte) congestionRatio);
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[]{ congestionState });
}
return new SubmitMultiResult(messageId.getValue(), new UnsuccessDelivery[0], new OptionalParameter[0]);
}
#Override
public DataSmResult onAcceptDataSm(DataSm dataSm, Session source)
throws ProcessRequestException {
log.info("Accepting data_sm, but not implemented");
throw new ProcessRequestException(DATASM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RSYSERR);
}
#Override
public void onAcceptCancelSm(CancelSm cancelSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_sm, but not implemented");
throw new ProcessRequestException(CANCELSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RCANCELFAIL);
}
#Override
public void onAcceptReplaceSm(ReplaceSm replaceSm, SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting replace_sm, but not implemented");
throw new ProcessRequestException(REPLACESM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RREPLACEFAIL);
}
#Override
public BroadcastSmResult onAcceptBroadcastSm(final BroadcastSm broadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
MessageId messageId = messageIDGenerator.newMessageId();
log.debug("Receiving broadcast_sm '{}', and return message id {}",
new String(broadcastSm.getOptionalParameter(OptionalParameter.Tag.MESSAGE_PAYLOAD).serialize()), messageId);
return new BroadcastSmResult(messageId, new OptionalParameter[0]);
}
#Override
public void onAcceptCancelBroadcastSm(final CancelBroadcastSm cancelBroadcastSm, final SMPPServerSession source)
throws ProcessRequestException {
log.info("Accepting cancel_broadcast_sm, but not implemented");
throw new ProcessRequestException(CANCELBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTCANCELFAIL);
}
#Override
public QueryBroadcastSmResult onAcceptQueryBroadcastSm(final QueryBroadcastSm queryBroadcastSm,
final SMPPServerSession source) throws ProcessRequestException {
log.info("Accepting query_broadcast_sm, but not implemented");
throw new ProcessRequestException(QUERYBROADCASTSM_NOT_IMPLEMENTED, SMPPConstant.STAT_ESME_RBCASTQUERYFAIL);
}
private static class WaitBindTask implements Callable<Boolean> {
private final SMPPServerSession serverSession;
private final long timeout;
private final String systemId;
private final String password;
public WaitBindTask(SMPPServerSession serverSession, long timeout, String systemId, String password) {
this.serverSession = serverSession;
this.timeout = timeout;
this.systemId = systemId;
this.password = password;
}
#Override
public Boolean call() {
try {
System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
BindRequest bindRequest = serverSession.waitForBind(timeout);
try {
if (BindType.BIND_TRX.equals(bindRequest.getBindType())) {
if (systemId.equals(bindRequest.getSystemId())) {
if (password.equals(bindRequest.getPassword())) {
log.info("Accepting bind for session {}, interface version {}", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
serverSession.setInterfaceVersion(InterfaceVersion.IF_50.min(bindRequest.getInterfaceVersion()));
// The systemId identifies the SMSC to the ESME.
bindRequest.accept(SMSC_SYSTEMID, InterfaceVersion.IF_50);
return true;
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid password", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVPASWD);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, invalid system id", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RINVSYSID);
}
} else {
log.info("Rejecting bind for session {}, interface version {}, only accept transceiver", serverSession.getSessionId(), bindRequest.getInterfaceVersion());
bindRequest.reject(SMPPConstant.STAT_ESME_RBINDFAIL);
}
} catch (PDUStringException e) {
log.error("Invalid system id: " + SMSC_SYSTEMID, e);
bindRequest.reject(SMPPConstant.STAT_ESME_RSYSERR);
}
} catch (IllegalStateException e) {
log.error("System error", e);
} catch (TimeoutException e) {
log.warn("Wait for bind has reach timeout", e);
} catch (IOException e) {
log.error("Failed accepting bind request for session {}", serverSession.getSessionId());
}
return false;
}
}
private static class DeliveryReceiptTask implements Runnable {
private final SMPPServerSession session;
private final MessageId messageId;
private final TypeOfNumber sourceAddrTon;
private final NumberingPlanIndicator sourceAddrNpi;
private final String sourceAddress;
private final TypeOfNumber destAddrTon;
private final NumberingPlanIndicator destAddrNpi;
private final String destAddress;
private final int totalSubmitted;
private final int totalDelivered;
private final byte[] shortMessage;
public DeliveryReceiptTask(SMPPServerSession session,
SubmitSm submitSm, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// reversing destination to source
sourceAddrTon = TypeOfNumber.valueOf(submitSm.getDestAddrTon());
sourceAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getDestAddrNpi());
sourceAddress = submitSm.getDestAddress();
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitSm.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitSm.getSourceAddrNpi());
destAddress = submitSm.getSourceAddr();
totalSubmitted = totalDelivered = 1;
shortMessage = submitSm.getShortMessage();
}
public DeliveryReceiptTask(SMPPServerSession session,
SubmitMulti submitMulti, MessageId messageId) {
this.session = session;
this.messageId = messageId;
// set to unknown and null, since it was submit_multi
sourceAddrTon = TypeOfNumber.UNKNOWN;
sourceAddrNpi = NumberingPlanIndicator.UNKNOWN;
sourceAddress = null;
// reversing source to destination
destAddrTon = TypeOfNumber.valueOf(submitMulti.getSourceAddrTon());
destAddrNpi = NumberingPlanIndicator.valueOf(submitMulti.getSourceAddrNpi());
destAddress = submitMulti.getSourceAddr();
// distribution list assumed only contains single address
totalSubmitted = totalDelivered = submitMulti.getDestAddresses().length;
shortMessage = submitMulti.getShortMessage();
}
#Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
log.error("Interrupted", e);
//re-interrupt the current thread
Thread.currentThread().interrupt();
}
SessionState state = session.getSessionState();
if (!state.isReceivable()) {
log.debug("Not sending delivery receipt for message id {} since session state is {}", messageId, state);
return;
}
String stringValue = Integer.valueOf(messageId.getValue(), 16).toString();
try {
DeliveryReceipt delRec = new DeliveryReceipt(stringValue, totalSubmitted, totalDelivered, new Date(), new Date(), DeliveryReceiptState.DELIVRD, "000", new String(shortMessage));
session.deliverShortMessage(
"mc",
sourceAddrTon, sourceAddrNpi, sourceAddress,
destAddrTon, destAddrNpi, destAddress,
new ESMClass(MessageMode.DEFAULT, MessageType.SMSC_DEL_RECEIPT, GSMSpecificFeature.DEFAULT),
(byte)0,
(byte)0,
new RegisteredDelivery(0),
DataCodings.ZERO,
delRec.toString().getBytes());
log.debug("Sending delivery receipt for message id {}: {}", messageId, stringValue);
} catch (Exception e) {
log.error("Failed sending delivery_receipt for message id " + messageId + ":" + stringValue, e);
}
}
}
public static void main(String[] args) {
// System.setProperty("javax.net.debug", "ssl");
/*
* To use SSL, add -Djsmpp.simulator.ssl=true
* To debug SSL, add -Djavax.net.debug=ssl
*/
String systemId = System.getProperty("jsmpp.client.systemId", DEFAULT_SYSID);
String password = System.getProperty("jsmpp.client.password", DEFAULT_PASSWORD);
int port;
try {
port = Integer.parseInt(System.getProperty("jsmpp.simulator.port", DEFAULT_PORT.toString()));
} catch (NumberFormatException e) {
port = DEFAULT_PORT;
}
boolean useSsl = Boolean.parseBoolean(System.getProperty("jsmpp.simulator.ssl", "false"));
SMPPServerSimulator smppServerSim = new SMPPServerSimulator(useSsl, port, systemId, password);
smppServerSim.run();
}
}

how to use .clone() Retrofit in android application

I am somewhat new to android development and okhttp/Retrofit
Please check my first post for the reason why I need to try and get a retry mechanism working
My First post
I need some help implementing the .clone() for Retrofit in my service so that it can try to call my URL again if it fails the first time.
my urlcontroller.java
public class UrlController{
public static boolean loading = false;
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.MINUTES)
.writeTimeout(60, TimeUnit.MINUTES)
.readTimeout(60, TimeUnit.MINUTES)
.callTimeout(60, TimeUnit.MINUTES)
.build();
public static String IP_ADDRESS = "https://e***edd****.com/";//Enter You Ip_Address here here
public static String Purchase_code = "********************";
public static String Custom_Security = "***************";//Enter the Custom Security code here
// Please don't change the below code without proper knowledge
private static final OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static String Base_URL = IP_ADDRESS + "json/appr/v1/";
private static final Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(Base_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
public static <S> S createService(Class<S> serviceClass) {
return retrofit.create(serviceClass);
}
public static <S> S createService(
Class<S> serviceClass, String username, String password, Context context) {
if (!TextUtils.isEmpty(username)
&& !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createService(serviceClass, authToken, context);
} else {
return createService(serviceClass);
}
}
public static <S> S createServiceNoTimeout(Class<S> serviceClass, String authToken, Context context) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor = new AuthenticationInterceptor(authToken, context);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
httpClient.connectTimeout(0, TimeUnit.MINUTES);
httpClient.readTimeout(0, TimeUnit.SECONDS);
httpClient.writeTimeout(0, TimeUnit.SECONDS);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
public static <S> S createServiceNoTimeoutUP(
Class<S> serviceClass, String username, String password, Context context) {
if (!TextUtils.isEmpty(username)
&& !TextUtils.isEmpty(password)) {
String authToken = Credentials.basic(username, password);
return createServiceNoTimeout(serviceClass, authToken, context);
}
return createService(serviceClass);
}
public static <S> S createService(
Class<S> serviceClass, final String authToken, Context context) {
if (!TextUtils.isEmpty(authToken)) {
AuthenticationInterceptor interceptor =
new AuthenticationInterceptor(authToken, context);
if (!httpClient.interceptors().contains(interceptor)) {
httpClient.addInterceptor(interceptor);
builder.client(httpClient.build());
retrofit = builder.build();
}
}
return retrofit.create(serviceClass);
}
public static Map<String, String> AddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
*THIS INFO WAS REMOVED FOR SECURITY PURPOSES
return map;
}
public static Map<String, String> UploadImageAddHeaders(Context context) {
Map<String, String> map = new HashMap<>();
*THIS INFO WAS REMOVED FOR SECURITY PURPOSES
return map;
}
}
My splashScreen.java
I Removed some lines of code which basically just gets the data the was returned from the call to my webpage which then gets implemented in my app it is basic data like names, color-codes and user login/signup data
public void api_getSettings() {
RestService restService = UrlController.createService(RestService.class);
try{
Call<ResponseBody> myCall = restService.getSettings(UrlController.AddHeaders(this));
myCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> responseObj) {
try {
System.out.println("try2");
if (responseObj.isSuccessful()) {
Log.d("info settings Responce", "" + responseObj.toString());
JSONObject response = new JSONObject(responseObj.body().string());
if (response.getBoolean("success")) {
jsonObjectSetting = response.getJSONObject("data");
//some stuff have been hidden for security reasons
} else {
Toast.makeText(activity, response.get("test message").toString(), Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
} catch (
ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}

Getting null in Environment variable

#Configuration
public class CustomRemoteTokenService implements ResourceServerTokenServices {
private static final Logger logger = LoggerFactory.getLogger(CustomRemoteTokenService.class);
#Resource
Environment environment;
private RestOperations restTemplate;
private String checkTokenEndpointUrl;
private String clientId;
private String clientSecret;
private String tokenName = "token";
private AccessTokenConverter tokenConverter = new DefaultAccessTokenConverter();
#Autowired
public CustomRemoteTokenService() {
restTemplate = new RestTemplate();
((RestTemplate) restTemplate).setErrorHandler(new DefaultResponseErrorHandler() {
#Override
// Ignore 400
public void handleError(ClientHttpResponse response) throws IOException {
if (response.getRawStatusCode() != 400
&& response.getRawStatusCode() != 403 /* && response.getRawStatusCode() != 401 */) {
super.handleError(response);
}
}
});
}
public void setRestTemplate(RestOperations restTemplate) {
this.restTemplate = restTemplate;
}
public void setCheckTokenEndpointUrl(String checkTokenEndpointUrl) {
this.checkTokenEndpointUrl = checkTokenEndpointUrl;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public void setAccessTokenConverter(AccessTokenConverter accessTokenConverter) {
this.tokenConverter = accessTokenConverter;
}
public void setTokenName(String tokenName) {
this.tokenName = tokenName;
}
#Override
public OAuth2Authentication loadAuthentication(String accessToken)
throws AuthenticationException, InvalidTokenException, GenericException {
/*
* This code needs to be more dynamic. Every time an API is added we have to add
* its entry in the if check for now. Should be changed later.
*/
HttpServletRequest request = Context.getCurrentInstance().getRequest();
MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
formData.add(tokenName, accessToken);
formData.add("api", environment.getProperty("resource.api"));
/* formData.add("api", "5b64018880999103244f1fdd");*/
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
Map<String, Object> map = null;
try {
map = postForMap(checkTokenEndpointUrl, formData, headers);
} catch (ResourceAccessException e) {
logger.error("Socket Exception occured at " + System.currentTimeMillis() + "for client_id : " + clientId);
GenericException ge = new GenericException(
"Could not validate your access token. If this occurs too often please contact MapmyIndia support at apisupport#mapmyindia.com");
ge.setHttpErrorCode(504);
ge.setOauthError("Access Token validation failed");
throw ge;
}
if (map.containsKey("error")) {
logger.error("check_token returned error: " + map.get("error") + " for client id : " + clientId);
String temp = map.get("error").toString();
GenericException ge = new GenericException(map.get("error_description").toString());
ge.setHttpErrorCode(Integer.parseInt(map.get("responsecode").toString()));
ge.setOauthError(temp);
switch (temp) {
case "invalid_token":
throw new InvalidTokenException(accessToken);
default:
throw ge;
}
}
Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
return tokenConverter.extractAuthentication(map);
}
#Override
public OAuth2AccessToken readAccessToken(String accessToken) {
throw new UnsupportedOperationException("Not supported: read access token");
}
private String getAuthorizationHeader(String clientId, String clientSecret) {
String creds = String.format("%s:%s", clientId, clientSecret);
try {
return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Could not convert String");
}
}
private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers)
throws RestClientException {
if (headers.getContentType() == null) {
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
}
#SuppressWarnings("rawtypes")
Map map = restTemplate.exchange(path, HttpMethod.POST,
new HttpEntity<MultiValueMap<String, String>>(formData, headers), Map.class).getBody();
#SuppressWarnings("unchecked")
Map<String, Object> result = map;
return result;
}
}
I autowired Environment and getting null when I do environment.getProperty("resource.api");
It is always returning null but in another classes I autowire Environment and successfully retrieve the value from properties.
You have to take this steps :
1.Register a Properties
You need to register you properties file by #PropertySource("classpath:foo.properties") as :
#Configuration
#PropertySource("classpath:foo.properties")
public class CustomRemoteTokenService implements ResourceServerTokenServices {
//...
}
2.Injecting Properties
To obtain the value of a property with the Environment API:
#Autowired
private Environment env;

TokenStore MongoDB Spring OAuth2

I'm trying to create token store with on MongoDB
I wanted to use the current DB connection in my app.
I've used the JdbcTokenStore and convert it but I think I've done it wrong since I was not able to #Autowired (it is null).
I guess it is because that bean is starting before the Mongo connection bean.
Is any fix for that or I need to create the connection from scratch?
Also the #Value("${spring.data.mongodb.host}") is not working....
The most helpful if someone already wrote the TokenStore on Mongo.
Because I guess I'll also have serialization issues after.
I'm attaching my not so working code, please advise.
import lombok.Getter;
import lombok.Setter;
public class MongoDBTokenStore implements TokenStore {
private static final Log LOG = LogFactory.getLog(MongoDBTokenStore.class);
private AuthenticationKeyGenerator authenticationKeyGenerator = new DefaultAuthenticationKeyGenerator();
#Autowired
AccessTokenRepository accessTokenRepository;
#Autowired
RefreshTokenRepository refreshTokenRepository;
#Value("${spring.data.mongodb.uri}")
String mongo_uri;
#Value("${spring.data.mongodb.host}")
String mongo_host;
#Value("${spring.data.mongodb.database}")
String mongo_database;
#Value("${spring.data.mongodb.port}")
String mongo_port;
public MongoDBTokenStore() {
//MongoClient mongoClient = new MongoClient();
//Assert.notNull(mongoTemplate, "DataSource required");
}
public void setAuthenticationKeyGenerator(AuthenticationKeyGenerator authenticationKeyGenerator) {
this.authenticationKeyGenerator = authenticationKeyGenerator;
}
public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
OAuth2AccessToken accessToken = null;
String key = authenticationKeyGenerator.extractKey(authentication);
try {
AccessTockenElement element = accessTokenRepository.findByAuthenticationId(key);
accessToken = element.getOAuth2AccessToken();
}
catch (EmptyResultDataAccessException e) {
if (LOG.isDebugEnabled()) {
LOG.debug("Failed to find access token for authentication " + authentication);
}
}
catch (IllegalArgumentException e) {
LOG.error("Could not extract access token for authentication " + authentication, e);
}
if (accessToken != null
&& !key.equals(authenticationKeyGenerator.extractKey(readAuthentication(accessToken.getValue())))) {
removeAccessToken(accessToken.getValue());
// Keep the store consistent (maybe the same user is represented by this authentication but the details have
// changed)
storeAccessToken(accessToken, authentication);
}
return accessToken;
}
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
String refreshToken = null;
if (token.getRefreshToken() != null) {
refreshToken = token.getRefreshToken().getValue();
}
if (readAccessToken(token.getValue())!=null) {
removeAccessToken(token.getValue());
}
AccessTockenElement element = new AccessTockenElement();
element.setTokenId(extractTokenKey(token.getValue()));
element.setOAuth2AccessToken(token);
element.setAuthenticationId(authenticationKeyGenerator.extractKey(authentication));
element.setUsername(authentication.isClientOnly() ? null : authentication.getName());
element.setClientId(authentication.getOAuth2Request().getClientId());
element.setOAuth2Authentication(authentication);
element.setRefreshToken(extractTokenKey(refreshToken));
accessTokenRepository.save(element);
}
public OAuth2AccessToken readAccessToken(String tokenValue) {
OAuth2AccessToken accessToken = null;
try {
AccessTockenElement element = accessTokenRepository.findByTokenId(extractTokenKey(tokenValue));
accessToken = element.getOAuth2AccessToken();
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for token " + tokenValue);
}
}
catch (IllegalArgumentException e) {
LOG.warn("Failed to deserialize access token for " + tokenValue, e);
removeAccessToken(tokenValue);
}
return accessToken;
}
public void removeAccessToken(OAuth2AccessToken token) {
removeAccessToken(token.getValue());
}
public void removeAccessToken(String tokenValue) {
accessTokenRepository.delete(extractTokenKey(tokenValue));
//jdbcTemplate.update(deleteAccessTokenSql, extractTokenKey(tokenValue));
}
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
return readAuthentication(token.getValue());
}
public OAuth2Authentication readAuthentication(String token) {
OAuth2Authentication authentication = null;
try {
AccessTockenElement element = accessTokenRepository.findByTokenId(extractTokenKey(token));
authentication = element.getOAuth2Authentication();
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for token " + token);
}
}
catch (IllegalArgumentException e) {
LOG.warn("Failed to deserialize authentication for " + token, e);
removeAccessToken(token);
}
return authentication;
}
public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
RefreshTockenElement element = new RefreshTockenElement();
element.setTokenId(extractTokenKey(refreshToken.getValue()));
element.setOAuth2RefreshToken(refreshToken);
element.setOAuth2Authentication(authentication);
refreshTokenRepository.save(element);
}
public OAuth2RefreshToken readRefreshToken(String token) {
OAuth2RefreshToken refreshToken = null;
try {
RefreshTockenElement element = refreshTokenRepository.findByTokenId(extractTokenKey(token));
refreshToken = element.getOAuth2RefreshToken();
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find refresh token for token " + token);
}
}
catch (IllegalArgumentException e) {
LOG.warn("Failed to deserialize refresh token for token " + token, e);
removeRefreshToken(token);
}
return refreshToken;
}
public void removeRefreshToken(OAuth2RefreshToken token) {
removeRefreshToken(token.getValue());
}
public void removeRefreshToken(String token) {
refreshTokenRepository.delete(extractTokenKey(token));
}
public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return readAuthenticationForRefreshToken(token.getValue());
}
public OAuth2Authentication readAuthenticationForRefreshToken(String value) {
OAuth2Authentication authentication = null;
try {
RefreshTockenElement element = refreshTokenRepository.findByTokenId(extractTokenKey(value));
authentication = element.getOAuth2Authentication();
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for token " + value);
}
}
catch (IllegalArgumentException e) {
LOG.warn("Failed to deserialize access token for " + value, e);
removeRefreshToken(value);
}
return authentication;
}
public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
removeAccessTokenUsingRefreshToken(refreshToken.getValue());
}
public void removeAccessTokenUsingRefreshToken(String refreshToken) {
accessTokenRepository.deleteByRefreshToken(extractTokenKey(refreshToken));
}
public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();
try {
List<AccessTockenElement> elements = accessTokenRepository.findByClientId(clientId);
for (AccessTockenElement element : elements) {
accessTokens.add(element.getOAuth2AccessToken());
}
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for clientId " + clientId);
}
}
accessTokens = removeNulls(accessTokens);
return accessTokens;
}
public Collection<OAuth2AccessToken> findTokensByUserName(String userName) {
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();
try {
List<AccessTockenElement> elements = accessTokenRepository.findByUsername(userName);
for (AccessTockenElement element : elements) {
accessTokens.add(element.getOAuth2AccessToken());
}
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled())
LOG.info("Failed to find access token for userName " + userName);
}
accessTokens = removeNulls(accessTokens);
return accessTokens;
}
public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
List<OAuth2AccessToken> accessTokens = new ArrayList<OAuth2AccessToken>();
try {
List<AccessTockenElement> elements = accessTokenRepository.findByClientIdAndUsername(clientId, userName);
for (AccessTockenElement element : elements) {
accessTokens.add(element.getOAuth2AccessToken());
}
}
catch (EmptyResultDataAccessException e) {
if (LOG.isInfoEnabled()) {
LOG.info("Failed to find access token for clientId " + clientId + " and userName " + userName);
}
}
accessTokens = removeNulls(accessTokens);
return accessTokens;
}
private List<OAuth2AccessToken> removeNulls(List<OAuth2AccessToken> accessTokens) {
List<OAuth2AccessToken> tokens = new ArrayList<OAuth2AccessToken>();
for (OAuth2AccessToken token : accessTokens) {
if (token != null) {
tokens.add(token);
}
}
return tokens;
}
protected String extractTokenKey(String value) {
if (value == null) {
return null;
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm not available. Fatal (should be in the JDK).");
}
try {
byte[] bytes = digest.digest(value.getBytes("UTF-8"));
return String.format("%032x", new BigInteger(1, bytes));
}
catch (UnsupportedEncodingException e) {
throw new IllegalStateException("UTF-8 encoding not available. Fatal (should be in the JDK).");
}
}
protected byte[] serializeAccessToken(OAuth2AccessToken token) {
return SerializationUtils.serialize(token);
}
protected byte[] serializeRefreshToken(OAuth2RefreshToken token) {
return SerializationUtils.serialize(token);
}
protected byte[] serializeAuthentication(OAuth2Authentication authentication) {
return SerializationUtils.serialize(authentication);
}
protected OAuth2AccessToken deserializeAccessToken(byte[] token) {
return SerializationUtils.deserialize(token);
}
protected OAuth2RefreshToken deserializeRefreshToken(byte[] token) {
return SerializationUtils.deserialize(token);
}
protected OAuth2Authentication deserializeAuthentication(byte[] authentication) {
return SerializationUtils.deserialize(authentication);
}
#Document
#Setter
#Getter
class AccessTockenElement {
#Id
String tokenId;
OAuth2AccessToken OAuth2AccessToken;
#Indexed
String authenticationId;
#Indexed
String username;
#Indexed
String clientId;
OAuth2Authentication OAuth2Authentication;
#Indexed
String refreshToken;
}
#Document
#Setter
#Getter
class RefreshTockenElement {
#Id
String tokenId;
OAuth2RefreshToken OAuth2RefreshToken;
OAuth2Authentication OAuth2Authentication;
}
#RepositoryRestResource
interface AccessTokenRepository extends MongoRepository<AccessTockenElement, String> {
#Transactional
public AccessTockenElement findByTokenId(String tokenId);
#Transactional
public AccessTockenElement findByAuthenticationId(String tokenId);
#Transactional
public List<AccessTockenElement> findByClientId(String clientId);
#Transactional
public List<AccessTockenElement> findByUsername(String username);
#Transactional
public List<AccessTockenElement> findByClientIdAndUsername(String clientId, String username);
#Transactional
public void deleteByRefreshToken(String refreshTokenId);
}
#RepositoryRestResource
public interface RefreshTokenRepository extends MongoRepository<RefreshTockenElement, String> {
#Transactional
public RefreshTockenElement findByTokenId(String tokenId);
}
}
The calling to that TokenStore is like that:
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends
AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new MongoDBTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private ExtendedUserDetailsService userDetailsService;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints
.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
}
.
.
.
}
#Autowired and #Value fields are null because MongoDBTokenStore is not a bean actually. It created by new and Spring knows nothing about it.
Annotate MongoDBTokenStore class with #Component or create it by #Bean factory method.
Also, check out this implementation MongoTokenStore, I think this is exactly what you're looking for.

Why is this cache not getting evicted?

AdminSOAPRunner:
#Component
public class AdminSOAPRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(AdminSOAPRunner.class);
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
#Autowired
private AdminAuth adminAuthenticator;
#Autowired
private AdminBean adminBean;
private AccountService accountService;
private void setBindingProviderByAccountService() {
WSBindingProvider bindingProvider = (WSBindingProvider) this.accountService;
bindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, adminBean.getAccountUrl());
LOGGER.info("Endpoint {}", adminBean.getAccountUrl());
}
private RequestInfo getRequestInfo() {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setAppName(adminBean.getAppName());
requestInfo.setUserId(this.getUserId());
requestInfo.setTrace(UUID.randomUUID().toString());
return requestInfo;
}
public List<ApplyAccountResult> getAccounts(ApplyAccountRequest request) {
AccountService_Service service = null;
URL serviceWSDL = AccountService_Service.class.getResource("/Account-service/Account-service.wsdl");
service = new AccountService_Service(serviceWSDL);
SOAPHandlerResolver SOAPHandlerResolver = new SOAPHandlerResolver();
SOAPHandlerResolver.getHandlerList().add(new SOAPHandler(this.adminAuthenticator));
service.setHandlerResolver(SOAPHandlerResolver);
if (accountService == null) {
accountService = service.getAccountService();
}
setBindingProviderByAccountService();
ApplyAccountAccountResponse response = null;
LOGGER.info("Making a SOAP request.");
response = AccountService.applyAccount(request, getRequestInfo(), new Holder<ResponseInfo>());
LOGGER.info("SOAP request completed.");
return response.getApplyAccountResults();
}
SOAPHandlerResolver:
public class SOAPHandlerResolver implements HandlerResolver {
#SuppressWarnings("rawtypes")
private List<Handler> handlerList;
public SOAPHandlerResolver() {
this.handlerList = null;
}
#SuppressWarnings("rawtypes")
public List<Handler> getHandlerList() {
if (this.handlerList == null) {
this.handlerList = new ArrayList<>();
}
return this.handlerList;
}
#SuppressWarnings("rawtypes")
#Override
public List<Handler> getHandlerChain(PortInfo portInfo) {
List<Handler> handlerChain = new ArrayList<>();
if (this.handlerList == null || this.handlerList.isEmpty()) {
this.handlerList = new ArrayList<>();
this.handlerList.add(new SOAPHandler(null));
}
handlerChain.addAll(this.handlerList);
return handlerChain;
}
}
SOAPHandler
public class SOAPHandler implements SOAPHandler<SOAPMessageContext> {
private AdminAuth adminAuth;
private static final Logger LOGGER = LoggerFactory.getLogger(SOAPHandler.class);
public MosaicOnboardSOAPHandler(AdminAuth adminAuth) {
if (adminAuth == null) {
adminAuth = new AdminAuth();
LOGGER.info("AdminAuth found null. Creating new adminAuth instance.");
}
this.adminAuth = adminAuth;
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty) {
#SuppressWarnings("unchecked")
Map<String, List<String>> headers = (Map<String, List<String>>) context.get(MessageContext.HTTP_REQUEST_HEADERS);
if (headers == null) {
headers = new HashMap<>();
context.put(MessageContext.HTTP_REQUEST_HEADERS, headers);
}
List<String> cookie = headers.get("Cookie");
if (cookie == null) {
cookie = new ArrayList<>();
headers.put("Cookie", cookie);
}
cookie.add(this.adminAuth.getToken());
}
return true;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
return false;
}
#Override
public void close(MessageContext context) {
}
#Override
public Set<QName> getHeaders() {
return null;
}
}
AdminAuth:
#Component
public class AdminAuth {
#Autowired
private AdminBean adminBean;
private static final Logger LOG = LoggerFactory.getLogger(Admin.class);
private String token;
private void generateToken() {
try {
AdminTokenHelper adminTokenHelper = new AdminTokenHelper(adminBean.getAutheticationServerURL(), adminBean.getLicense());
token = adminTokenHelper.getToken(adminBean.getUsername(), adminBean.getPassword().toCharArray());
LOG.info("Token generation successful");
} catch (Exception ex) {
ex.printStackTrace();
LOG.error("Token generation failed");
LOG.error(ex.getMessage());
throw new RuntimeException("Token generation failed", ex);
}
}
#Cacheable(value = "tokenCache")
public String getToken() {
LOG.warn("Token not available. Generating a new token.");
generateToken();
return token;
}
}
ehcache.xml
<cache name="tokenCache" maxEntriesLocalHeap="1" eternal="false" timeToIdleSeconds="895" timeToLiveSeconds="895" memoryStoreEvictionPolicy="LRU"/>
Applcation
#EnableCaching
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(final String[] args) {
SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
return application.sources(Application.class).profiles(determineEnvironmentProfile());
}
}
In AdminAuth, it uses functional user to generate token. the token generated for authentication expires in 15 minutes. So my purpose was to write cache so that all the calls from ui can use the same token regardless of actual user. So i set the time 14:55 to generate new token. Now the problem comes when it's after 15 minutes and the cache doesn't evict the old toeken so that call uses the old and expired token and it fails.
I tried different eviction policies like LRU, LFU, FiFO but nothing is working. The calls are coming from ui through tomcat container in spring boot 1.3.
Why is this not getting evicted? What am i missing? Any help is appreciated
Replace #Cacheable(value = "tokenCache") with #Cacheable("tokenCache")
From the comments:
The dependency on spring-boot-starter-cache was missing. This prevented Spring Boot from automatically configuring the CacheManager. Once this dependency was added, the cache configuration worked.
See http://docs.spring.io/spring-boot/docs/1.3.x/reference/html/boot-features-caching.html

Categories