diff --git a/.github/keys/mosipgpgkey_pub.gpg b/.github/keys/mosipgpgkey_pub.gpg index 86e5dfe3..4bdb1a94 100644 Binary files a/.github/keys/mosipgpgkey_pub.gpg and b/.github/keys/mosipgpgkey_pub.gpg differ diff --git a/.github/keys/mosipgpgkey_sec.gpg b/.github/keys/mosipgpgkey_sec.gpg index b0180d54..97de5567 100644 Binary files a/.github/keys/mosipgpgkey_sec.gpg and b/.github/keys/mosipgpgkey_sec.gpg differ diff --git a/.github/workflows/push_trigger.yml b/.github/workflows/push_trigger.yml index 174282cd..a6930c1f 100644 --- a/.github/workflows/push_trigger.yml +++ b/.github/workflows/push_trigger.yml @@ -102,16 +102,65 @@ jobs: - name: Publish the maven package run: | - cd data-share && mvn deploy -DskipTests -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml + cd data-share && mvn deploy -DaltDeploymentRepository=ossrh::default::${{ secrets.RELEASE_URL }} -s $GITHUB_WORKSPACE/settings.xml -f pom.xml env: GITHUB_TOKEN: ${{ secrets.RELEASE_TOKEN }} GPG_TTY: $(tty) - - name: Analyze with SonarCloud - run: | - mvn -B verify sonar:sonar -Dsonar.projectKey=${{ secrets.PROJECT_KEY }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + + sonar_analysis: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v1 + with: + ref: ${{ github.ref }} + java-version: 11 + server-id: ossrh # Value of the distributionManagement/repository/id field of the pom.xml + settings-path: ${{ github.workspace }} # location for the settings.xml file + + - name: Setup branch and GPG public key + run: | + # Strip git ref prefix from version + echo ${{ env.BRANCH_NAME }} + echo ${{ env.GPG_TTY }} + sudo apt-get --yes install gnupg2 + gpg2 --import ./.github/keys/mosipgpgkey_pub.gpg + gpg2 --quiet --batch --passphrase=${{secrets.gpg_secret}} --allow-secret-key-import --import ./.github/keys/mosipgpgkey_sec.gpg + + - uses: actions/cache@v1 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} + + - name: Install xmllint + run: | + sudo apt-get update + sudo apt-get install libxml2-utils + + - name: Setup the settings file for ossrh server + run: echo " ossrh ${{secrets.RELEASE_USER}} ${{secrets.RELEASE_TOKEN}} ossrh true gpg2 ${{secrets.gpg_secret}} allow-snapshots true snapshots-repo https://oss.sonatype.org/content/repositories/snapshots false true releases-repo https://oss.sonatype.org/service/local/staging/deploy/maven2 true false sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml + + - name: Build with Maven + run: | + mvn -B package -s $GITHUB_WORKSPACE/settings.xml --file pom.xml + + - name: Analyze with SonarCloud + run: | + mvn -B -Dgpg.skip verify sonar:sonar -Dsonar.projectKey=mosip_${{ github.event.repository.name }} -Dsonar.organization=${{ secrets.ORG_KEY }} -Dsonar.host.url=https://sonarcloud.io -Dsonar.login=${{ secrets.SONAR_TOKEN }} + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} + - uses: 8398a7/action-slack@v3 + with: + status: ${{ job.status }} + fields: repo,message,commit,workflow,job # selectable (default: repo,message) + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_DEVOPS_WEBHOOK }} # required + if: failure() # Pick up events even if the job fails or is canceled. + docker-data-share-service: needs: build diff --git a/.github/workflows/release_changes.yml b/.github/workflows/release_changes.yml new file mode 100644 index 00000000..c6febb6c --- /dev/null +++ b/.github/workflows/release_changes.yml @@ -0,0 +1,56 @@ +name: Release/pre-release Preparation. + +on: + workflow_dispatch: + inputs: + message: + description: 'Triggered for release or pe-release' + required: false + default: 'Release Preparation' + releaseTags: + description: 'tag to update' + required: true + snapshotTags: + description: 'tag to be replaced' + required: true + base: + description: 'base branch for PR' + required: true +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Setup branch and env + run: | + # Strip git ref prefix from version + echo "BRANCH_NAME=$(echo ${{ github.ref }} | sed -e 's,.*/\(.*\),\1,')" >> $GITHUB_ENV + echo "GPG_TTY=$(tty)" >> $GITHUB_ENV + + - name: Mannualy changing the pom versions + run: find . -type f -name "*pom.xml" -print0 | xargs -0 sed -i "s/${{ github.event.inputs.snapshotTags }}/${{ github.event.inputs.releaseTags }}/g" + + - name: Updating the Release URL in POM + run: | + cd .github/workflows + sed -i 's/OSSRH_SNAPSHOT_URL/RELEASE_URL/g' push_trigger.yml + + - name: Updating libs-snapshot-local to libs-release local for artifactory URL's. + run: find . -type f -name "*Dockerfile" -print0 | xargs -0 sed -i "s/libs-snapshot-local/libs-release-local/g" + + - name: removing -DskipTests + run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-DskipTests"//g" + +# - name: removing --Dgpg.skip +# run: find . -type f -name "*push_trigger.yml" -print0 | xargs -0 sed -i "s/"-Dgpg.skip"//g" + + - name: Create Pull Request + uses: peter-evans/create-pull-request@v3 + with: + commit-message: Updated Pom versions for release changes + title: Release changes + body: Automated PR for ${{ github.event.inputs.releaseTags }} release. + branch: release-branch + delete-branch: true + base: ${{ github.event.inputs.base }} + token: ${{ secrets.ACTION_PAT }} diff --git a/data-share/data-share-service/pom.xml b/data-share/data-share-service/pom.xml index 06233026..f48efe47 100644 --- a/data-share/data-share-service/pom.xml +++ b/data-share/data-share-service/pom.xml @@ -5,11 +5,11 @@ io.mosip.datashare data-share - 1.2.0-SNAPSHOT + 1.1.5.3-P2 data-share-service - 1.2.0-SNAPSHOT + 1.1.5.3-P2 data-share-service @@ -95,7 +95,7 @@ ${kernel.logger.logback.version} - io.mosip.commons. + io.mosip.commons khazana ${kernel.object.store.version} @@ -124,7 +124,7 @@ javax.xml.bind jaxb-api - 2.3.0 + 2.3.1 diff --git a/data-share/data-share-service/src/main/java/io/mosip/datashare/util/RestUtil.java b/data-share/data-share-service/src/main/java/io/mosip/datashare/util/RestUtil.java index d075cf70..b744e148 100644 --- a/data-share/data-share-service/src/main/java/io/mosip/datashare/util/RestUtil.java +++ b/data-share/data-share-service/src/main/java/io/mosip/datashare/util/RestUtil.java @@ -1,334 +1,350 @@ -package io.mosip.datashare.util; -import java.io.IOException; -import java.net.URI; -import java.security.KeyManagementException; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.X509Certificate; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLContext; - -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.ssl.TrustStrategy; -import org.apache.http.util.EntityUtils; -import org.springframework.beans.factory.annotation.Autowired; -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; -import org.springframework.web.client.RestTemplate; -import org.springframework.web.util.UriComponents; -import org.springframework.web.util.UriComponentsBuilder; - -import com.google.gson.Gson; - -import io.mosip.datashare.constant.ApiName; -import io.mosip.datashare.dto.Metadata; -import io.mosip.datashare.dto.PasswordRequest; -import io.mosip.datashare.dto.SecretKeyRequest; -import io.mosip.datashare.dto.TokenRequestDTO; -import io.mosip.datashare.exception.ApiNotAccessibleException; -import io.mosip.kernel.core.util.DateUtils; -import io.mosip.kernel.core.util.StringUtils; -import io.mosip.kernel.core.util.TokenHandlerUtil; - - -/** - * @author Sowmya The Class RestUtil. - */ -@Component -public class RestUtil { - - /** The environment. */ - @Autowired - private Environment environment; - - /** The Constant AUTHORIZATION. */ - private static final String AUTHORIZATION = "Authorization="; - - /** - * Post api. - * - * @param the generic type - * @param apiName the api name - * @param pathsegments the pathsegments - * @param queryParamName the query param name - * @param queryParamValue the query param value - * @param mediaType the media type - * @param requestType the request type - * @param responseClass the response class - * @return the t - * @throws ApiNotAccessibleException the api not accessible exception - */ - @SuppressWarnings("unchecked") - public T postApi(ApiName apiName, List pathsegments, String queryParamName, String queryParamValue, - MediaType mediaType, Object requestType, Class responseClass) throws ApiNotAccessibleException { - T result = null; - String apiHostIpPort = environment.getProperty(apiName.name()); - UriComponentsBuilder builder = null; - if (apiHostIpPort != null) - builder = UriComponentsBuilder.fromUriString(apiHostIpPort); - if (builder != null) { - - if (!((pathsegments == null) || (pathsegments.isEmpty()))) { - for (String segment : pathsegments) { - if (!((segment == null) || (("").equals(segment)))) { - builder.pathSegment(segment); - } - } - - } - if (!((queryParamName == null) || (("").equals(queryParamName)))) { - String[] queryParamNameArr = queryParamName.split(","); - String[] queryParamValueArr = queryParamValue.split(","); - - for (int i = 0; i < queryParamNameArr.length; i++) { - 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 ApiNotAccessibleException(e); - } - } - return result; - } - - /** - * Gets the api. - * - * @param the generic type - * @param apiName the api name - * @param pathsegments the pathsegments - * @param queryParamName the query param name - * @param queryParamValue the query param value - * @param responseType the response type - * @return the api - * @throws ApiNotAccessibleException the api not accessible exception - */ - @SuppressWarnings("unchecked") - public T getApi(ApiName apiName, List pathsegments, String queryParamName, String queryParamValue, - Class responseType) throws ApiNotAccessibleException { - - String apiHostIpPort = environment.getProperty(apiName.name()); - T result = null; - UriComponentsBuilder builder = null; - UriComponents uriComponents = null; - if (apiHostIpPort != null) { - - builder = UriComponentsBuilder.fromUriString(apiHostIpPort); - if (!((pathsegments == null) || (pathsegments.isEmpty()))) { - for (String segment : pathsegments) { - if (!((segment == null) || (("").equals(segment)))) { - builder.pathSegment(segment); - } - } - - } - - if (!((queryParamName == null) || (("").equals(queryParamName)))) { - - String[] queryParamNameArr = queryParamName.split(","); - String[] queryParamValueArr = queryParamValue.split(","); - for (int i = 0; i < queryParamNameArr.length; i++) { - builder.queryParam(queryParamNameArr[i], queryParamValueArr[i]); - } - - } - 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 ApiNotAccessibleException(e); - } - - } - return result; - } - - @SuppressWarnings("unchecked") - public T getApi(ApiName apiName, Map pathsegments, Class responseType) throws Exception { - - String apiHostIpPort = environment.getProperty(apiName.name()); - T result = null; - UriComponentsBuilder builder = null; - UriComponents uriComponents = null; - if (apiHostIpPort != null) { - - builder = UriComponentsBuilder.fromUriString(apiHostIpPort); - - URI urlWithPath = builder.build(pathsegments); - - RestTemplate restTemplate; - - try { - restTemplate = getRestTemplate(); - result = (T) restTemplate - .exchange(urlWithPath, 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 { - TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true; - SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom() - .loadTrustMaterial(null, acceptingTrustStrategy).build(); - SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext); - CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build(); - HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); - requestFactory.setHttpClient(httpClient); - - return new RestTemplate(requestFactory); - - } - - /** - * Sets the request header. - * - * @param requestType the request type - * @param mediaType the media type - * @return the http entity - * @throws IOException Signals that an I/O exception has occurred. - */ - private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { - MultiValueMap headers = new LinkedMultiValueMap(); - headers.add("Cookie", getToken()); - if (mediaType != null) { - headers.add("Content-Type", mediaType.toString()); - } - if (requestType != null) { - try { - HttpEntity httpEntity = (HttpEntity) requestType; - HttpHeaders httpHeader = httpEntity.getHeaders(); - Iterator iterator = httpHeader.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - if (!(headers.containsKey("Content-Type") && key == "Content-Type")) - headers.add(key, httpHeader.get(key).get(0)); - } - return new HttpEntity(httpEntity.getBody(), headers); - } catch (ClassCastException e) { - return new HttpEntity(requestType, headers); - } - } else - return new HttpEntity(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, - environment.getProperty("data.share.token.request.issuerUrl"), - environment.getProperty("data.share.token.request.clientId")); - - - } - if (!isValid) { - TokenRequestDTO tokenRequestDTO = new TokenRequestDTO(); - tokenRequestDTO.setId(environment.getProperty("data.share.token.request.id")); - tokenRequestDTO.setMetadata(new Metadata()); - - tokenRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); - // tokenRequestDTO.setRequest(setPasswordRequestDTO()); - tokenRequestDTO.setRequest(setSecretKeyRequestDTO()); - tokenRequestDTO.setVersion(environment.getProperty("data.share.token.request.version")); - - Gson gson = new Gson(); - HttpClient 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"); - HttpResponse response = httpClient.execute(post); - org.apache.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; - } - } - return AUTHORIZATION + token; - } - - /** - * Sets the secret key request DTO. - * - * @return the secret key request - */ - private SecretKeyRequest setSecretKeyRequestDTO() { - SecretKeyRequest request = new SecretKeyRequest(); - request.setAppId(environment.getProperty("data.share.token.request.appid")); - request.setClientId(environment.getProperty("data.share.token.request.clientId")); - request.setSecretKey(environment.getProperty("data.share.token.request.secretKey")); - return request; - } - - /** - * Sets the password request DTO. - * - * @return the password request - */ - private PasswordRequest setPasswordRequestDTO() { - PasswordRequest request = new PasswordRequest(); - request.setAppId(environment.getProperty("data.share.token.request.appid")); - request.setPassword(environment.getProperty("data.share.token.request.password")); - request.setUserName(environment.getProperty("data.share.token.request.username")); - return request; - } -} +package io.mosip.datashare.util; +import java.io.IOException; +import java.net.URI; +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 org.apache.http.Header; +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.springframework.beans.factory.annotation.Value; +import org.apache.http.util.EntityUtils; +import org.springframework.beans.factory.annotation.Autowired; +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; +import org.springframework.web.client.HttpStatusCodeException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponents; +import org.springframework.web.util.UriComponentsBuilder; + +import com.google.gson.Gson; + +import io.mosip.datashare.constant.ApiName; +import io.mosip.datashare.dto.Metadata; +import io.mosip.datashare.dto.PasswordRequest; +import io.mosip.datashare.dto.SecretKeyRequest; +import io.mosip.datashare.dto.TokenRequestDTO; +import io.mosip.datashare.exception.ApiNotAccessibleException; +import io.mosip.kernel.core.util.DateUtils; +import io.mosip.kernel.core.util.StringUtils; +import io.mosip.kernel.core.util.TokenHandlerUtil; + + +/** + * @author Sowmya The Class RestUtil. + */ +@Component +public class RestUtil { + + @Value("${data.share.default.resttemplate.httpclient.connections.max.per.host:20}") + private int maxConnectionPerRoute; + + @Value("${data.share.default.resttemplate.httpclient.connections.max:100}") + private int totalMaxConnection; + + private RestTemplate restTemplate; + + /** The environment. */ + @Autowired + private Environment environment; + + /** The Constant AUTHORIZATION. */ + private static final String AUTHORIZATION = "Authorization="; + + /** + * Post api. + * + * @param the generic type + * @param apiName the api name + * @param pathsegments the pathsegments + * @param queryParamName the query param name + * @param queryParamValue the query param value + * @param mediaType the media type + * @param requestType the request type + * @param responseClass the response class + * @return the t + * @throws ApiNotAccessibleException the api not accessible exception + */ + @SuppressWarnings("unchecked") + public T postApi(ApiName apiName, List pathsegments, String queryParamName, String queryParamValue, + MediaType mediaType, Object requestType, Class responseClass) throws ApiNotAccessibleException { + T result = null; + String apiHostIpPort = environment.getProperty(apiName.name()); + UriComponentsBuilder builder = null; + if (apiHostIpPort != null) + builder = UriComponentsBuilder.fromUriString(apiHostIpPort); + if (builder != null) { + + if (!((pathsegments == null) || (pathsegments.isEmpty()))) { + for (String segment : pathsegments) { + if (!((segment == null) || (("").equals(segment)))) { + builder.pathSegment(segment); + } + } + + } + if (!((queryParamName == null) || (("").equals(queryParamName)))) { + String[] queryParamNameArr = queryParamName.split(","); + String[] queryParamValueArr = queryParamValue.split(","); + + for (int i = 0; i < queryParamNameArr.length; i++) { + builder.queryParam(queryParamNameArr[i], queryParamValueArr[i]); + } + } + + RestTemplate restTemplate; + + try { + restTemplate = getRestTemplate(); + result = (T) restTemplate.postForObject(builder.toUriString(), setRequestHeader(requestType, mediaType), + responseClass); + + } catch (Exception e) { + tokenExceptionHandler(e); + throw new ApiNotAccessibleException(e); + } + } + return result; + } + + /** + * Gets the api. + * + * @param the generic type + * @param apiName the api name + * @param pathsegments the pathsegments + * @param queryParamName the query param name + * @param queryParamValue the query param value + * @param responseType the response type + * @return the api + * @throws ApiNotAccessibleException the api not accessible exception + */ + @SuppressWarnings("unchecked") + public T getApi(ApiName apiName, List pathsegments, String queryParamName, String queryParamValue, + Class responseType) throws ApiNotAccessibleException { + + String apiHostIpPort = environment.getProperty(apiName.name()); + T result = null; + UriComponentsBuilder builder = null; + UriComponents uriComponents = null; + if (apiHostIpPort != null) { + + builder = UriComponentsBuilder.fromUriString(apiHostIpPort); + if (!((pathsegments == null) || (pathsegments.isEmpty()))) { + for (String segment : pathsegments) { + if (!((segment == null) || (("").equals(segment)))) { + builder.pathSegment(segment); + } + } + + } + + if (!((queryParamName == null) || (("").equals(queryParamName)))) { + + String[] queryParamNameArr = queryParamName.split(","); + String[] queryParamValueArr = queryParamValue.split(","); + for (int i = 0; i < queryParamNameArr.length; i++) { + builder.queryParam(queryParamNameArr[i], queryParamValueArr[i]); + } + + } + 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) { + tokenExceptionHandler(e); + throw new ApiNotAccessibleException(e); + } + + } + return result; + } + + @SuppressWarnings("unchecked") + public T getApi(ApiName apiName, Map pathsegments, Class responseType) throws Exception { + + String apiHostIpPort = environment.getProperty(apiName.name()); + T result = null; + UriComponentsBuilder builder = null; + UriComponents uriComponents = null; + if (apiHostIpPort != null) { + + builder = UriComponentsBuilder.fromUriString(apiHostIpPort); + + URI urlWithPath = builder.build(pathsegments); + + RestTemplate restTemplate; + + try { + restTemplate = getRestTemplate(); + result = (T) restTemplate + .exchange(urlWithPath, HttpMethod.GET, setRequestHeader(null, null), responseType).getBody(); + } catch (Exception e) { + tokenExceptionHandler(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) { + HttpClientBuilder httpClientBuilder = HttpClients.custom().setMaxConnPerRoute(maxConnectionPerRoute) + .setMaxConnTotal(totalMaxConnection).disableCookieManagement(); + HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); + requestFactory.setHttpClient(httpClientBuilder.build()); + + restTemplate = new RestTemplate(requestFactory); + } + return restTemplate; + } + + /** + * Sets the request header. + * + * @param requestType the request type + * @param mediaType the media type + * @return the http entity + * @throws IOException Signals that an I/O exception has occurred. + */ + private HttpEntity setRequestHeader(Object requestType, MediaType mediaType) throws IOException { + MultiValueMap headers = new LinkedMultiValueMap(); + headers.add("Cookie", getToken()); + if (mediaType != null) { + headers.add("Content-Type", mediaType.toString()); + } + if (requestType != null) { + try { + HttpEntity httpEntity = (HttpEntity) requestType; + HttpHeaders httpHeader = httpEntity.getHeaders(); + Iterator iterator = httpHeader.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (!(headers.containsKey("Content-Type") && key == "Content-Type")) + headers.add(key, httpHeader.get(key).get(0)); + } + return new HttpEntity(httpEntity.getBody(), headers); + } catch (ClassCastException e) { + return new HttpEntity(requestType, headers); + } + } else + return new HttpEntity(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, + environment.getProperty("data.share.token.request.issuerUrl"), + environment.getProperty("data.share.token.request.clientId")); + + + } + if (!isValid) { + TokenRequestDTO tokenRequestDTO = new TokenRequestDTO(); + tokenRequestDTO.setId(environment.getProperty("data.share.token.request.id")); + tokenRequestDTO.setMetadata(new Metadata()); + + tokenRequestDTO.setRequesttime(DateUtils.getUTCCurrentDateTimeString()); + // tokenRequestDTO.setRequest(setPasswordRequestDTO()); + tokenRequestDTO.setRequest(setSecretKeyRequestDTO()); + tokenRequestDTO.setVersion(environment.getProperty("data.share.token.request.version")); + + Gson gson = new Gson(); + HttpClient 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"); + HttpResponse response = httpClient.execute(post); + org.apache.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; + } + } + return AUTHORIZATION + token; + } + + /** + * Sets the secret key request DTO. + * + * @return the secret key request + */ + private SecretKeyRequest setSecretKeyRequestDTO() { + SecretKeyRequest request = new SecretKeyRequest(); + request.setAppId(environment.getProperty("data.share.token.request.appid")); + request.setClientId(environment.getProperty("data.share.token.request.clientId")); + request.setSecretKey(environment.getProperty("data.share.token.request.secretKey")); + return request; + } + + /** + * Sets the password request DTO. + * + * @return the password request + */ + private PasswordRequest setPasswordRequestDTO() { + PasswordRequest request = new PasswordRequest(); + request.setAppId(environment.getProperty("data.share.token.request.appid")); + request.setPassword(environment.getProperty("data.share.token.request.password")); + request.setUserName(environment.getProperty("data.share.token.request.username")); + return request; + } + + public void tokenExceptionHandler(Exception e) { + if (e instanceof HttpStatusCodeException) { + HttpStatusCodeException ex = (HttpStatusCodeException) e; + if (ex.getRawStatusCode() == 401) { + System.setProperty("token", ""); + } + } + } +} diff --git a/data-share/pom.xml b/data-share/pom.xml index cfbbbc75..0df50a37 100644 --- a/data-share/pom.xml +++ b/data-share/pom.xml @@ -5,11 +5,11 @@ io.mosip.datashare durian - 1.2.0-SNAPSHOT + 1.1.5.3-P2 data-share - 1.2.0-SNAPSHOT + 1.1.5.3-P2 pom data-share @@ -23,7 +23,7 @@ 3.1.0 0.8.1 3.7.0.1746 - 3.0.1 + 3.2.0 2.0.2.RELEASE 2.0.7.RELEASE @@ -33,13 +33,13 @@ 2.9.8 1.0.6 2.9.2 - 1.2.0-SNAPSHOT - 1.2.0-SNAPSHOT + 1.1.5.2 + 1.1.5.2 1.0.6 1.0.6 2.0.7 2.28.2 - 1.2.0-SNAPSHOT + 1.1.5.5-rc2 **/constant/**,**/config/**,**/cache/**,**/dto/**,**/model/**,**/exception/**,**/repository/**,**/security/**,**/*Config.java,**/*Application.java,**/*Handler.java,**/*RestUtil.java **/dto/**,**/config/**,**/api/** 1.4.2 diff --git a/pom.xml b/pom.xml index 307aaabb..08b1ca2d 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 io.mosip.datashare durian - 1.2.0-SNAPSHOT + 1.1.5.3-P2 pom MOSIP Durian Parent POM @@ -54,7 +54,7 @@ ossrh - https://oss.sonatype.org/service/local/staging/deploy/maven2/ + https://oss.sonatype.org/service/local/staging/deploy/maven2 @@ -87,7 +87,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 2.9.1 + 3.2.0 attach-javadocs