Browse Source

more classes and additional edge checking. WIP

Dr-Swopt 9 hours ago
parent
commit
e33fa7b3aa

+ 27 - 8
pom.xml

@@ -9,34 +9,53 @@
     <version>1.0-SNAPSHOT</version>
 
     <properties>
-        <!-- Specify the Java version Maven should use for compiling -->
         <maven.compiler.source>21</maven.compiler.source>
         <maven.compiler.target>21</maven.compiler.target>
     </properties>
 
+    <!-- Jackson BOM for version alignment -->
+    <dependencyManagement>
+        <dependencies>
+            <dependency>
+                <groupId>com.fasterxml.jackson</groupId>
+                <artifactId>jackson-bom</artifactId>
+                <version>2.17.0</version>
+                <type>pom</type>
+                <scope>import</scope>
+            </dependency>
+        </dependencies>
+    </dependencyManagement>
+
     <dependencies>
-        <!-- JSON dependency -->
+        <!-- JSON from org.json -->
         <dependency>
             <groupId>org.json</groupId>
             <artifactId>json</artifactId>
             <version>20231013</version>
         </dependency>
 
-        <!-- For JSON as well?? -->
+        <!-- Jackson core, databind, and CBOR all aligned to 2.17.0 via BOM -->
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-core</artifactId>
+        </dependency>
         <dependency>
             <groupId>com.fasterxml.jackson.core</groupId>
             <artifactId>jackson-databind</artifactId>
-            <version>2.13.0</version>
         </dependency>
-        
-        <!-- SourceAFIS dependency -->
+        <dependency>
+            <groupId>com.fasterxml.jackson.dataformat</groupId>
+            <artifactId>jackson-dataformat-cbor</artifactId>
+        </dependency>
+
+        <!-- SourceAFIS for fingerprint processing -->
         <dependency>
             <groupId>com.machinezoo.sourceafis</groupId>
             <artifactId>sourceafis</artifactId>
             <version>3.18.1</version>
         </dependency>
 
-        <!-- pom.xml -->
+        <!-- MessagePack -->
         <dependency>
             <groupId>org.msgpack</groupId>
             <artifactId>msgpack-core</artifactId>
@@ -52,7 +71,7 @@
                 <version>3.1.0</version>
                 <executions>
                     <execution>
-                        <phase>compile</phase>  <!-- Ensure it's part of the compile phase -->
+                        <phase>compile</phase>
                         <goals>
                             <goal>java</goal>
                         </goals>

+ 88 - 15
src/main/java/com/example/EventHandler.java

@@ -6,6 +6,7 @@ import java.util.ArrayList;
 import java.util.Base64;
 import java.util.Collections;
 import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import javax.imageio.ImageIO;
 
