diff --git a/.github/workflows/manual_push_trigger.yml b/.github/workflows/manual_push_trigger.yml index 9ff18054..16bdbaea 100644 --- a/.github/workflows/manual_push_trigger.yml +++ b/.github/workflows/manual_push_trigger.yml @@ -1,4 +1,4 @@ -name: Cardprinter trigger for maven install +name: MSP Print-Service trigger for maven install on: workflow_dispatch @@ -43,7 +43,7 @@ jobs: ${{ runner.os }}-maven-${{ env.BRANCH_NAME }} - name: Setup the settings file for ossrh server - run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} 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 + run: echo " ossrh ${{secrets.ossrh_user}} ${{secrets.ossrh_secret}} 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 danubetech-maven-public https://repo.danubetech.com/repository/maven-public/ sonar . https://sonarcloud.io false " > $GITHUB_WORKSPACE/settings.xml - name: Build with Maven diff --git a/pom.xml b/pom.xml index 0749d45f..69f8637b 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ io.mosip.print print - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 print @@ -39,8 +39,8 @@ **/dto/**,**/config/**,**/api/** 1.4.2 2.8.4 - 1.2.0.1-SNAPSHOT - 1.2.0.1-SNAPSHOT + 1.2.0.1-B1 + 1.2.0.1-B1 7.1.0 2.0.0 5.5.13 @@ -48,7 +48,7 @@ 3.7 2.6 1.11 - 1.66 + 1.68 3.8.1 3.3.3 42.2.2 @@ -70,6 +70,12 @@ org.springframework.cloud spring-cloud-starter-config 2.0.2.RELEASE + + + org.bouncycastle + bcprov-jdk15on + + org.springframework.boot @@ -145,7 +151,7 @@ org.bouncycastle - bcprov-jdk15on + bcprov-jdk15to18 ${bouncycastle.version} @@ -209,6 +215,12 @@ io.mosip.kernel kernel-websubclient-api ${kernel.websub.version} + + + org.bouncycastle + bcprov-jdk15on + + io.mosip.kernel @@ -240,16 +252,16 @@ jackson-datatype-jsr310 2.12.0 - - info.weboftrust - ld-signatures-java - 0.8.0 - org.postgresql postgresql ${postgresql.version} + + io.mosip.vercred + vcverifier + 1.0.0 + @@ -271,10 +283,10 @@ false - - danubetech-maven-public - https://repo.danubetech.com/repository/maven-public/ - + + danubetech-maven-public + https://repo.danubetech.com/repository/maven-public/ + diff --git a/src/main/java/io/mosip/print/PrintPDFApplication.java b/src/main/java/io/mosip/print/PrintPDFApplication.java index 8cebd3b2..4bdde05b 100644 --- a/src/main/java/io/mosip/print/PrintPDFApplication.java +++ b/src/main/java/io/mosip/print/PrintPDFApplication.java @@ -6,14 +6,9 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.annotation.EnableScheduling; -import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import io.mosip.print.service.impl.CbeffImpl; -import io.mosip.print.spi.CbeffUtil; @SpringBootApplication(scanBasePackages = { "io.mosip.print.*", "${mosip.auth.adapter.impl.basepackage}" }, exclude = { SecurityAutoConfiguration.class, DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class, @@ -26,21 +21,6 @@ @EnableAsync public class PrintPDFApplication { - - @Bean - @Primary - public CbeffUtil getCbeffUtil() { - return new CbeffImpl(); - } - - @Bean - public ThreadPoolTaskScheduler taskScheduler() { - ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); - threadPoolTaskScheduler.setPoolSize(5); - threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler"); - return threadPoolTaskScheduler; - } - public static void main(String[] args) { SpringApplication.run(PrintPDFApplication.class, args); } diff --git a/src/main/java/io/mosip/print/config/PrintConfig.java b/src/main/java/io/mosip/print/config/PrintConfig.java index c4fb5d7a..4e4010bc 100644 --- a/src/main/java/io/mosip/print/config/PrintConfig.java +++ b/src/main/java/io/mosip/print/config/PrintConfig.java @@ -1,7 +1,11 @@ package io.mosip.print.config; +import io.mosip.print.service.impl.CbeffImpl; +import io.mosip.print.spi.CbeffUtil; +import io.mosip.vercred.CredentialsVerifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; @@ -9,6 +13,17 @@ @Configuration public class PrintConfig { + @Bean + @Primary + public CbeffUtil getCbeffUtil() { + return new CbeffImpl(); + } + + @Bean + public CredentialsVerifier credentialsVerifier() { + return new CredentialsVerifier(); + } + @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler(); diff --git a/src/main/java/io/mosip/print/constant/CredentialStatusConstant.java b/src/main/java/io/mosip/print/constant/CredentialStatusConstant.java new file mode 100644 index 00000000..6fe967dd --- /dev/null +++ b/src/main/java/io/mosip/print/constant/CredentialStatusConstant.java @@ -0,0 +1,11 @@ +package io.mosip.print.constant; + +/** + * An Enum for credential status. + */ +public enum CredentialStatusConstant { + + RECEIVED, + PRINTED, + ERROR +} diff --git a/src/main/java/io/mosip/print/controller/Print.java b/src/main/java/io/mosip/print/controller/Print.java index 93174aa2..11565003 100644 --- a/src/main/java/io/mosip/print/controller/Print.java +++ b/src/main/java/io/mosip/print/controller/Print.java @@ -40,7 +40,7 @@ public class Print { @PostMapping(path = "/callback/notifyPrint", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthenticateContentAndVerifyIntent(secret = "${mosip.event.secret}", callback = "/v1/cardprint/print/callback/notifyPrint", topic = "${mosip.event.topic}") public ResponseEntity handleSubscribeEvent(@RequestBody EventModel eventModel) throws Exception { - printLogger.info("event recieved from websub"+", id: {}",eventModel.getEvent().getId()); + printLogger.info("Event received from WebSub"+", id: {}",eventModel.getEvent().getId()); boolean isPrinted = printService.generateCard(eventModel); printLogger.info("printing status : {} for event id: {}",isPrinted,eventModel.getEvent().getId()); return new ResponseEntity<>("request accepted.", HttpStatus.OK); diff --git a/src/main/java/io/mosip/print/service/PrintService.java b/src/main/java/io/mosip/print/service/PrintService.java index 9309ce5e..f25c31c2 100644 --- a/src/main/java/io/mosip/print/service/PrintService.java +++ b/src/main/java/io/mosip/print/service/PrintService.java @@ -12,7 +12,7 @@ public interface PrintService { * @return * @throws Exception */ - public boolean generateCard(EventModel eventModel) throws Exception; + public boolean generateCard(EventModel eventModel); // Map getDocuments(String credentialSubject, String sign, // String cardType, diff --git a/src/main/java/io/mosip/print/service/UinCardGenerator.java b/src/main/java/io/mosip/print/service/UinCardGenerator.java index 4b36997b..32b38767 100644 --- a/src/main/java/io/mosip/print/service/UinCardGenerator.java +++ b/src/main/java/io/mosip/print/service/UinCardGenerator.java @@ -1,30 +1,30 @@ -package io.mosip.print.service; - -import java.io.InputStream; - -import io.mosip.print.constant.UinCardType; -import io.mosip.print.exception.ApisResourceAccessException; - -/** - * The Interface UinCardGenerator. - * - * @author M1048358 Alok - * - * @param - * the generic type - */ -public interface UinCardGenerator { - - /** - * Generate uin card. - * - * @param in - * the in - * @param type - * the type - * @param password - * the password - * @return the i - */ - public I generateUinCard(InputStream in, UinCardType type, String password) throws ApisResourceAccessException; -} +package io.mosip.print.service; + +import io.mosip.print.constant.UinCardType; +import io.mosip.print.exception.ApisResourceAccessException; + +import java.io.InputStream; + +/** + * The Interface UinCardGenerator. + * + * @author M1048358 Alok + * + * @param + * the generic type + */ +public interface UinCardGenerator { + + /** + * Generate uin card. + * + * @param in + * the in + * @param type + * the type + * @param password + * the password + * @return the i + */ + public I generateUinCard(InputStream in, UinCardType type, String password) throws ApisResourceAccessException; +} diff --git a/src/main/java/io/mosip/print/service/impl/PDFGeneratorImpl.java b/src/main/java/io/mosip/print/service/impl/PDFGeneratorImpl.java index 5b6dca41..2a07ff0c 100644 --- a/src/main/java/io/mosip/print/service/impl/PDFGeneratorImpl.java +++ b/src/main/java/io/mosip/print/service/impl/PDFGeneratorImpl.java @@ -1,25 +1,5 @@ package io.mosip.print.service.impl; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; - -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Component; - import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import com.itextpdf.html2pdf.css.media.MediaDeviceDescription; @@ -38,26 +18,28 @@ import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfSignatureAppearance; import com.itextpdf.text.pdf.PdfStamper; -import com.itextpdf.text.pdf.security.BouncyCastleDigest; -import com.itextpdf.text.pdf.security.CertificateUtil; -import com.itextpdf.text.pdf.security.CrlClient; -import com.itextpdf.text.pdf.security.CrlClientOnline; -import com.itextpdf.text.pdf.security.ExternalDigest; -import com.itextpdf.text.pdf.security.ExternalSignature; -import com.itextpdf.text.pdf.security.MakeSignature; +import com.itextpdf.text.pdf.security.*; import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard; -import com.itextpdf.text.pdf.security.OcspClient; -import com.itextpdf.text.pdf.security.OcspClientBouncyCastle; -import com.itextpdf.text.pdf.security.PrivateKeySignature; -import com.itextpdf.text.pdf.security.TSAClient; -import com.itextpdf.text.pdf.security.TSAClientBouncyCastle; - import io.mosip.print.constant.PDFGeneratorExceptionCodeConstant; import io.mosip.print.exception.PDFGeneratorException; import io.mosip.print.logger.PrintLogger; import io.mosip.print.model.CertificateEntry; import io.mosip.print.spi.PDFGenerator; import io.mosip.print.util.EmptyCheckUtils; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +import javax.imageio.ImageIO; +import java.awt.image.BufferedImage; +import java.io.*; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; /** * The PdfGeneratorImpl is the class you will use most when converting processed diff --git a/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java b/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java index a998efa4..565a4d93 100644 --- a/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java +++ b/src/main/java/io/mosip/print/service/impl/PrintServiceImpl.java @@ -7,11 +7,9 @@ import io.mosip.print.constant.*; import io.mosip.print.dto.CryptoWithPinRequestDto; import io.mosip.print.dto.CryptoWithPinResponseDto; -import io.mosip.print.dto.DataShare; import io.mosip.print.dto.JsonValue; import io.mosip.print.entity.MspCardEntity; import io.mosip.print.exception.*; -import io.mosip.print.idrepo.dto.IdResponseDTO1; import io.mosip.print.logger.LogDescription; import io.mosip.print.logger.PrintLogger; import io.mosip.print.model.CredentialStatusEvent; @@ -19,10 +17,14 @@ import io.mosip.print.model.StatusEvent; import io.mosip.print.repository.MspCardRepository; import io.mosip.print.service.PrintService; -import io.mosip.print.service.UinCardGenerator; import io.mosip.print.spi.CbeffUtil; import io.mosip.print.spi.QrCodeGenerator; import io.mosip.print.util.*; +import io.mosip.vercred.CredentialsVerifier; +import io.mosip.vercred.exception.ProofDocumentNotFoundException; +import io.mosip.vercred.exception.ProofTypeNotFoundException; +import io.mosip.vercred.exception.PubicKeyNotFoundException; +import io.mosip.vercred.exception.UnknownException; import org.apache.commons.codec.binary.Base64; import org.joda.time.DateTime; import org.json.simple.JSONArray; @@ -55,7 +57,7 @@ import java.util.*; @Service -public class PrintServiceImpl implements PrintService{ +public class PrintServiceImpl implements PrintService { private String topic="CREDENTIAL_STATUS_UPDATE"; @@ -63,10 +65,7 @@ public class PrintServiceImpl implements PrintService{ private WebSubSubscriptionHelper webSubSubscriptionHelper; @Autowired - private DataShareUtil dataShareUtil; - - @Autowired - CryptoUtil cryptoUtil; + private CryptoUtil cryptoUtil; @Autowired private RestApiClient restApiClient; @@ -80,9 +79,6 @@ public class PrintServiceImpl implements PrintService{ /** The Constant VALUE. */ private static final String VALUE = "value"; - /** The Constant UIN_CARD_TEMPLATE. */ - private static final String UIN_CARD_TEMPLATE = "RPR_UIN_CARD_TEMPLATE"; - /** The Constant FACE. */ private static final String FACE = "Face"; @@ -99,28 +95,18 @@ public class PrintServiceImpl implements PrintService{ private static final String UINCARDPASSWORD = "mosip.registration.processor.print.service.uincard.password"; /** The print logger. */ - Logger printLogger = PrintLogger.getLogger(PrintServiceImpl.class); - - /** The core audit request builder. */ - @Autowired - private AuditLogRequestBuilder auditLogRequestBuilder; - - /** The template generator. */ - @Autowired - private TemplateGenerator templateGenerator; + private Logger printLogger = PrintLogger.getLogger(PrintServiceImpl.class); /** The utilities. */ @Autowired private Utilities utilities; - /** The uin card generator. */ - @Autowired - private UinCardGenerator uinCardGenerator; - /** The qr code generator. */ @Autowired private QrCodeGenerator qrCodeGenerator; + @Autowired + private CredentialsVerifier credentialsVerifier; /** The Constant VID_CREATE_ID. */ public static final String VID_CREATE_ID = "registration.processor.id.repo.generate"; @@ -141,12 +127,6 @@ public class PrintServiceImpl implements PrintService{ @Autowired private Environment env; - @Value("${mosip.datashare.partner.id}") - private String partnerId; - - @Value("${mosip.datashare.policy.id}") - private String policyId; - @Value("${mosip.template-language}") private String templateLang; @@ -156,9 +136,6 @@ public class PrintServiceImpl implements PrintService{ @Value("${mosip.print.verify.credentials.flag:true}") private boolean verifyCredentialsFlag; - @Value("${token.request.clientId}") - private String clientId; - @Value("${mosip.print.default.infant.photo:null}") private String defaultBabyPhoto; @@ -174,10 +151,84 @@ public class PrintServiceImpl implements PrintService{ public boolean generateCard(EventModel eventModel) { Map byteMap = new HashMap<>(); - String decodedCrdential = null; String credential = null; boolean isPrinted =false; - try{ + try { + printStatusUpdate(eventModel.getEvent().getTransactionId(), CredentialStatusConstant.RECEIVED.name()); + credential = getCredential(eventModel); + String encryptionPin = eventModel.getEvent().getData().get("protectionKey").toString(); + String decodedCredential = cryptoCoreUtil.decrypt(credential); + printLogger.debug("vc is printed security valuation.... : {}", decodedCredential); + if (!hasPrintCredentialVerified(eventModel, decodedCredential)) return false; + Map proofMap = new HashMap(); + proofMap = (Map) eventModel.getEvent().getData().get("proof"); + String sign = proofMap.get("signature").toString(); + Map attributes = getDocuments(decodedCredential, + eventModel.getEvent().getData().get("credentialType").toString(), encryptionPin, + eventModel.getEvent().getTransactionId(), getSignature(sign, credential), "UIN", false, eventModel.getEvent().getId(), + eventModel.getEvent().getData().get("registrationId").toString()); + + + String printid = (String) eventModel.getEvent().getId(); + StringBuilder stringBuilder = new StringBuilder(); + for(Map.Entry entry : attributes.entrySet()) { + stringBuilder.append(entry.getKey()).append(","); + } + printLogger.info("Attribute keys: {}", stringBuilder.toString()); + org.json.simple.JSONObject obj = new org.json.simple.JSONObject(); + Object photo = attributes.get(APPLICANT_PHOTO); + if (photo == null && isChildRegistration(attributes)) { + photo = defaultBabyPhoto; + } + obj.put("photo", photo); + obj.put("qrCode", attributes.get(QRCODE)); + String fullAddress = getFullAddress(attributes); + String fullName = getFullName(attributes); + obj.put("address", (fullAddress.length() > 0) ? fullAddress : " "); + obj.put("locality", ((attributes.get("locality") != null && !attributes.get("locality").equals("")) ? attributes.get("locality").toString() : " ")); + obj.put("city", ((attributes.get("city") != null && !attributes.get("city").equals("")) ? attributes.get("city").toString() : " ")); + obj.put("state", ((attributes.get("state") != null && !attributes.get("state").equals("")) ? attributes.get("state").toString() : " ")); + obj.put("postalCode", ((attributes.get("postalCode") != null && !attributes.get("postalCode").equals("")) ? attributes.get("postalCode").toString() : " ")); + obj.put("gender", ((attributes.get("gender") != null && !attributes.get("gender").equals("")) ? attributes.get("gender").toString() : " ")); + obj.put("fullName", (fullName.length() > 0) ? fullName : " "); + obj.put("dateOfBirth", ((attributes.get("dateOfBirth") != null && !attributes.get("dateOfBirth").equals("")) ? attributes.get("dateOfBirth").toString() : " ")); + obj.put("phone", ((attributes.get("phone") != null && !attributes.get("phone").equals("")) ? attributes.get("phone").toString() : " ")); + obj.put("vid", ((attributes.get("VID") != null && !attributes.get("VID").equals("")) ? attributes.get("VID").toString() : " ")); + obj.put("UIN", ((attributes.get("UIN") != null && !attributes.get("UIN").equals("")) ? attributes.get("UIN").toString() : " ")); + obj.put("email", ((attributes.get("email") != null && !attributes.get("email").equals("")) ? attributes.get("email").toString() : " ")); + + String woenc = obj.toJSONString(); + + MspCardEntity mspCardEntity = new MspCardEntity(); + mspCardEntity.setJsonData(woenc); + mspCardEntity.setRequestId(eventModel.getEvent().getTransactionId()); + mspCardEntity.setRegistrationDate(DateUtils.getUTCCurrentDateTime()); + mspCardEntity.setStatus(90); + UUID uuid=UUID.randomUUID(); + mspCardEntity.setId(uuid.toString()); + mspCardRepository.create(mspCardEntity); + isPrinted=true; + } catch (Exception e) { + printLogger.error(e.getMessage() , e); + isPrinted = false; + } finally { + if (isPrinted) { + printStatusUpdate(eventModel.getEvent().getTransactionId(), CredentialStatusConstant.PRINTED.name()); + } else { + printStatusUpdate(eventModel.getEvent().getTransactionId(), CredentialStatusConstant.ERROR.name()); + } + } + return isPrinted; + } + + /** + * Fetch credential from the event if not using datashare URL. + * @param eventModel + * @return + * @throws Exception + */ + private String getCredential(EventModel eventModel) throws Exception { + String credential; if (eventModel.getEvent().getDataShareUri() == null || eventModel.getEvent().getDataShareUri().isEmpty()) { credential = eventModel.getEvent().getData().get("credential").toString(); } else { @@ -185,57 +236,7 @@ public boolean generateCard(EventModel eventModel) { URI dataShareUri = URI.create(dataShareUrl); credential = restApiClient.getApi(dataShareUri, String.class); } - - String ecryptionPin = eventModel.getEvent().getData().get("protectionKey").toString(); - decodedCrdential = cryptoCoreUtil.decrypt(credential); - - Map proofMap = new HashMap(); - proofMap = (Map) eventModel.getEvent().getData().get("proof"); - String sign = proofMap.get("signature").toString(); - Map attributes = getDocuments(decodedCrdential, - eventModel.getEvent().getData().get("credentialType").toString(), ecryptionPin, - eventModel.getEvent().getTransactionId(), getSignature(sign, credential), "UIN", false, eventModel.getEvent().getId(), - eventModel.getEvent().getData().get("registrationId").toString()); - - - String printid = (String) eventModel.getEvent().getId(); - - org.json.simple.JSONObject obj = new org.json.simple.JSONObject(); - Object photo = attributes.get(APPLICANT_PHOTO); - if (photo == null && isChildRegistration(attributes)) { - photo = defaultBabyPhoto; - } - obj.put("photo", photo); - obj.put("qrCode", attributes.get(QRCODE)); - String fullAddress = getFullAddress(attributes); - obj.put("address", (fullAddress.length() > 0) ? fullAddress : "N/A"); - obj.put("locality", ((attributes.get("locality") != null && !attributes.get("locality").equals("")) ? attributes.get("locality").toString() : "N/A")); - obj.put("city", ((attributes.get("city") != null && !attributes.get("city").equals("")) ? attributes.get("city").toString() : "N/A")); - obj.put("state", ((attributes.get("state") != null && !attributes.get("state").equals("")) ? attributes.get("state").toString() : "N/A")); - obj.put("postalCode", ((attributes.get("postalCode") != null && !attributes.get("postalCode").equals("")) ? attributes.get("postalCode").toString() : "N/A")); - obj.put("gender", ((attributes.get("gender") != null && !attributes.get("gender").equals("")) ? attributes.get("gender").toString() : "N/A")); - obj.put("fullName", ((attributes.get("fullName") != null && !attributes.get("fullName").equals("")) ? attributes.get("fullName").toString() : "N/A")); - obj.put("dateOfBirth", ((attributes.get("dateOfBirth") != null && !attributes.get("dateOfBirth").equals("")) ? attributes.get("dateOfBirth").toString() : "N/A")); - obj.put("phone", ((attributes.get("phone") != null && !attributes.get("phone").equals("")) ? attributes.get("phone").toString() : "N/A")); - obj.put("vid", ((attributes.get("VID") != null && !attributes.get("VID").equals("")) ? attributes.get("VID").toString() : "N/A")); - obj.put("UIN", ((attributes.get("UIN") != null && !attributes.get("UIN").equals("")) ? attributes.get("UIN").toString() : "N/A")); - obj.put("email", ((attributes.get("email") != null && !attributes.get("email").equals("")) ? attributes.get("email").toString() : "N/A")); - - String woenc = obj.toJSONString(); - - MspCardEntity mspCardEntity = new MspCardEntity(); - mspCardEntity.setJsonData(woenc); - mspCardEntity.setRequestId(printid); - mspCardEntity.setStatus(90); - UUID uuid=UUID.randomUUID(); - mspCardEntity.setId(uuid.toString()); - mspCardRepository.create(mspCardEntity); - isPrinted=true; - }catch (Exception e){ - printLogger.error(e.getMessage() , e); - isPrinted = false; - } - return isPrinted; + return credential; } private boolean isChildRegistration(Map attributes) { @@ -256,12 +257,20 @@ private String getFullAddress(Map attributes) { return StringUtils.arrayToCommaDelimitedString(fullAddress); } + private String getFullName(Map attributes) { + Object fullName[] = new Object[]{ attributes.get("firstName"), attributes.get("middleName"), attributes.get("lastName")}; + fullName = Arrays.stream(fullName) + .filter(s -> (s != null && !s.equals(""))) + .toArray(Object[]::new); + return StringUtils.arrayToDelimitedString(fullName, " "); + } + private String getSignature(String sign, String crdential) { String signHeader = sign.split("\\.")[0]; String signData = sign.split("\\.")[2]; - String signature = signHeader + "." + crdential + "." + signData; - return signature; + return signHeader + "." + crdential + "." + signData; } + private Map getDocuments(String credential, String credentialType, String encryptionPin, String requestId, String sign, String cardType, @@ -274,19 +283,17 @@ private Map getDocuments(String credential, String credentialTyp Map byteMap = new HashMap<>(); String uin = null; LogDescription description = new LogDescription(); - String password = null; boolean isPhotoSet=false; String individualBio = null; Map attributes = new LinkedHashMap<>(); boolean isTransactionSuccessful = false; - IdResponseDTO1 response = null; - String template = UIN_CARD_TEMPLATE; byte[] pdfbytes = null; try { credentialSubject = getCrdentialSubject(credential); org.json.JSONObject credentialSubjectJson = new org.json.JSONObject(credentialSubject); org.json.JSONObject decryptedJson = decryptAttribute(credentialSubjectJson, encryptionPin, credential); + //Print decryptedJson if(decryptedJson.has("biometrics")){ individualBio = decryptedJson.getString("biometrics"); String individualBiometric = new String(individualBio); @@ -295,9 +302,6 @@ private Map getDocuments(String credential, String credentialTyp } uin = decryptedJson.getString("UIN"); - if (isPasswordProtected) { - password = getPassword(uin); - } if (!isPhotoSet) { printLogger.debug(LoggerFileConstant.SESSIONID.toString(), @@ -306,6 +310,7 @@ private Map getDocuments(String credential, String credentialTyp } setTemplateAttributes(decryptedJson.toString(), attributes); attributes.put(IdType.UIN.toString(), uin); + attributes.put(IdType.RID.toString(), registrationId); byte[] textFileByte = createTextFile(decryptedJson.toString()); byteMap.put(UIN_TEXT_FILE, textFileByte); @@ -317,7 +322,7 @@ private Map getDocuments(String credential, String credentialTyp PlatformErrorMessages.PRT_PRT_QRCODE_NOT_SET.name()); } - printStatusUpdate(requestId, credentialType, uin, refId, registrationId); + printStatusUpdate(requestId, CredentialStatusConstant.PRINTED.name()); isTransactionSuccessful = true; } catch (VidCreationException e) { @@ -411,12 +416,7 @@ private Map getDocuments(String credential, String credentialTyp eventName = EventName.EXCEPTION.toString(); eventType = EventType.SYSTEM.toString(); } - /** Module-Id can be Both Success/Error code */ - String moduleId = isTransactionSuccessful ? PlatformSuccessMessages.RPR_PRINT_SERVICE_SUCCESS.getCode() - : description.getCode(); - String moduleName = ModuleName.PRINT_SERVICE.toString(); - auditLogRequestBuilder.createAuditRequestBuilder(description.getMessage(), eventId, eventName, eventType, - moduleId, moduleName, uin); + } printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), "", "PrintServiceImpl::getDocuments()::exit"); @@ -424,6 +424,36 @@ private Map getDocuments(String credential, String credentialTyp return attributes; } + /** + * Verifies Print credentials using credential verifier. + * @param eventModel + * @param decodedCredential + * @return + */ + private boolean hasPrintCredentialVerified(EventModel eventModel, String decodedCredential) { + + if (verifyCredentialsFlag) { + printLogger.info("Configured received credentials to be verified. Flag {}", verifyCredentialsFlag); + try { + boolean verified = credentialsVerifier.verifyPrintCredentials(decodedCredential); + if (!verified) { + printLogger.error("Received Credentials failed in verifiable credential verify method. So, the credentials will not be printed." + + " Id: {}, Transaction Id: {}", eventModel.getEvent().getId(), eventModel.getEvent().getTransactionId()); + return false; + } + } catch (ProofDocumentNotFoundException | ProofTypeNotFoundException e) { + printLogger.error("Proof document is not available in the received credentials." + + " Id: {}, Transaction Id: {}", eventModel.getEvent().getId(), eventModel.getEvent().getTransactionId()); + return false; + } catch (UnknownException | PubicKeyNotFoundException e) { + printLogger.error("Received Credentials failed in verifiable credential verify method. So, the credentials will not be printed." + + " Id: {}, Transaction Id: {}", eventModel.getEvent().getId(), eventModel.getEvent().getTransactionId()); + return false; + } + } + return true; + } + /** * Creates the text file. @@ -568,6 +598,10 @@ private void setTemplateAttributes(String jsonString, Map attrib Object object = demographicIdentity.get(value); if (object != null) { try { + if (object instanceof Collection) { + // In order to parse the collection values, mainly for VC. + object = JsonUtil.writeValueAsString(object); + } obj = new JSONParser().parse(object.toString()); } catch (Exception e) { obj = object; @@ -717,48 +751,26 @@ public byte[] extractFaceImageData(byte[] decodedBioValue) { private String getCrdentialSubject(String crdential) { org.json.JSONObject jsonObject = new org.json.JSONObject(crdential); - String credentialSubject = jsonObject.get("credentialSubject").toString(); - return credentialSubject; - } - - private void printStatusUpdate(String requestId, byte[] data, String credentialType) - throws DataShareException, ApiNotAccessibleException, IOException, Exception { - DataShare dataShare = null; - dataShare = dataShareUtil.getDataShare(data, policyId, partnerId); - CredentialStatusEvent creEvent = new CredentialStatusEvent(); - LocalDateTime currentDtime = DateUtils.getUTCCurrentDateTime(); - StatusEvent sEvent = new StatusEvent(); - sEvent.setId(UUID.randomUUID().toString()); - sEvent.setRequestId(requestId); - sEvent.setStatus("printing"); - sEvent.setUrl(dataShare.getUrl()); - sEvent.setTimestamp(Timestamp.valueOf(currentDtime).toString()); - creEvent.setPublishedOn(new DateTime().toString()); - creEvent.setPublisher("PRINT_SERVICE"); - creEvent.setTopic(topic); - creEvent.setEvent(sEvent); - webSubSubscriptionHelper.printStatusUpdateEvent(topic, creEvent); + return jsonObject.get("credentialSubject").toString(); } + private void printStatusUpdate(String requestId, String status) { - private void printStatusUpdate(String requestId, String credentialType, String uin, String printRefId, String registrationId) - throws DataShareException, ApiNotAccessibleException, IOException, Exception { CredentialStatusEvent creEvent = new CredentialStatusEvent(); LocalDateTime currentDtime = DateUtils.getUTCCurrentDateTime(); StatusEvent sEvent = new StatusEvent(); sEvent.setId(UUID.randomUUID().toString()); sEvent.setRequestId(requestId); - sEvent.setStatus("printing"); + sEvent.setStatus(status); sEvent.setUrl(""); sEvent.setTimestamp(Timestamp.valueOf(currentDtime).toString()); creEvent.setPublishedOn(new DateTime().toString()); - creEvent.setPublisher("PRINT_SERVICE"); + creEvent.setPublisher("MSP_PRINT_SERVICE"); creEvent.setTopic(topic); creEvent.setEvent(sEvent); webSubSubscriptionHelper.printStatusUpdateEvent(topic, creEvent); } - public org.json.JSONObject decryptAttribute(org.json.JSONObject data, String encryptionPin, String credential) throws ParseException { @@ -774,7 +786,7 @@ public org.json.JSONObject decryptAttribute(org.json.JSONObject data, String enc for (Object str : jsonArray) { CryptoWithPinRequestDto cryptoWithPinRequestDto = new CryptoWithPinRequestDto(); - CryptoWithPinResponseDto cryptoWithPinResponseDto = new CryptoWithPinResponseDto(); + CryptoWithPinResponseDto cryptoWithPinResponseDto; cryptoWithPinRequestDto.setUserPin(encryptionPin); cryptoWithPinRequestDto.setData(data.getString(str.toString())); diff --git a/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java b/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java index 1cfef21c..619e1195 100644 --- a/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java +++ b/src/main/java/io/mosip/print/service/impl/UinCardGeneratorImpl.java @@ -1,21 +1,6 @@ package io.mosip.print.service.impl; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; - -import org.apache.commons.codec.binary.Base64; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.env.Environment; -import org.springframework.http.MediaType; -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.databind.ObjectMapper; - import io.mosip.print.constant.ApiName; import io.mosip.print.constant.PDFGeneratorExceptionCodeConstant; import io.mosip.print.constant.UinCardType; @@ -34,6 +19,19 @@ import io.mosip.print.spi.PDFGenerator; import io.mosip.print.util.DateUtils; import io.mosip.print.util.RestApiClient; +import org.apache.commons.codec.binary.Base64; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.core.env.Environment; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; /** * The Class UinCardGeneratorImpl. diff --git a/src/main/java/io/mosip/print/spi/PDFGenerator.java b/src/main/java/io/mosip/print/spi/PDFGenerator.java index 8d4b558b..27b57d0e 100644 --- a/src/main/java/io/mosip/print/spi/PDFGenerator.java +++ b/src/main/java/io/mosip/print/spi/PDFGenerator.java @@ -1,108 +1,108 @@ -package io.mosip.print.spi; - -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.URL; -import java.security.GeneralSecurityException; -import java.security.PrivateKey; -import java.security.Provider; -import java.security.cert.X509Certificate; -import java.util.List; - -import io.mosip.print.model.CertificateEntry; -import io.mosip.print.model.Rectangle; - -/** - * This interface is has specifications for PDF generation from different types. - * - * The user of this interface will have basic functionalities related to PDF. - * - * @author Urvil Joshi - * @author Uday Kumar - * @author Neha - * - * @since 1.0.0 - */ -public interface PDFGenerator { - /** - * Converts HTML obtained from an {@link InputStream} to a PDF written to an - * {@link OutputStream}. - * - * @param htmlStream the processedTemplate in the form of a {@link InputStream} - * @throws IOException Signals that an I/O exception has occurred. - * @return outpustStream PDF Output Stream (PDF stream) - */ - public OutputStream generate(InputStream htmlStream) throws IOException; - - /** - * This method will convert process Template as String to outpustStream - * - * @param template the processedTemplate in the form of a {@link String} - * @return OutputStream PDF Output Stream (PDF stream) - * @throws IOException Signals that an I/O exception has occurred. - */ - public OutputStream generate(String template) throws IOException; - - /** - * This method will take input as template file and convert template to PDF and - * save to the given path with given fileName. - * - * @param templatePath the processedTemplate in the form of a {@link String} - * @param outputFilePath Output File Path - * @param outputFileName Output File Name - * @throws IOException Signals that an I/O exception has occurred. - */ - public void generate(String templatePath, String outputFilePath, String outputFileName) throws IOException; - - /** - * This method will convert InputStream to OutputStream. - * - * @param dataStream the processedTemplate in the form of a - * {@link InputStream}. - * @param resourceLoc resourceLoction {@link String}. - * @throws IOException Signals that an I/O exception has occurred. - * @return outpustStream PDF Output Stream (PDF stream). - */ - public OutputStream generate(InputStream dataStream, String resourceLoc) throws IOException; - - /** - * This method will convert BufferedImage list to Byte Array. - * - * @param bufferedImages the input image to convert as PDF. - * @return array comprising PDF. - * @throws IOException Signals that an I/O exception has occurred. - */ - public byte[] asPDF(List bufferedImages) throws IOException; - - /** - * This method will merge all the PDF files. - * - * @param pdfLists the URL list of PDF files. - * @return the byte array comprising merged file. - * @throws IOException Signals that an I/O exception has occurred. - */ - public byte[] mergePDF(List pdfLists) throws IOException; - - /** - * Signs a PDF and protect it with password - * - * @param pdf byte array of pdf. - * @param rectangle {@link Rectangle} class to enclose signing - * @param reason reason of signing. - * @param pageNumber page number of rectangle. - * @param provider {@link Provider}. - * @param certificateEntry {@link CertificateEntry} class for certificate and - * private key as Input; - * @param password password for protecting pdf. - * @return {@link OutputStream} of signed PDF. - * @throws IOException Signals that an I/O exception has occurred. - * @throws GeneralSecurityException Signals general security exception while - * signing. - */ - OutputStream signAndEncryptPDF(byte[] pdf, Rectangle rectangle, String reason, int pageNumber, Provider provider, - CertificateEntry certificateEntry, String password) - throws IOException, GeneralSecurityException; - -} +package io.mosip.print.spi; + +import io.mosip.print.model.CertificateEntry; +import io.mosip.print.model.Rectangle; + +import java.awt.image.BufferedImage; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.cert.X509Certificate; +import java.util.List; + +/** + * This interface is has specifications for PDF generation from different types. + * + * The user of this interface will have basic functionalities related to PDF. + * + * @author Urvil Joshi + * @author Uday Kumar + * @author Neha + * + * @since 1.0.0 + */ +public interface PDFGenerator { + /** + * Converts HTML obtained from an {@link InputStream} to a PDF written to an + * {@link OutputStream}. + * + * @param htmlStream the processedTemplate in the form of a {@link InputStream} + * @throws IOException Signals that an I/O exception has occurred. + * @return outpustStream PDF Output Stream (PDF stream) + */ + public OutputStream generate(InputStream htmlStream) throws IOException; + + /** + * This method will convert process Template as String to outpustStream + * + * @param template the processedTemplate in the form of a {@link String} + * @return OutputStream PDF Output Stream (PDF stream) + * @throws IOException Signals that an I/O exception has occurred. + */ + public OutputStream generate(String template) throws IOException; + + /** + * This method will take input as template file and convert template to PDF and + * save to the given path with given fileName. + * + * @param templatePath the processedTemplate in the form of a {@link String} + * @param outputFilePath Output File Path + * @param outputFileName Output File Name + * @throws IOException Signals that an I/O exception has occurred. + */ + public void generate(String templatePath, String outputFilePath, String outputFileName) throws IOException; + + /** + * This method will convert InputStream to OutputStream. + * + * @param dataStream the processedTemplate in the form of a + * {@link InputStream}. + * @param resourceLoc resourceLoction {@link String}. + * @throws IOException Signals that an I/O exception has occurred. + * @return outpustStream PDF Output Stream (PDF stream). + */ + public OutputStream generate(InputStream dataStream, String resourceLoc) throws IOException; + + /** + * This method will convert BufferedImage list to Byte Array. + * + * @param bufferedImages the input image to convert as PDF. + * @return array comprising PDF. + * @throws IOException Signals that an I/O exception has occurred. + */ + public byte[] asPDF(List bufferedImages) throws IOException; + + /** + * This method will merge all the PDF files. + * + * @param pdfLists the URL list of PDF files. + * @return the byte array comprising merged file. + * @throws IOException Signals that an I/O exception has occurred. + */ + public byte[] mergePDF(List pdfLists) throws IOException; + + /** + * Signs a PDF and protect it with password + * + * @param pdf byte array of pdf. + * @param rectangle {@link Rectangle} class to enclose signing + * @param reason reason of signing. + * @param pageNumber page number of rectangle. + * @param provider {@link Provider}. + * @param certificateEntry {@link CertificateEntry} class for certificate and + * private key as Input; + * @param password password for protecting pdf. + * @return {@link OutputStream} of signed PDF. + * @throws IOException Signals that an I/O exception has occurred. + * @throws GeneralSecurityException Signals general security exception while + * signing. + */ + OutputStream signAndEncryptPDF(byte[] pdf, Rectangle rectangle, String reason, int pageNumber, Provider provider, + CertificateEntry certificateEntry, String password) + throws IOException, GeneralSecurityException; + +} diff --git a/src/main/java/io/mosip/print/util/TemplateGenerator.java b/src/main/java/io/mosip/print/util/TemplateGenerator.java index e6e40d48..d7cd26c3 100644 --- a/src/main/java/io/mosip/print/util/TemplateGenerator.java +++ b/src/main/java/io/mosip/print/util/TemplateGenerator.java @@ -1,140 +1,138 @@ -package io.mosip.print.util; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.lang.exception.ExceptionUtils; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.RuntimeConstants; -import org.apache.velocity.runtime.log.NullLogChute; -import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; -import org.apache.velocity.runtime.resource.loader.FileResourceLoader; -import org.slf4j.Logger; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.fasterxml.jackson.databind.ObjectMapper; - -import io.mosip.kernel.core.templatemanager.exception.TemplateMethodInvocationException; -import io.mosip.kernel.core.templatemanager.exception.TemplateParsingException; -import io.mosip.kernel.core.templatemanager.exception.TemplateResourceNotFoundException; -import io.mosip.print.constant.ApiName; -import io.mosip.print.constant.LoggerFileConstant; -import io.mosip.print.core.http.ResponseWrapper; -import io.mosip.print.dto.TemplateResponseDto; -import io.mosip.print.exception.ApisResourceAccessException; -import io.mosip.print.exception.PlatformErrorMessages; -import io.mosip.print.exception.TemplateProcessingFailureException; -import io.mosip.print.logger.PrintLogger; -import io.mosip.print.service.PrintRestClientService; -import io.mosip.print.service.impl.TemplateManagerImpl; -import io.mosip.print.spi.TemplateManager; - -/** - * The Class TemplateGenerator. - * - * @author M1048358 Alok - */ -@Component -public class TemplateGenerator { - - /** The reg proc logger. */ - private static Logger printLogger = PrintLogger.getLogger(TemplateGenerator.class); - - /** The resource loader. */ - private String resourceLoader = "classpath"; - - /** The template path. */ - private String templatePath = "."; - - /** The cache. */ - private boolean cache = Boolean.TRUE; - - /** The default encoding. */ - private String defaultEncoding = StandardCharsets.UTF_8.name(); - - /** The rest client service. */ - @Autowired - private PrintRestClientService restClientService; - - @Autowired - private ObjectMapper mapper; - - /** - * Gets the template. - * - * @param templateTypeCode - * the template type code - * @param attributes - * the attributes - * @param langCode - * the lang code - * @return the template - * @throws IOException - * Signals that an I/O exception has occurred. - * @throws ApisResourceAccessException - * the apis resource access exception - */ - public InputStream getTemplate(String templateTypeCode, Map attributes, String langCode) - throws IOException, ApisResourceAccessException { - - ResponseWrapper responseWrapper; - TemplateResponseDto template; - printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "TemplateGenerator::getTemplate()::entry"); - - try { - List pathSegments = new ArrayList<>(); - pathSegments.add(langCode); - pathSegments.add(templateTypeCode); - - responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.TEMPLATES, pathSegments, "", "", - ResponseWrapper.class); - template = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), - TemplateResponseDto.class); - - InputStream fileTextStream = null; - if (template != null) { - InputStream stream = new ByteArrayInputStream( - template.getTemplates().iterator().next().getFileText().getBytes()); - fileTextStream = getTemplateManager().merge(stream, attributes); - } - printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", - "TemplateGenerator::getTemplate()::exit"); - return fileTextStream; - - } catch (TemplateResourceNotFoundException | TemplateParsingException | TemplateMethodInvocationException e) { - printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), - null, PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.name() + e.getMessage() - + ExceptionUtils.getStackTrace(e)); - throw new TemplateProcessingFailureException(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getCode()); - } - } - - /** - * Gets the template manager. - * - * @return the template manager - */ - public TemplateManager getTemplateManager() { - final Properties properties = new Properties(); - properties.put(RuntimeConstants.INPUT_ENCODING, defaultEncoding); - properties.put(RuntimeConstants.OUTPUT_ENCODING, defaultEncoding); - properties.put(RuntimeConstants.ENCODING_DEFAULT, defaultEncoding); - properties.put(RuntimeConstants.RESOURCE_LOADER, resourceLoader); - properties.put(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); - properties.put(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, cache); - properties.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName()); - properties.put("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); - properties.put("file.resource.loader.class", FileResourceLoader.class.getName()); - VelocityEngine engine = new VelocityEngine(properties); - engine.init(); - return new TemplateManagerImpl(engine); - } -} +package io.mosip.print.util; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.mosip.kernel.core.templatemanager.exception.TemplateMethodInvocationException; +import io.mosip.kernel.core.templatemanager.exception.TemplateParsingException; +import io.mosip.kernel.core.templatemanager.exception.TemplateResourceNotFoundException; +import io.mosip.print.constant.ApiName; +import io.mosip.print.constant.LoggerFileConstant; +import io.mosip.print.core.http.ResponseWrapper; +import io.mosip.print.dto.TemplateResponseDto; +import io.mosip.print.exception.ApisResourceAccessException; +import io.mosip.print.exception.PlatformErrorMessages; +import io.mosip.print.exception.TemplateProcessingFailureException; +import io.mosip.print.logger.PrintLogger; +import io.mosip.print.service.PrintRestClientService; +import io.mosip.print.service.impl.TemplateManagerImpl; +import io.mosip.print.spi.TemplateManager; +import org.apache.commons.lang.exception.ExceptionUtils; +import org.apache.velocity.app.VelocityEngine; +import org.apache.velocity.runtime.RuntimeConstants; +import org.apache.velocity.runtime.log.NullLogChute; +import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader; +import org.apache.velocity.runtime.resource.loader.FileResourceLoader; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +/** + * The Class TemplateGenerator. + * + * @author M1048358 Alok + */ +@Component +public class TemplateGenerator { + + /** The reg proc logger. */ + private static Logger printLogger = PrintLogger.getLogger(TemplateGenerator.class); + + /** The resource loader. */ + private String resourceLoader = "classpath"; + + /** The template path. */ + private String templatePath = "."; + + /** The cache. */ + private boolean cache = Boolean.TRUE; + + /** The default encoding. */ + private String defaultEncoding = StandardCharsets.UTF_8.name(); + + /** The rest client service. */ + @Autowired + private PrintRestClientService restClientService; + + @Autowired + private ObjectMapper mapper; + + /** + * Gets the template. + * + * @param templateTypeCode + * the template type code + * @param attributes + * the attributes + * @param langCode + * the lang code + * @return the template + * @throws IOException + * Signals that an I/O exception has occurred. + * @throws ApisResourceAccessException + * the apis resource access exception + */ + public InputStream getTemplate(String templateTypeCode, Map attributes, String langCode) + throws IOException, ApisResourceAccessException { + + ResponseWrapper responseWrapper; + TemplateResponseDto template; + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "TemplateGenerator::getTemplate()::entry"); + + try { + List pathSegments = new ArrayList<>(); + pathSegments.add(langCode); + pathSegments.add(templateTypeCode); + + responseWrapper = (ResponseWrapper) restClientService.getApi(ApiName.TEMPLATES, pathSegments, "", "", + ResponseWrapper.class); + template = mapper.readValue(mapper.writeValueAsString(responseWrapper.getResponse()), + TemplateResponseDto.class); + + InputStream fileTextStream = null; + if (template != null) { + InputStream stream = new ByteArrayInputStream( + template.getTemplates().iterator().next().getFileText().getBytes()); + fileTextStream = getTemplateManager().merge(stream, attributes); + } + printLogger.debug(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.USERID.toString(), "", + "TemplateGenerator::getTemplate()::exit"); + return fileTextStream; + + } catch (TemplateResourceNotFoundException | TemplateParsingException | TemplateMethodInvocationException e) { + printLogger.error(LoggerFileConstant.SESSIONID.toString(), LoggerFileConstant.REGISTRATIONID.toString(), + null, PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.name() + e.getMessage() + + ExceptionUtils.getStackTrace(e)); + throw new TemplateProcessingFailureException(PlatformErrorMessages.PRT_TEM_PROCESSING_FAILURE.getCode()); + } + } + + /** + * Gets the template manager. + * + * @return the template manager + */ + public TemplateManager getTemplateManager() { + final Properties properties = new Properties(); + properties.put(RuntimeConstants.INPUT_ENCODING, defaultEncoding); + properties.put(RuntimeConstants.OUTPUT_ENCODING, defaultEncoding); + properties.put(RuntimeConstants.ENCODING_DEFAULT, defaultEncoding); + properties.put(RuntimeConstants.RESOURCE_LOADER, resourceLoader); + properties.put(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templatePath); + properties.put(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, cache); + properties.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, NullLogChute.class.getName()); + properties.put("classpath.resource.loader.class", ClasspathResourceLoader.class.getName()); + properties.put("file.resource.loader.class", FileResourceLoader.class.getName()); + VelocityEngine engine = new VelocityEngine(properties); + engine.init(); + return new TemplateManagerImpl(engine); + } +} diff --git a/src/main/resources/application-local1.properties b/src/main/resources/application-local1.properties index 23444a21..c5b20768 100644 --- a/src/main/resources/application-local1.properties +++ b/src/main/resources/application-local1.properties @@ -1,31 +1,12 @@ -mosip.event.hubURL=https://dev2.mosip.net/hub/ -mosip.partner.id=mpartner-default-print -mosip.datashare.partner.id=mpartner-default-resident -mosip.datashare.policy.id=mpolicy-default-resident -mosip.event.callBackUrl=https://4674-2409-4043-49d-d218-b7d1-c644-b1a2-a16b.ngrok.io/v1/print/print/callback/notifyPrint +mosip.event.hubURL=http://localhost:9191/websub/hub +mosip.partner.id=mpartner-msp-cardprint +mosip.event.callBackUrl=https://ac5a-2409-4072-191-6192-1c18-4dc9-87a2-8ff6.in.ngrok.io/v1/print/print/callback/notifyPrint mosip.event.topic=${mosip.partner.id}/CREDENTIAL_ISSUED csrf.disabled=true mosip.event.delay-millisecs=60000 print-websub-resubscription-delay-millisecs=1000000 mosip.event.secret=Kslk30SNF2AChs2 registration.processor.print.textfile=registration-processor-print-text-file.json -#-------------TOKEN GENERATION---------------- -#Token generation request id -token.request.id=io.mosip.registration.processor -#Token generation app id -token.request.appid=regproc -#Token generation username -token.request.username=registrationprocessor -#Token generation password -token.request.password=abc123 -#Token generation version -token.request.version=1.0 -#Token generation Client Id -token.request.clientId=mosip-regproc-client -#Token generation secret key -token.request.secretKey=abc123 -#Token generation issuer url -token.request.issuerUrl=http://keycloak/auth/realms/mosip #Audit Service AUDIT=https://dev2.mosip.net/v1/auditmanager/audits @@ -134,12 +115,12 @@ mosip.kernel.auth.appids.realm.map={prereg:'preregistration',ida:'mosip',registr #-----------------DATABASE Configuration --------------------------# mosip.database.ip=postgres-postgresql.postgres.svc.cluster.local mosip.database.port=5432 -hibernate.dialect: org.hibernate.dialect.PostgreSQLDialect -hibernate.hbm2ddl.auto: none -hibernate.jdbc.lob.non_contextual_creation: true -hibernate.show_sql: false -javax.persistence.jdbc.driver: org.postgresql.Driver -javax.persistence.jdbc.password: password +hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect +hibernate.hbm2ddl.auto= none +hibernate.jdbc.lob.non_contextual_creation= true +hibernate.show_sql= false +javax.persistence.jdbc.driver= org.postgresql.Driver +javax.persistence.jdbc.password= password javax.persistence.jdbc.url=jdbc:postgresql://dev2.mosip.net:5432/mosip_print?useSSL=false -javax.persistence.jdbc.user: postgres -mosip.application.id=io.mosip.print +javax.persistence.jdbc.user= postgres +mosip.application.id=io.mosip.print \ No newline at end of file diff --git a/src/main/resources/partner.p12 b/src/main/resources/partner.p12 index 64be7808..ed4abc6f 100644 Binary files a/src/main/resources/partner.p12 and b/src/main/resources/partner.p12 differ diff --git a/src/test/java/io/mosip/print/test/service/impl/PrintServiceTest.java b/src/test/java/io/mosip/print/test/service/impl/PrintServiceTest.java index 6908edf3..a60eeb13 100644 --- a/src/test/java/io/mosip/print/test/service/impl/PrintServiceTest.java +++ b/src/test/java/io/mosip/print/test/service/impl/PrintServiceTest.java @@ -20,21 +20,20 @@ import org.springframework.test.context.junit4.SpringRunner; import io.mosip.kernel.core.util.CryptoUtil; +import io.mosip.print.service.UinCardGenerator; import io.mosip.print.constant.QrVersion; import io.mosip.print.dto.IdResponseDTO1; import io.mosip.print.dto.ResponseDTO; import io.mosip.print.model.EventModel; import io.mosip.print.service.PrintRestClientService; -import io.mosip.print.service.UinCardGenerator; import io.mosip.print.service.impl.PrintServiceImpl; import io.mosip.print.spi.CbeffUtil; import io.mosip.print.spi.QrCodeGenerator; import io.mosip.print.test.TestBootApplication; import io.mosip.print.util.CryptoCoreUtil; import io.mosip.print.util.JsonUtil; -import io.mosip.print.util.TemplateGenerator; import io.mosip.print.util.Utilities; - +import io.mosip.print.util.TemplateGenerator; @SpringBootTest(classes = TestBootApplication.class) @RunWith(SpringRunner.class) diff --git a/src/test/java/io/mosip/print/test/util/UinCardGeneratorImplTest.java b/src/test/java/io/mosip/print/test/util/UinCardGeneratorImplTest.java index e3ba6af1..7099b8d3 100644 --- a/src/test/java/io/mosip/print/test/util/UinCardGeneratorImplTest.java +++ b/src/test/java/io/mosip/print/test/util/UinCardGeneratorImplTest.java @@ -26,6 +26,8 @@ import org.springframework.test.util.ReflectionTestUtils; import io.mosip.print.constant.UinCardType; +import io.mosip.print.service.impl.UinCardGeneratorImpl; +import io.mosip.print.spi.PDFGenerator; import io.mosip.print.core.http.ResponseWrapper; import io.mosip.print.dto.ErrorDTO; import io.mosip.print.dto.SignatureResponseDto; @@ -33,8 +35,6 @@ import io.mosip.print.exception.PDFGeneratorException; import io.mosip.print.exception.PDFSignatureException; import io.mosip.print.service.PrintRestClientService; -import io.mosip.print.service.impl.UinCardGeneratorImpl; -import io.mosip.print.spi.PDFGenerator; import io.mosip.print.test.TestBootApplication; @SpringBootTest(classes = TestBootApplication.class)