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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
import javax.imageio.ImageIO;
import javax.transaction.Transactional;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
Expand Down Expand Up @@ -77,14 +80,28 @@ public class CertificateServiceImpl implements CertificateService {
private static final String documents = retrieveDocuments();
private final int teluguStateCode = 40;
private final int chhatisgarhStateCode = 46;
private static File TeluguCertificateFile = new File(documents + "Certificate/TeluguSampleCertificate.pdf");
private static File chhatisgarhCertificateFile = new File(documents + "Certificate/ChhatisgarhAshaCertificateSample.pdf");
private static final File TeluguCertificateFile = new File(documents + "Certificate/TeluguSampleCertificate.pdf");
private static final File chhatisgarhCertificateFile = new File(documents + "Certificate/ChhatisgarhAshaCertificateSample.pdf");
private final String rootDir = documents + "WholeCertificate/Asha/";

BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

private Logger logger = LoggerFactory.getLogger(CertificateServiceImpl.class);

private static BufferedImage certificateSign1Image;
private static BufferedImage certificateSign2Image;
private static BufferedImage certificateSign3Image;

static {
try {
certificateSign1Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign1.png")));
certificateSign2Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign2.png")));
certificateSign3Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign3.png")));
} catch (IOException e) {
throw new RuntimeException("Failed to preload signature images", e);
}
}
Comment on lines +95 to +103
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Close streams and avoid crashing class initialization on missing images.

  • Files.newInputStream streams are never closed here, causing FD leaks.
  • Throwing at class init will fail app start if images are missing. Prefer logging and a graceful fallback.
  • Also reuse the already-initialized documents instead of re-calling retrieveDocuments().

Apply this diff:

 static {
     try {
-            certificateSign1Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign1.png")));
-            certificateSign2Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign2.png")));
-            certificateSign3Image = ImageIO.read(Files.newInputStream(Paths.get(retrieveDocuments() + "Certificate/certificate_sign3.png")));
-        } catch (IOException e) {
-            throw new RuntimeException("Failed to preload signature images", e);
-        }
+        certificateSign1Image = ImageIO.read(new File(documents + "Certificate/certificate_sign1.png"));
+        certificateSign2Image = ImageIO.read(new File(documents + "Certificate/certificate_sign2.png"));
+        certificateSign3Image = ImageIO.read(new File(documents + "Certificate/certificate_sign3.png"));
+    } catch (IOException e) {
+        LOGGER.warn("Failed to preload signature images; will fall back to on-demand loading.", e);
+        certificateSign1Image = null;
+        certificateSign2Image = null;
+        certificateSign3Image = null;
+    }
 }

Optionally add a tiny helper and fallback usage (outside this hunk) to on-demand load if cached is null:

// helper (place near deepCopy)
private static BufferedImage requireSignImage(BufferedImage cached, String relativePath) {
    if (cached != null) return cached;
    try { return ImageIO.read(new File(documents + relativePath)); }
    catch (IOException e) {
        LOGGER.error("Unable to load signature image: {}", relativePath, e);
        return null;
    }
}

And replace uses with requireSignImage(certificateSign1Image, "Certificate/certificate_sign1.png") etc.

🤖 Prompt for AI Agents
In
NMSReportingSuite/src/main/java/com/beehyv/nmsreporting/business/impl/CertificateServiceImpl.java
around lines 95-103, the static initializer opens Files.newInputStream without
closing streams, re-calls retrieveDocuments(), and throws a RuntimeException
which will break class initialization if images are missing; change to reuse the
already-initialized documents variable, read images with try-with-resources or
use ImageIO.read(File) so streams are closed, stop throwing from the static
block and instead catch exceptions, log the error via LOGGER.error(...) and
leave the static BufferedImage fields null as a graceful fallback, and
optionally add the suggested requireSignImage helper to lazily load and log
errors when images are requested.