@@ -45,17 +46,27 @@ public class EventHandler {
 
             FingerprintCompareListItem[] fpTemplateList = new FingerprintCompareListItem[templateArray.length()];
             for (int i = 0; i < templateArray.length(); i++) {
-                System.out.println(templateArray);
                 JSONObject obj = templateArray.getJSONObject(i);
                 String name = obj.optString("name");
                 int fpPosition = obj.optInt("fpPosition");
                 String fpTemplateString = obj.optString("fpTemplate");
 
                 // Decoding it back to fingeprintTemplate so that afis can compare
-                byte[] templateBytes = Base64.getDecoder().decode(fpTemplateString);
-                FingerprintTemplate fpTemplate = new FingerprintTemplate(templateBytes);
+                // byte[] templateBytes = Base64.getDecoder().decode(fpTemplateString);
+                // FingerprintTemplate fpTemplate = new FingerprintTemplate(templateBytes);
+                try {
+                    byte[] templateBytes = Base64.getDecoder().decode(fpTemplateString);
+                    System.out.println("Decoded bytes length: " + templateBytes.length);
+
+                    FingerprintTemplate fpTemplate = new FingerprintTemplate(templateBytes);
+                    System.out.println("Successfully created FingerprintTemplate!");
+                    fpTemplateList[i] = new FingerprintCompareListItem(name, fpPosition, fpTemplate);
+                } catch (Exception e) {
+                    System.err.println("Error decoding or constructing FingerprintTemplate: " + e.getMessage());
+                    e.printStackTrace();
+                }
 
-                fpTemplateList[i] = new FingerprintCompareListItem(name, fpPosition, fpTemplate);
+                // fpTemplateList[i] = new FingerprintCompareListItem(name, fpPosition, fpTemplate);
             };
 
             if (imageBase64 == null || imageBase64.isEmpty()) {
@@ -68,6 +79,8 @@ public class EventHandler {
                     return handleRegistration(id, imageBase64, fpTemplateList, personInfo, fingerPosition);
                 case "verification":
                     return handleVerification(id, imageBase64, fpTemplateList, personInfo, fingerPosition);
+                case "qualityassurance":
+                    return handleQualityAssurance(id, imageBase64, fpTemplateList, personInfo, fingerPosition);
                 default:
                     // Unknown command fallback
                     JSONObject unknown = new JSONObject();
@@ -79,7 +92,7 @@ public class EventHandler {
         } catch (Exception e) {
             // Generic error response
             JSONObject error = new JSONObject();
-            error.put("error", "Failed to process message: " + e.getMessage());
+            error.put("message", "Failed to process message: " + e.getMessage());
             return error.toString();
         }
     }
@@ -87,6 +100,7 @@ public class EventHandler {
     public static String handleRegistration(String id, String imageBase64, FingerprintCompareListItem[] templateArray, PersonFingerprintData personInfo, int fingerPosition) {
         try {
             // Decode the fingerprint image from base64
+            Integer edgeScore = null;
             byte[] imageBytes = Base64.getDecoder().decode(imageBase64);
             BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
             if (image == null) {
@@ -96,10 +110,21 @@ public class EventHandler {
             // Create a FingerprintTemplate from the imageBytes
             FingerprintTemplate probeTemplate = new FingerprintTemplate(new FingerprintImage(imageBytes));
 
+            // Logic for transparency goes here
+            // ... <Edge Number Must be 250 to be considered success>
+            try (TransparencyContents transparency = new TransparencyContents()) {
+                FingerprintTemplate probe = new FingerprintTemplate(imageBytes);
+                transparency.accepts("edge-table");
+                transparency.take("edge-table", "application/cbor", imageBytes);
+                edgeScore = transparency.countEdgeNumber();
+            } catch (Exception e) {
+                System.out.println("Error: " + e.getMessage());
+            }
+
             // If no existing templates are provided, register the new one
             if (templateArray == null || templateArray.length <= 0) {
                 // Register this new template
-                String response = buildJavaResponse(id, "Registration", "Success", "No existing templates. Registered as new.", probeTemplate, 100.0, personInfo, fingerPosition);
+                String response = buildJavaResponse(id, "Registration", "Success", "No existing templates. Registered as new.", probeTemplate, 100.0, edgeScore, personInfo, fingerPosition);
                 return response.toString();  // Return the response as a JSON string
             }
 
@@ -121,16 +146,16 @@ public class EventHandler {
             // Return response based on score
             if (bestScore >= MATCH_THRESHOLD) {
                 // Match found
-                return buildJavaResponse(id, "Registration", "Registered", "Existing Fingerprint template found for " + matchedPerson + "!", probeTemplate, bestScore, personInfo, fingerPosition).toString();
+                return buildJavaResponse(id, "Registration", "Registered", "Existing Fingerprint template found for " + matchedPerson + "!", probeTemplate, bestScore, edgeScore, personInfo, fingerPosition).toString();
             } else {
                 // Register new template
-                String response = buildJavaResponse(id, "Registration", "Success", "New fingerprint template constructed.", probeTemplate, 100.0, personInfo, fingerPosition);
+                String response = buildJavaResponse(id, "Registration", "Success", "New fingerprint template constructed.", probeTemplate, 100.0, edgeScore, personInfo, fingerPosition);
                 return response.toString();
             }
 
         } catch (Exception e) {
             // Handle errors during registration
-            String errorResponse = buildJavaResponse(id, "Registration", "Failed", "Template Construction Failed: " + e.getMessage(), null, 0.0, personInfo, fingerPosition);
+            String errorResponse = buildJavaResponse(id, "Registration", "Failed", "Template Construction Failed: " + e.getMessage(), null, 0.0, null, personInfo, fingerPosition);
             return errorResponse.toString();
         }
     }
@@ -138,6 +163,7 @@ public class EventHandler {
     public static String handleVerification(String id, String imageBase64, FingerprintCompareListItem[] templateArray, PersonFingerprintData personInfo, int fingerPosition) {
         try {
             // Decode the fingerprint image from base64
+            Integer edgeScore = null;
             byte[] imageBytes = Base64.getDecoder().decode(imageBase64);
             BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
             if (image == null) {
@@ -147,6 +173,17 @@ public class EventHandler {
             // Create a FingerprintTemplate from the imageBytes
             FingerprintTemplate probeTemplate = new FingerprintTemplate(new FingerprintImage(imageBytes));
 
+            // Logic for transparency goes here
+            // ... <Edge Number Must be 250 to be considered success>
+            try (TransparencyContents transparency = new TransparencyContents()) {
+                FingerprintTemplate probe = new FingerprintTemplate(imageBytes);
+                transparency.accepts("edge-table");
+                transparency.take("edge-table", "application/cbor", imageBytes);
+                edgeScore = transparency.countEdgeNumber();
+            } catch (Exception e) {
+                System.out.println("Error: " + e.getMessage());
+            }
+
             double bestScore = 0;
             int matchedFingerprintPosition = 0; // just put 0 as default value for now
             String matchedPerson = null;
@@ -185,7 +222,7 @@ public class EventHandler {
                         fingerprints
                 );
                 // JavaResponse response = new JavaResponse(id, "Verification", "Match found.", matchedData, bestScore);
-                String response = buildJavaResponse(id, "Verification", "Registered", "Match found.", matchedFingerprintTemplate, bestScore, matchedData, matchedFingerprintPosition);
+                String response = buildJavaResponse(id, "Verification", "Registered", "Match found.", matchedFingerprintTemplate, bestScore, null, matchedData, matchedFingerprintPosition);
                 return response.toString();
             } else {
                 // No match
@@ -196,8 +233,7 @@ public class EventHandler {
                         personInfo.getCode(),
                         new ArrayList<Fingerprint>()
                 );
-                // JavaResponse response = new JavaResponse(id, "Verification", "No match found.", noMatchData, bestScore);
-                String response = buildJavaResponse(id, "Verification", "Not Registered", "No Match found.", matchedFingerprintTemplate, bestScore, noMatchData, fingerPosition); // defaul value
+                String response = buildJavaResponse(id, "Verification", "Not Registered", "No Match found.", probeTemplate, bestScore, null, noMatchData, fingerPosition); // defaul value
                 return response.toString();
             }
 
@@ -209,7 +245,43 @@ public class EventHandler {
                     personInfo.getCode(),
                     new ArrayList<Fingerprint>()
             );
-            String errorResponse = buildJavaResponse(id, "Verification", "Failed", "No Match found.", null, 0, personInfo, fingerPosition); // defaul value
+            String errorResponse = buildJavaResponse(id, "Verification", "Failed", "No Match found.", null, 0, null, personInfo, fingerPosition); // defaul value
+            return errorResponse.toString();
+        }
+    }
+
+    public static String handleQualityAssurance(String id, String imageBase64, FingerprintCompareListItem[] templateArray, PersonFingerprintData personInfo, int fingerPosition) {
+        try {
+            Integer edgeScore = null;
+            double bestScore = 0;
+            // Decode the fingerprint image from base64
+            byte[] imageBytes = Base64.getDecoder().decode(imageBase64);
+            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
+            if (image == null) {
+                throw new IllegalArgumentException("Invalid image format.");
+            }
+
+            // Create a FingerprintTemplate from the imageBytes
+            FingerprintTemplate probeTemplate = new FingerprintTemplate(new FingerprintImage(imageBytes));
+
+            // Logic for transparency goes here
+            // ... <Edge Number Must be 250 to be considered success>
+            try (TransparencyContents transparency = new TransparencyContents()) {
+                transparency.accepts("edge-table");
+                transparency.take("edge-table", "application/cbor", imageBytes);
+                edgeScore = transparency.countEdgeNumber();
+
+                // Addition features to verify against existing fingerprint data
+                String response = buildJavaResponse(id, "QualityAssurance", "Success", "Edge score result: " + bestScore, probeTemplate, bestScore, edgeScore, personInfo, fingerPosition); // defaul value
+                return response.toString();
+            } catch (Exception e) {
+                System.out.println("Error: " + e.getMessage());
+                String response = buildJavaResponse(id, "QualityAssurance", "Failed", "Edge score result: " + bestScore, probeTemplate, bestScore, edgeScore, personInfo, fingerPosition); // defaul value
+                return response.toString();
+            }
+        } catch (Exception e) {
+            // Handle errors during checking
+            String errorResponse = buildJavaResponse(id, "QualityAssurance", "Failed", "Unable to produce Edge score... " + e.getMessage(), null, 0.0, null, personInfo, fingerPosition);
             return errorResponse.toString();
         }
     }
@@ -221,6 +293,7 @@ public class EventHandler {
             String message,
             FingerprintTemplate fingerprintTemplate,
             double score,
+            Integer edgeScore,
             PersonFingerprintData personInfo,
             int fingerPosition) {
 
@@ -234,8 +307,8 @@ public class EventHandler {
         personInfo.addFingerprint(fingerprint);
 
         // Build the JavaResponse
-        JavaResponse javaResponse = new JavaResponse(id, operation, status, message, personInfo, score);
-        System.out.println("Java Response: " + javaResponse);
+        JavaResponse javaResponse = new JavaResponse(id, operation, status, message, personInfo, score, edgeScore);
+        // System.out.println("Java Response: " + javaResponse.toString());
 
         // Serialize JavaResponse to JSON string using Jackson
         try {

+ 25 - 5
src/main/java/com/example/Fingerprint.java

@@ -1,6 +1,7 @@
 package com.example;
 
 public class Fingerprint {
+
     private String name;
     private int fpPosition;
     private String fpTemplate;
@@ -12,20 +13,39 @@ public class Fingerprint {
         this.fpTemplate = fpTemplate;
     }
 
-    // Getters and Setters
-    public int getFingerPosition() {
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getFpPosition() {
         return fpPosition;
     }
 
-    public void setFingerPosition(int fpPosition) {
+    public void setFpPosition(int fpPosition) {
         this.fpPosition = fpPosition;
     }
 
-    public String getTemplate() {
+    public String getFpTemplate() {
         return fpTemplate;
     }
 
-    public void setTemplate(String fpTemplate) {
+    public void setFpTemplate(String fpTemplate) {
         this.fpTemplate = fpTemplate;
     }
+
+    // @Override
+    // public String toString() {
+    //     String shortTemplate = (fpTemplate != null && fpTemplate.length() > 20)
+    //             ? fpTemplate.substring(0, 20) + "..."
+    //             : fpTemplate;
+    //     return "Fingerprint{" +
+    //             "name='" + name + '\'' +
+    //             ", fpPosition=" + fpPosition +
+    //             ", fpTemplate='" + shortTemplate + '\'' +
+    //             '}';
+    // }
 }

+ 11 - 1
src/main/java/com/example/JavaResponse.java

@@ -8,9 +8,10 @@ public class JavaResponse {
     private String message;
     private PersonFingerprintData data;
     private Double score;
+    private Integer edgeScore;
 
     // Constructor
-    public JavaResponse(String id, String operation, String status, String message, PersonFingerprintData data, Double score) {
+    public JavaResponse(String id, String operation, String status, String message, PersonFingerprintData data, Double score, Integer edgeScore) {
         // logic here
         this.id = id;
         this.operation = operation;
@@ -18,6 +19,7 @@ public class JavaResponse {
         this.message = message;
         this.data = data;
         this.score = score;
+        this.edgeScore = edgeScore;
     }
 
     // Getters and Setters
@@ -69,4 +71,12 @@ public class JavaResponse {
         this.score = score;
     }
 
+    public Integer getEdgeScore() {
+        return edgeScore;
+    }
+
+    public void setEdgeScore(Integer edgeScore) {
+        this.edgeScore = edgeScore;
+    }
+
 }

+ 5 - 1
src/main/java/com/example/Main.java

@@ -1,8 +1,12 @@
 package com.example;
 
 public class Main {
+
     public static void main(String[] args) {
-        TCPServer.startServer(3005);
+        TCPServer.startApplication(3005);
+
+        MonitorMemory.startMemoryMonitor();// Starts background memory monitor
+        // No need to block manually — server keeps the JVM alive
         // TCPClient.startClient("127.0.0.1", 3003);
     }
 }

+ 36 - 0
src/main/java/com/example/MonitorMemory.java

@@ -0,0 +1,36 @@
+package com.example;
+
+public class MonitorMemory {
+
+    public static void printMemoryUsage() {
+        Runtime runtime = Runtime.getRuntime();
+
+        long totalMemory = runtime.totalMemory();
+        long freeMemory = runtime.freeMemory();
+        long usedMemory = totalMemory - freeMemory;
+        long maxMemory = runtime.maxMemory();
+
+        System.out.println("=== Memory Usage ===");
+        System.out.println("Used Memory: " + (usedMemory / 1024 / 1024) + " MB");
+        System.out.println("Free Memory: " + (freeMemory / 1024 / 1024) + " MB");
+        System.out.println("Total Memory: " + (totalMemory / 1024 / 1024) + " MB");
+        System.out.println("Max Memory: " + (maxMemory / 1024 / 1024) + " MB");
+        System.out.println("====================");
+    }
+
+    public static void startMemoryMonitor() {
+        Thread monitorThread = new Thread(() -> {
+            try {
+                while (true) {
+                    printMemoryUsage();
+                    Thread.sleep(5000); // 5 seconds
+                }
+            } catch (InterruptedException e) {
+                System.out.println("Memory monitor interrupted.");
+            }
+        });
+
+        monitorThread.setDaemon(true); // So it won't block program exit
+        monitorThread.start();
+    }
+}

+ 1 - 0
src/main/java/com/example/PersonFingerprintData.java

@@ -66,6 +66,7 @@ public class PersonFingerprintData {
         //     this.fingerprints = new ArrayList<Fingerprint>();
         // }
         this.fingerprints.add(fingerprint);
+        System.out.println("ingerprint log" + this.fingerprints);
     }
 
 }

+ 1 - 1
src/main/java/com/example/TCPServer.java

@@ -5,7 +5,7 @@ import java.net.ServerSocket;
 import java.net.Socket;
 
 public class TCPServer {
-    public static void startServer(int port) {
+    public static void startApplication(int port) {
         try (ServerSocket serverSocket = new ServerSocket(port)) {
             System.out.println("TCP Server started on port " + port);
 

+ 53 - 0
src/main/java/com/example/TransparencyContents.java

@@ -0,0 +1,53 @@
+package com.example;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.dataformat.cbor.CBORFactory;
+import com.fasterxml.jackson.dataformat.cbor.CBORParser;
+import com.machinezoo.sourceafis.FingerprintTransparency;
+
+// to  calcualte the edge of a fingerpint. Must exeed a specific amount to be considered a valid fingerprint data
+public class TransparencyContents extends FingerprintTransparency {
+
+    int edgeNumber = 0;
+
+    @Override
+    public void take(String key, String mime, byte[] data) {
+        try {
+            if ("edge-table".equals(key)) {
+                CBORFactory cborFactory = new CBORFactory();
+                ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
+                try (CBORParser cborParser = cborFactory.createParser(inputStream)) {
+                    JsonToken token;
+                    while ((token = cborParser.nextToken()) != null) {
+                        // Only check when token is a field name
+                        if (token == JsonToken.FIELD_NAME) {
+                            String fieldName = cborParser.getText();
+                            if ("length".equals(fieldName)) {
+                                edgeNumber++;
+                            }
+                        }
+                    }
+                    countEdgeNumber();
+                } catch (IOException e) {
+                    e.printStackTrace();   // <-- print full exception for debugging
+                    throw new IOException("Counting edge error", e);
+                }
+            }
+        } catch (NullPointerException | IOException ex) {
+            ex.printStackTrace();
+            System.out.println("Error: " + ex);
+        }
+    }
+
+    @Override
+    public boolean accepts(String key) {
+        return super.accepts(key);
+    }
+
+    public Integer countEdgeNumber() {
+        return edgeNumber;
+    }
+}

+ 2 - 0
target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst

@@ -1,9 +1,11 @@
 com\example\FingerprintCompareListItem.class
 com\example\Main.class
+com\example\TransparencyContents.class
 com\example\ClientHandler.class
 com\example\EventHandler.class
 com\example\Fingerprint.class
 com\example\JavaResponse.class
+com\example\MonitorMemory.class
 com\example\FingerprintImage.class
 com\example\TCPServer.class
 com\example\PersonFingerprintData.class

+ 2 - 0
target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

@@ -5,6 +5,8 @@ E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\FingerprintImage.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\JavaResponse.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\Main.java
+E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\MonitorMemory.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\PersonFingerprintData.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\TCPClient.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\TCPServer.java
+E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\TransparencyContents.java