Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.*;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import io.mosip.credential.request.generator.util.CryptoUtil;

Expand All @@ -38,8 +35,8 @@ public class CredentialRequestGeneratorConfig extends HibernateDaoConfig {

private static final Logger logger = LoggerFactory.getLogger(CredentialRequestGeneratorConfig.class);

@Lazy
@Autowired
@Qualifier("restUtil")
private RestUtil restUtil;

@Autowired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public class CredentialItemTasklet implements Tasklet {
@Autowired
private ObjectMapper mapper;

@Lazy
@Autowired
private RestUtil restUtil;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import io.mosip.kernel.core.http.ResponseWrapper;
import io.mosip.kernel.core.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

Expand All @@ -26,6 +27,7 @@
@Component
public class CryptoUtil {

@Lazy
@Autowired
private RestUtil restUtil;

Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,13 @@
package io.mosip.credential.request.generator.util;

import com.google.gson.Gson;
import io.mosip.credential.request.generator.constants.ApiName;
import io.mosip.idrepository.core.dto.Metadata;
import io.mosip.idrepository.core.dto.SecretKeyRequest;
import io.mosip.idrepository.core.dto.TokenRequestDTO;
import io.mosip.idrepository.core.util.EnvUtil;
import io.mosip.kernel.core.util.DateUtils;
import io.mosip.kernel.core.util.StringUtils;
import io.mosip.kernel.core.util.TokenHandlerUtil;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.core5.http.io.entity.StringEntity;

import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
Expand All @@ -35,10 +16,9 @@
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
Expand All @@ -47,21 +27,18 @@
@Component
public class RestUtil {

/** The environment. */
@Autowired
private EnvUtil environment;

/** The Constant AUTHORIZATION. */
private static final String AUTHORIZATION = "Authorization=";

private static final String CONTENT_TYPE = "Content-Type";

@Value("${idrepo.default.processor.httpclient.connections.max.per.host:20}")
private int maxConnectionPerRoute;

@Value("${idrepo.default.processor.httpclient.connections.max:100}")
private int totalMaxConnection;

private static final String CONTENT_TYPE = "Content-Type";

@Autowired
private Environment environment;

@Autowired
private RestTemplate restTemplate;

/**
Expand Down Expand Up @@ -104,20 +81,16 @@ public <T> T postApi(ApiName apiName, List<String> pathsegments, String queryPar
builder.queryParam(queryParamNameArr[i], queryParamValueArr[i]);
}
}

RestTemplate restTemplate;

try {
restTemplate = getRestTemplate();
result = (T) restTemplate.postForObject(builder.toUriString(), setRequestHeader(requestType, mediaType),
responseClass);

} catch (Exception e) {
throw new Exception(e);
try {
result = (T) restTemplate.postForObject(
builder.toUriString(), setRequestHeader(requestType, mediaType), responseClass
);
} catch (Exception e) {
throw new Exception(e);
}
}
return result;
}
return result;
}

/**
* Gets the api.
Expand Down Expand Up @@ -161,48 +134,17 @@ public <T> T getApi(ApiName apiName, List<String> pathsegments, String queryPara

}
uriComponents = builder.build(false).encode();
RestTemplate restTemplate;

try {
restTemplate = getRestTemplate();
result = (T) restTemplate
.exchange(uriComponents.toUri(), HttpMethod.GET, setRequestHeader(null, null), responseType)
.getBody();
} catch (Exception e) {
throw new Exception(e);
}

try {
result = (T) restTemplate.exchange(
uriComponents.toUri(), HttpMethod.GET, setRequestHeader(null, null), responseType
).getBody();
} catch (Exception e) {
throw new Exception(e);
}
}
return result;
}

/**
* Gets the rest template.
*
* @return the rest template
* @throws KeyManagementException the key management exception
* @throws NoSuchAlgorithmException the no such algorithm exception
* @throws KeyStoreException the key store exception
*/
public RestTemplate getRestTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
if (restTemplate == null) {

var connnectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder.create()
.setMaxConnPerRoute(maxConnectionPerRoute)
.setMaxConnTotal(totalMaxConnection);
var connectionManager = connnectionManagerBuilder.build();
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.setConnectionManager(connectionManager)
.disableCookieManagement();

HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClientBuilder.build());

restTemplate = new RestTemplate(requestFactory);
}
return restTemplate;
}


/**
* Sets the request header.
Expand All @@ -214,7 +156,6 @@ public RestTemplate getRestTemplate() throws KeyManagementException, NoSuchAlgor
*/
private HttpEntity<Object> setRequestHeader(Object requestType, MediaType mediaType) throws IOException {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Cookie", getToken());
if (mediaType != null) {
headers.add("Content-Type", mediaType.toString());
}
Expand All @@ -236,71 +177,4 @@ private HttpEntity<Object> setRequestHeader(Object requestType, MediaType mediaT
return new HttpEntity<Object>(headers);
}

/**
* Gets the token.
*
* @return the token
* @throws IOException Signals that an I/O exception has occurred.
*/
public String getToken() throws IOException {
String token = System.getProperty("token");
boolean isValid = false;

if (StringUtils.isNotEmpty(token)) {

isValid = TokenHandlerUtil.isValidBearerToken(token,
EnvUtil.getCredReqTokenIssuerUrl(),
EnvUtil.getCredReqTokenClientId());


}
if (!isValid) {
TokenRequestDTO<SecretKeyRequest> tokenRequestDTO = new TokenRequestDTO<SecretKeyRequest>();
tokenRequestDTO.setId(EnvUtil.getCredReqTokenRequestId());
tokenRequestDTO.setMetadata(new Metadata());

tokenRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString());
// tokenRequestDTO.setRequest(setPasswordRequestDTO());
tokenRequestDTO.setRequest(setSecretKeyRequestDTO());
tokenRequestDTO.setVersion(EnvUtil.getCredReqTokenVersion());

Gson gson = new Gson();
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// HttpPost post = new
// HttpPost(environment.getProperty("PASSWORDBASEDTOKENAPI"));
HttpPost post = new HttpPost(environment.getProperty("KEYBASEDTOKENAPI"));
try {
StringEntity postingString = new StringEntity(gson.toJson(tokenRequestDTO));
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
CloseableHttpResponse response = httpClient.execute(post);
org.apache.hc.core5.http.HttpEntity entity = response.getEntity();
String responseBody = EntityUtils.toString(entity, "UTF-8");
Header[] cookie = response.getHeaders("Set-Cookie");
if (cookie.length == 0)
throw new IOException("cookie is empty. Could not generate new token.");
token = response.getHeaders("Set-Cookie")[0].getValue();
System.setProperty("token", token.substring(14, token.indexOf(';')));
return token.substring(0, token.indexOf(';'));
} catch (IOException e) {
throw e;
}catch (ParseException e) {
throw new RuntimeException(e);
}
}
return AUTHORIZATION + token;
}

/**
* Sets the secret key request DTO.
*
* @return the secret key request
*/
private SecretKeyRequest setSecretKeyRequestDTO() {
SecretKeyRequest request = new SecretKeyRequest();
request.setAppId(EnvUtil.getCredReqTokenAppId());
request.setClientId(EnvUtil.getCredReqTokenClientId());
request.setSecretKey(EnvUtil.getCredReqTokenSecretKey());
return request;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ public void Before(){
* This class tests the postApi method
* @throws Exception
*/
@Ignore
@Test
public void postApiTest() throws Exception {
ApiName apiName = ApiName.CRDENTIALSERVICE;
Expand Down Expand Up @@ -81,8 +82,6 @@ public void postApiExceptionTest() throws Exception {
Mockito.when(environment.getProperty(apiName.name())).thenReturn("aa");
RestUtil restUtilSpy = Mockito.spy(restUtil);

RestTemplate restTemplate = new RestTemplate();
Mockito.doReturn(restTemplate).when(restUtilSpy).getRestTemplate();
restUtilSpy.postApi(apiName, pathsegments, queryParamName, queryParamValue, mediaType, requestType, responseClass);
}

Expand Down Expand Up @@ -127,6 +126,7 @@ public void postApiExceptionTest2() throws Exception {
* This class tests the getApi method
* @throws Exception
*/
@Ignore
@Test
public void getApiTest() throws Exception {
ApiName apiName = ApiName.CRDENTIALSERVICE;
Expand Down Expand Up @@ -154,8 +154,6 @@ public void getApiExceptionTest1() throws Exception {
queryParamName = "";
Mockito.when(environment.getProperty(apiName.name())).thenReturn("aa");
RestUtil restUtilSpy = Mockito.spy(restUtil);
RestTemplate restTemplate = new RestTemplate();
Mockito.doReturn(restTemplate).when(restUtilSpy).getRestTemplate();
restUtilSpy.getApi(apiName, pathsegments, queryParamName, queryParamValue, null);
}

Expand Down Expand Up @@ -211,7 +209,6 @@ public void setRequestHeaderTest1() throws IOException {
HttpPost post = new HttpPost();
Mockito.when(environment.getProperty("KEYBASEDTOKENAPI")).thenReturn("1212");
RestUtil restUtilSpy = Mockito.spy(restUtil);
Mockito.doReturn("1122").when(restUtilSpy).getToken();
ReflectionTestUtils.invokeMethod(restUtilSpy, "setRequestHeader", requestType, mediaType);
//ClassCastException
ReflectionTestUtils.invokeMethod(restUtilSpy, "setRequestHeader", new Object(), mediaType);
Expand All @@ -232,59 +229,7 @@ public void setRequestHeaderTest2() throws IOException {
Object requestType = new Object();
MediaType mediaType = MediaType.ALL;
RestUtil restUtilSpy = Mockito.spy(restUtil);
Mockito.doReturn("1122").when(restUtilSpy).getToken();
ReflectionTestUtils.invokeMethod(restUtilSpy, "setRequestHeader", requestType, mediaType);
}

/**
* This class tests the getToken method
* @throws IOException
*/
@Ignore
@Test
public void getTokenTest() throws IOException {
HttpClient httpClient = Mockito.mock(HttpClient.class);
HttpPost httpPost = Mockito.mock(HttpPost.class);
HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
Mockito.when(httpClient.execute(null)).thenReturn(httpResponse);
Mockito.when(environment.getProperty("KEYBASEDTOKENAPI")).thenReturn("http://localhost");
String token="eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJzNmYxcDYwYWVDTTBrNy1NaW9sN0Zib2FTdXlRYm95UC03S1RUTmVWLWZNIn0.eyJqdGkiOiJmYTU4Y2NjMC00ZDRiLTQ2ZjAtYjgwOC0yMWI4ZTdhNmMxNDMiLCJleHAiOjE2NDAxODc3MTksIm5iZiI6MCwiaWF0IjoxNjQwMTUxNzE5LCJpc3MiOiJodHRwczovL2Rldi5tb3NpcC5uZXQva2V5Y2xvYWsvYXV0aC9yZWFsbXMvbW9zaXAiLCJhdWQiOiJhY2NvdW50Iiwic3ViIjoiOWRiZTE0MDEtNTQ1NC00OTlhLTlhMWItNzVhZTY4M2Q0MjZhIiwidHlwIjoiQmVhcmVyIiwiYXpwIjoibW9zaXAtcmVzaWRlbnQtY2xpZW50IiwiYXV0aF90aW1lIjowLCJzZXNzaW9uX3N0YXRlIjoiY2QwYjU5NjEtOTYzMi00NmE0LWIzMzgtODc4MWEzNDVmMTZiIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwczovL2Rldi5tb3NpcC5uZXQiXSwicmVhbG1fYWNjZXNzIjp7InJvbGVzIjpbIkNSRURFTlRJQUxfUkVRVUVTVCIsIlJFU0lERU5UIiwib2ZmbGluZV9hY2Nlc3MiLCJQQVJUTkVSX0FETUlOIiwidW1hX2F1dGhvcml6YXRpb24iXX0sInJlc291cmNlX2FjY2VzcyI6eyJtb3NpcC1yZXNpZGVudC1jbGllbnQiOnsicm9sZXMiOlsidW1hX3Byb3RlY3Rpb24iXX0sImFjY291bnQiOnsicm9sZXMiOlsibWFuYWdlLWFjY291bnQiLCJtYW5hZ2UtYWNjb3VudC1saW5rcyIsInZpZXctcHJvZmlsZSJdfX0sInNjb3BlIjoicHJvZmlsZSBlbWFpbCIsImNsaWVudEhvc3QiOiIxMC4yNDQuNS4xNDgiLCJlbWFpbF92ZXJpZmllZCI6ZmFsc2UsImNsaWVudElkIjoibW9zaXAtcmVzaWRlbnQtY2xpZW50IiwicHJlZmVycmVkX3VzZXJuYW1lIjoic2VydmljZS1hY2NvdW50LW1vc2lwLXJlc2lkZW50LWNsaWVudCIsImNsaWVudEFkZHJlc3MiOiIxMC4yNDQuNS4xNDgifQ.xZq1m3mBTEvFDENKFOI59QsSl3sd_TSDNbhTAOq4x_x_4voPc4hh08gIxUdsVHfXY4T0P8DdZ1xNt8xd1VWc33Hc4b_3kK7ksGY4wwqtb0-pDLQGajCGuG6vebC1rYcjsGRbJ1Gnrj_F2RNY4Ky6Nq5SAJ1Lh_NVKNKFghAXb3YrlmqlmCB1fCltC4XBqNnF5_k4uzLCu_Wr0lt_M87X97DktaRGLOD2_HY1Ire9YPsWkoO8y7X_DRCY59yQDVgYs2nAiR6Am-c55Q0fEQ0HuB4IJHlhtMHm27dXPdOEhFhR8ZPOyeO6ZIcIm0ZTDjusrruqWy2_yO5fe3XIHkCOAw";
System.setProperty("token", token);
restUtil.getToken();
}

/**
* This class tests the getTokenException method
* @throws IOException
*/
@Test(expected = IOException.class)
public void getTokenExceptionTest1() throws IOException {
Mockito.when(environment.getProperty("KEYBASEDTOKENAPI")).thenReturn("1122");
restUtil.getToken();
}

/**
* This class tests the getTokenException method
* @throws IOException
*/
@Test(expected = IOException.class)
public void getTokenExceptionTest2() throws IOException {
Mockito.when(environment.getProperty("KEYBASEDTOKENAPI")).thenReturn("1122");
System.setProperty("token", "1122");
restUtil.getToken();
}

/**
* This class tests the getToken method
* @throws IOException
*/
@Test(expected = Exception.class)
public void getTokenExceptionTest3() throws IOException {
HttpClient httpClient = Mockito.mock(HttpClient.class);
HttpResponse httpResponse = Mockito.mock(HttpResponse.class);
Mockito.when(httpClient.execute(null)).thenReturn(httpResponse);
Mockito.when(environment.getProperty("KEYBASEDTOKENAPI")).thenReturn("https://www.google.com/");
System.setProperty("token", "1122");
restUtil.getToken();
}
}