rrpawar96 commented on a change in pull request #1235: URL: https://github.com/apache/fineract/pull/1235#discussion_r492519683
########## File path: fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReportsReadPlatformServiceImpl.java ########## @@ -0,0 +1,347 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fineract.infrastructure.creditbureau.service; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import org.apache.fineract.commands.domain.CommandWrapper; +import org.apache.fineract.commands.service.CommandWrapperBuilder; +import org.apache.fineract.infrastructure.core.api.JsonCommand; +import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper; +import org.apache.fineract.infrastructure.core.service.RoutingDataSource; +import org.apache.fineract.infrastructure.creditbureau.data.CreditReportData; +import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken; +import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauTokenCredential; +import org.apache.fineract.infrastructure.creditbureau.domain.TokenDataRepositoryWrapper; +import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper; +import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer; +import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class CreditBureauReportsReadPlatformServiceImpl implements CreditBureauReportsReadPlatformService { + + private static final Logger LOG = LoggerFactory.getLogger(CreditBureauReportsReadPlatformServiceImpl.class); + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final FromJsonHelper fromApiJsonHelper; + private final TokenRepositoryWrapper tokenRepository; + private final TokenDataRepositoryWrapper tokenDataRepository; + private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer; + + @Autowired + public CreditBureauReportsReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, + final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepository, + final TokenDataRepositoryWrapper tokenDataRepository, + final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.tokenRepository = tokenRepository; + this.tokenDataRepository = tokenDataRepository; + this.fromApiJsonHelper = fromApiJsonHelper; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; + } + + String nrcId = null; + Long uniqueID = 0L; + String userName = ""; + String password = ""; + String subscriptionId = ""; + String subscriptionKey = ""; + + StringBuilder response = new StringBuilder(); + HttpURLConnection postConnection; + String tokenDate; + String token = null; + String process = null; + String result = null; + + public void httpConnectionMethod() { + try { + String readLine = null; + String post_params = null; + + if (process.equals("token")) { + LOG.info("-----creating new token-----"); + post_params = "\n" + "BODY=x-www-form-urlencoded&\r\n" + "grant_type=password&\r\n" + "userName=" + userName + "&\r\n" + + "password=" + password + "&\r\n"; + + URL tokenurl = new URL("https://mmcix.azure-api.net/qa/20200324/Token"); + readLine = null; + postConnection = (HttpURLConnection) tokenurl.openConnection(); + postConnection.setRequestMethod("POST"); + + } else if (process.equals("NRC")) { + // Search Methods + LOG.info("-----Search by NRC-----"); + post_params = "BODY=x-www-form-urlencoded&nrc=" + nrcId + "&"; + + URL NrcURL = new URL("https://mmcix.azure-api.net/qa/20200324/api/Search/SimpleSearch?nrc=" + nrcId); + postConnection = (HttpURLConnection) NrcURL.openConnection(); + postConnection.setRequestMethod("POST"); + } + + else if (process.equals("CREDITREPORT")) { + LOG.info("-----Search by CREDIT_REPORT-----"); + URL CreditReportURL = new URL("https://mmcix.azure-api.net/qa/20200324/api/Dashboard/GetCreditReport?uniqueId=" + uniqueID); + postConnection = (HttpURLConnection) CreditReportURL.openConnection(); + postConnection.setRequestMethod("GET"); + + } + + // common set of headers + postConnection.setRequestProperty("mcix-subscription-key", subscriptionKey); + postConnection.setRequestProperty("mcix-subscription-id", subscriptionId); + postConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + // token header not used when creating token i.e. when token will be null + if (token != null) { + postConnection.setRequestProperty("Authorization", "Bearer " + token); + } + + // this set of code only required for fetching uniqueID from Nrc fetched data (POST-SimpleSearch) + if (process.equals("NRC") || process.equals("token")) { + LOG.info("-----NRC & CREDITREPORT -----"); + postConnection.setDoOutput(true); + OutputStream os = postConnection.getOutputStream(); + os.write(post_params.getBytes(StandardCharsets.UTF_8)); + os.flush(); + os.close(); + + } + + // common part of code in http connection method + int responseCode = postConnection.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + response = new StringBuilder(); + + LOG.info("----- RESPONSE OK-----"); + BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream(), StandardCharsets.UTF_8)); + while ((readLine = in.readLine()) != null) { + response.append(readLine); + } + in.close(); + result = response.toString(); + + } else { + LOG.info("Request is Invalid"); + } + + } catch (IOException e) { + LOG.error("Error occured.", e); + } + } + + @SuppressWarnings({ "CatchAndPrintStackTrace", "DefaultCharset" }) + @Override + @Transactional + @CacheEvict(value = "searchreport", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')") Review comment: Removed CacheEvict ########## File path: fineract-provider/src/main/java/org/apache/fineract/infrastructure/creditbureau/service/CreditBureauReportsReadPlatformServiceImpl.java ########## @@ -0,0 +1,347 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.fineract.infrastructure.creditbureau.service; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; +import org.apache.fineract.commands.domain.CommandWrapper; +import org.apache.fineract.commands.service.CommandWrapperBuilder; +import org.apache.fineract.infrastructure.core.api.JsonCommand; +import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper; +import org.apache.fineract.infrastructure.core.service.RoutingDataSource; +import org.apache.fineract.infrastructure.creditbureau.data.CreditReportData; +import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauToken; +import org.apache.fineract.infrastructure.creditbureau.domain.CreditBureauTokenCredential; +import org.apache.fineract.infrastructure.creditbureau.domain.TokenDataRepositoryWrapper; +import org.apache.fineract.infrastructure.creditbureau.domain.TokenRepositoryWrapper; +import org.apache.fineract.infrastructure.creditbureau.serialization.CreditBureauTokenCommandFromApiJsonDeserializer; +import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.CacheEvict; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +@Service +public class CreditBureauReportsReadPlatformServiceImpl implements CreditBureauReportsReadPlatformService { + + private static final Logger LOG = LoggerFactory.getLogger(CreditBureauReportsReadPlatformServiceImpl.class); + private final JdbcTemplate jdbcTemplate; + private final PlatformSecurityContext context; + private final FromJsonHelper fromApiJsonHelper; + private final TokenRepositoryWrapper tokenRepository; + private final TokenDataRepositoryWrapper tokenDataRepository; + private final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer; + + @Autowired + public CreditBureauReportsReadPlatformServiceImpl(final PlatformSecurityContext context, final RoutingDataSource dataSource, + final FromJsonHelper fromApiJsonHelper, final TokenRepositoryWrapper tokenRepository, + final TokenDataRepositoryWrapper tokenDataRepository, + final CreditBureauTokenCommandFromApiJsonDeserializer fromApiJsonDeserializer) { + this.context = context; + this.jdbcTemplate = new JdbcTemplate(dataSource); + this.tokenRepository = tokenRepository; + this.tokenDataRepository = tokenDataRepository; + this.fromApiJsonHelper = fromApiJsonHelper; + this.fromApiJsonDeserializer = fromApiJsonDeserializer; + } + + String nrcId = null; + Long uniqueID = 0L; + String userName = ""; + String password = ""; + String subscriptionId = ""; + String subscriptionKey = ""; + + StringBuilder response = new StringBuilder(); + HttpURLConnection postConnection; + String tokenDate; + String token = null; + String process = null; + String result = null; + + public void httpConnectionMethod() { + try { + String readLine = null; + String post_params = null; + + if (process.equals("token")) { + LOG.info("-----creating new token-----"); + post_params = "\n" + "BODY=x-www-form-urlencoded&\r\n" + "grant_type=password&\r\n" + "userName=" + userName + "&\r\n" + + "password=" + password + "&\r\n"; + + URL tokenurl = new URL("https://mmcix.azure-api.net/qa/20200324/Token"); + readLine = null; + postConnection = (HttpURLConnection) tokenurl.openConnection(); + postConnection.setRequestMethod("POST"); + + } else if (process.equals("NRC")) { + // Search Methods + LOG.info("-----Search by NRC-----"); + post_params = "BODY=x-www-form-urlencoded&nrc=" + nrcId + "&"; + + URL NrcURL = new URL("https://mmcix.azure-api.net/qa/20200324/api/Search/SimpleSearch?nrc=" + nrcId); + postConnection = (HttpURLConnection) NrcURL.openConnection(); + postConnection.setRequestMethod("POST"); + } + + else if (process.equals("CREDITREPORT")) { + LOG.info("-----Search by CREDIT_REPORT-----"); + URL CreditReportURL = new URL("https://mmcix.azure-api.net/qa/20200324/api/Dashboard/GetCreditReport?uniqueId=" + uniqueID); + postConnection = (HttpURLConnection) CreditReportURL.openConnection(); + postConnection.setRequestMethod("GET"); + + } + + // common set of headers + postConnection.setRequestProperty("mcix-subscription-key", subscriptionKey); + postConnection.setRequestProperty("mcix-subscription-id", subscriptionId); + postConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); + + // token header not used when creating token i.e. when token will be null + if (token != null) { + postConnection.setRequestProperty("Authorization", "Bearer " + token); + } + + // this set of code only required for fetching uniqueID from Nrc fetched data (POST-SimpleSearch) + if (process.equals("NRC") || process.equals("token")) { + LOG.info("-----NRC & CREDITREPORT -----"); + postConnection.setDoOutput(true); + OutputStream os = postConnection.getOutputStream(); + os.write(post_params.getBytes(StandardCharsets.UTF_8)); + os.flush(); + os.close(); + + } + + // common part of code in http connection method + int responseCode = postConnection.getResponseCode(); + + if (responseCode == HttpURLConnection.HTTP_OK) { + response = new StringBuilder(); + + LOG.info("----- RESPONSE OK-----"); + BufferedReader in = new BufferedReader(new InputStreamReader(postConnection.getInputStream(), StandardCharsets.UTF_8)); + while ((readLine = in.readLine()) != null) { + response.append(readLine); + } + in.close(); + result = response.toString(); + + } else { + LOG.info("Request is Invalid"); + } + + } catch (IOException e) { + LOG.error("Error occured.", e); + } + } + + @SuppressWarnings({ "CatchAndPrintStackTrace", "DefaultCharset" }) + @Override + @Transactional + @CacheEvict(value = "searchreport", key = "T(org.apache.fineract.infrastructure.core.service.ThreadLocalContextUtil).getTenant().getTenantIdentifier().concat('cv')") + public CreditReportData retrieveAllSearchReport(final String searchId) { + String Name = null; + String Gender = null; + nrcId = searchId; + String Address = null; + + this.context.authenticatedUser(); + + final CreditBureauTokenCredential credittokendata = this.tokenDataRepository.getTokenCredential(); + + if (credittokendata != null) { + userName = credittokendata.getUserName(); + password = credittokendata.getPassword(); + subscriptionId = credittokendata.getSubscriptionId(); + subscriptionKey = credittokendata.getSubscriptionKey(); + + // validation required, incase when configuration is not stored in database while fetching data. + } else { + + String configJson = "{ 'userName':'" + userName + "','password':'" + password + "','subscriptionId':'" + subscriptionId + + "','subscriptionKey':'" + subscriptionKey + "'}"; + + this.fromApiJsonDeserializer.validateForUsingTokenConfig(configJson); + } + + CreditBureauToken creditbureautoken = this.tokenRepository.getToken(); + LOG.info("creditbureautoken : {} ", creditbureautoken); + + // check the expiry date of the previous token. + if (creditbureautoken != null) { + Date current = new Date(); + Date getExpiryDate = creditbureautoken.getTokenExpiryDate(); + + LOG.info("current date : {} ", current); + LOG.info("getExpiryDate : {} ", getExpiryDate); + + if (getExpiryDate.before(current)) { + LOG.info("The token is expired"); + this.tokenRepository.delete(creditbureautoken); + creditbureautoken = null; + } + } + // storing token if it is valid token(not expired) + if (creditbureautoken != null) { + token = creditbureautoken.getCurrentToken(); + } + + // if token is not available or previous token is expired then create a new token + if (creditbureautoken == null) { + + // using common http connection method for creating token + process = "token"; + this.httpConnectionMethod(); + + JsonObject tokenObject = JsonParser.parseString(result).getAsJsonObject(); + String expiresextra = tokenObject.get(".expires").toString(); + String expires = expiresextra.substring(1, expiresextra.length() - 1); + DateFormat dateformat = new SimpleDateFormat("EEE, dd MMM yyyy kk:mm:ss zzz", Locale.ENGLISH); Review comment: Comment Addressed. ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org