@Override
public List<Map<String, String>> createSpecificCertificate(Long mobileNo, User currentUser) {

Expand Down Expand Up @@ -496,13 +513,13 @@ public Map<String, String> createAllCertificateUptoCurrentMonthInBulk(String for
for (MACourseFirstCompletion flw : flws) {
try {
if (flw.getFirstCompletionDate() != null) {

FrontLineWorkers frontLineWorker = frontLineWorkersDao.getFlwById(flw.getFlwId());
// creating directories
String dir = flw.getStateId() + "_" + stateName + "/";
if (flw.getDistrictId() != null) {
dir = dir + "/" + flw.getDistrictId() + "_" + districtMap.get(flw.getDistrictId());
if (flw.getBlockId() != null) {
dir = dir + "/" + flw.getBlockId() + "_" + blockMap.get(flw.getDistrictId()).get(flw.getBlockId());
String dir = frontLineWorker.getState() + "_" + stateName + "/";
if (frontLineWorker.getDistrict() != null) {
dir = dir + "/" + frontLineWorker.getDistrict() + "_" + districtMap.get(frontLineWorker.getDistrict());
if (frontLineWorker.getBlock() != null) {
dir = dir + "/" + frontLineWorker.getBlock() + "_" + blockMap.get(frontLineWorker.getDistrict()).get(frontLineWorker.getBlock());
} else {
dir = dir + "/" + "other";
}
Expand All @@ -515,9 +532,9 @@ public Map<String, String> createAllCertificateUptoCurrentMonthInBulk(String for
fileDr.mkdirs();
}

String fileName = flw.getMsisdn() + "_" + flw.getId() * 2 + 1 + ".pdf";
String fileName = frontLineWorker.getMobileNumber() + "_" + flw.getId() * 2 + 1 + ".pdf";

status = createCertificatePdf(rootDir + dir + "/" + fileName, frontLineWorkersDao.getFlwById(flw.getFlwId()).getFullName(), flw.getMsisdn(), flw.getFirstCompletionDate(), frontLineWorkersDao.getFlwById(flw.getFlwId()));
status = createCertificatePdf(rootDir + dir + "/" + fileName, frontLineWorker.getFullName(), frontLineWorker.getMobileNumber(), flw.getFirstCompletionDate(), frontLineWorker);
if (status.equalsIgnoreCase("success")) {
success++;
} else {
Expand Down Expand Up @@ -568,6 +585,7 @@ private String createCertificatePdf(String pdfFile, String name, Long msisdn, Da
document.addPage(sampleDocument.getPage(0));
textFont = PDType0Font.load( sampleDocument, new File(font_path) );
generateTeluguCertificate(document, textFont, name, rchId, msisdn, district, phc, village, healthSubFacility, completionDate);
LOGGER.info("Successfully generated Telugu certificate for FLW: {}", name);
} else if(state == chhatisgarhStateCode){
// File file = new File(documents + "Certificate/ChhatisgarhAshaCertificateSample.pdf");
sampleDocument = PDDocument.load(chhatisgarhCertificateFile);
Expand Down Expand Up @@ -632,6 +650,7 @@ private String createCertificatePdf(String pdfFile, String name, Long msisdn, Da
} catch (IOException ignore) {
response = "failed to load sample certificate";
System.out.println("---Error---=>" + response);
LOGGER.info(ignore.getMessage());
} finally {
try {
if (sampleDocument != null) {
Expand Down Expand Up @@ -699,44 +718,16 @@ private void generateTeluguCertificate(PDDocument document, PDFont textFont, Str

// be.quodlibet.boxable.utils.PDStreamUtils.write(contents, signature, textFont, textFontSize, signatureX, signatureY, Color.RED);

InputStream is = new FileInputStream(retrieveDocuments() + "Certificate/certificate_sign1.png");
byte[] bytes = IOUtils.toByteArray(is);
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
Image image1 = new Image(ImageIO.read(bin));
is.close();
bin.close();

float imageWidth = 110;
float imageHeight = 110;
image1 = image1.scaleByWidth(imageWidth);
image1 = image1.scaleByHeight(imageHeight);
image1.draw(document, contents1, signatureX1, signatureY -10);
// contents1.close();

InputStream is2 = new FileInputStream(retrieveDocuments() + "Certificate/certificate_sign2.png");
byte[] bytes2 = IOUtils.toByteArray(is2);
ByteArrayInputStream bin2 = new ByteArrayInputStream(bytes2);
Image image2 = new Image(ImageIO.read(bin2));
is2.close();
bin2.close();

float imageWidth2 = 65;
float imageHeight2 = 55;
image2 = image2.scaleByWidth(imageWidth2);
image2 = image2.scaleByHeight(imageHeight2);
image2.draw(document, contents1, signatureX2, signatureY+7);

InputStream is3 = new FileInputStream(retrieveDocuments() + "Certificate/certificate_sign3.png");
byte[] bytes3 = IOUtils.toByteArray(is3);
ByteArrayInputStream bin3 = new ByteArrayInputStream(bytes3);
Image image3 = new Image(ImageIO.read(bin3));
is3.close();
bin3.close();

float imageWidth3 = 125;
float imageHeight3 = 105;
image3 = image3.scaleByWidth(imageWidth3);
image3 = image3.scaleByHeight(imageHeight3);
Image image1 = new Image(deepCopy(certificateSign1Image));
image1 = image1.scaleByWidth(110).scaleByHeight(110);
image1.draw(document, contents1, signatureX1, signatureY - 10);

Image image2 = new Image(deepCopy(certificateSign2Image));
image2 = image2.scaleByWidth(65).scaleByHeight(55);
image2.draw(document, contents1, signatureX2, signatureY + 7);

Image image3 = new Image(deepCopy(certificateSign3Image));
image3 = image3.scaleByWidth(125).scaleByHeight(105);
image3.draw(document, contents1, signatureX3, signatureY + 17);
contents1.close();
} catch (IOException erros){
Expand Down Expand Up @@ -819,5 +810,12 @@ public static void zipFile(File fileToZip, String fileName, ZipOutputStream zipO
fis.close();
}

private static BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}


}
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ public Map<String,KilkariThematicContent> getKilkariThematicContentReportData(In
Restrictions.eq("locationId",locationId.longValue()),
Restrictions.eq("locationType",locationType),
Restrictions.eq("periodType",periodType),
Restrictions.eq("date", date)
// Restrictions.eq("messageWeekNumber", week_id)
Restrictions.eq("date", date),
Restrictions.ne("messageWeekNumber", "opt")
));
Comment on lines +36 to 38
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix Criteria construction; add null-safety for messageWeekNumber.

Good call excluding "opt". However, Restrictions.and only accepts two Criterion; passing 5 will not compile and/or won’t work as intended. Also consider excluding null messageWeekNumber values explicitly.

Apply this diff to build the predicates correctly and add isNotNull:

-        criteria.add(Restrictions.and(
-                Restrictions.eq("locationId",locationId.longValue()),
-                Restrictions.eq("locationType",locationType),
-                Restrictions.eq("periodType",periodType),
-                Restrictions.eq("date", date),
-                Restrictions.ne("messageWeekNumber", "opt")
-        ));
+        criteria.add(Restrictions.eq("locationId", locationId.longValue()));
+        criteria.add(Restrictions.eq("locationType", locationType));
+        criteria.add(Restrictions.eq("periodType", periodType));
+        criteria.add(Restrictions.eq("date", date));
+        criteria.add(Restrictions.isNotNull("messageWeekNumber"));
+        criteria.add(Restrictions.ne("messageWeekNumber", "opt"));

Also applies to: 32-38


List<KilkariThematicContent> result = (List<KilkariThematicContent>)criteria.list();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ public class ContactUs {
" </div>\n" +
" </div>-->\n" +
" <div class=\"col-sm-8 col-xs-8 col-lg-8 contactUs-locationColumn\">" +
" <p><b>Ms. Rangoli Pathak</b></p>\n" +
" <p>Deputy Director (MMP Cell)</p>\n" +
" <p>Room No. 407, Indian Red Cross Society Building</p>\n" +
" <p>Ministry of Health & Family Welfare</p>\n" +
" <p>New Delhi - 110011</p>\n" +
" <p>Email Id : rv.rangoli@gov.in</p>" +
" <p><b>Mr. Nikhil Agarwal</b></p>\n" +
" <p>Director, MMP Cell</p>\n" +
" <p>3rd Floor, Indian Red Cross Society Building,</p>\n" +
" <p>Ministry of Health & Family Welfare (MoHFW),</p>\n" +
" <p>Sansad Marg, New Delhi-110001</p>\n" +
" <p>Email Id - mmpc-mohfw@gov.in</p>" +
// " MMP Cell, MoHFW, Room No.509-D, Nirman\n" +
// " Bhawan, and New Delhi 110001.\n" +
" </div>\n" +
Expand Down