Procházet zdrojové kódy

integrate basic regisration and verifciation methods. To be tested again

Dr-Swopt před 6 hodinami
rodič
revize
3c7443ae2e

+ 7 - 0
pom.xml

@@ -22,6 +22,13 @@
             <version>20231013</version>
         </dependency>
 
+        <!-- For JSON as well?? -->
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+            <version>2.13.0</version>
+        </dependency>
+        
         <!-- SourceAFIS dependency -->
         <dependency>
             <groupId>com.machinezoo.sourceafis</groupId>

+ 3 - 2
src/main/java/com/example/ClientHandler.java

@@ -27,10 +27,11 @@ public class ClientHandler implements Runnable {
 
             String rawMessage;
             while ((rawMessage = in.readLine()) != null) {
-                System.out.println("📨 Received: " + rawMessage);
+                // System.out.println("📨 Received: " + rawMessage);
+                System.out.println("📨 Received Request" );
 
                 String response = EventHandler.handleEvent(rawMessage); // all fingerprint data goes through here
-                System.out.println("📤 Responding: " + response);
+                // System.out.println("📤 Responding: " + response);
                 out.println(response); // this is the part that is emits to the client
             }
 

+ 188 - 95
src/main/java/com/example/EventHandler.java

@@ -2,7 +2,10 @@ package com.example;
 
 import java.awt.image.BufferedImage;
 import java.io.ByteArrayInputStream;
+import java.util.ArrayList;
 import java.util.Base64;
+import java.util.Collections;
+import java.util.List;
 
 import javax.imageio.ImageIO;
 
@@ -12,6 +15,7 @@ import org.json.JSONObject;
 import com.machinezoo.sourceafis.FingerprintImage;
 import com.machinezoo.sourceafis.FingerprintMatcher;
 import com.machinezoo.sourceafis.FingerprintTemplate;
+import com.fasterxml.jackson.databind.ObjectMapper;
 
 public class EventHandler {
 
@@ -19,141 +23,230 @@ public class EventHandler {
 
     public static String handleEvent(String rawMessage) {
         try {
-            System.err.println(rawMessage);
-    
+            // System.err.println(rawMessage);  // Log raw message for debugging
+
             JSONObject message = new JSONObject(rawMessage);
-    
+
+            // Extract key fields from the JSON payload
             String id = message.optString("id", "unknown");
-            String cmd = message.optString("cmd", "").toLowerCase();
-            String data = message.optString("data", null); // base64 string
-    
-            if (data == null) {
-                throw new IllegalArgumentException("Missing base64 data payload");
+            String cmd = message.optString("cmd", "").toLowerCase(); // Normalize command
+            String imageBase64 = message.optString("fpScan", null);  // Base64 fingerprint image
+            int fingerPosition = message.optInt("fingerPosition", -1); // Optional finger position
+            JSONArray templateArray = message.optJSONArray("fpTemplateArray"); // Existing templates
+            JSONObject personInfoPayload = message.optJSONObject("personInfo"); // Optional person metadata This should be PersonFingerprintData
+
+            PersonFingerprintData personInfo = new PersonFingerprintData(
+                    personInfoPayload.optString("id"),
+                    personInfoPayload.optString("name"),
+                    personInfoPayload.optString("org"),
+                    personInfoPayload.optString("code"),
+                    new ArrayList<Fingerprint>()
+            );
+
+            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);
+
+                fpTemplateList[i] = new FingerprintCompareListItem(name, fpPosition, fpTemplate);
+            };
+
+            if (imageBase64 == null || imageBase64.isEmpty()) {
+                throw new IllegalArgumentException("Missing fpScan (base64 image) data.");
             }
-    
+
+            // Route command to appropriate handler
             switch (cmd) {
                 case "registration":
-                    return handleRegistration(id, data, message);
-                // case "verification":
-                //     return handleVerification(...);
-                case "extract template":
-                    return handleExtractTemplate(id, data);
+                    return handleRegistration(id, imageBase64, fpTemplateList, personInfo, fingerPosition);
+                case "verification":
+                    return handleVerification(id, imageBase64, fpTemplateList, personInfo, fingerPosition);
                 default:
+                    // Unknown command fallback
                     JSONObject unknown = new JSONObject();
                     unknown.put("id", id);
                     unknown.put("message", "Unknown command: " + cmd);
                     return unknown.toString();
             }
-    
+
         } catch (Exception e) {
+            // Generic error response
             JSONObject error = new JSONObject();
             error.put("error", "Failed to process message: " + e.getMessage());
             return error.toString();
         }
     }
-    
 
-    private static String handleRegistration(String id, String imageBase64, JSONObject message) {
+    public static String handleRegistration(String id, String imageBase64, FingerprintCompareListItem[] templateArray, PersonFingerprintData personInfo, int fingerPosition) {
         try {
-            // Extract the fingerprint template array (fpTemplateArray) from the root-level message
-            JSONArray templateArray = message.optJSONArray("fpTemplateArray");
-    
-            if (imageBase64 == null || templateArray == null) {
-                throw new IllegalArgumentException("Missing image data or template array.");
-            }
-    
-            // Convert Base64 image to BufferedImage
+            // 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 fingerprint template from the image
+
+            // Create a FingerprintTemplate from the imageBytes
             FingerprintTemplate probeTemplate = new FingerprintTemplate(new FingerprintImage(imageBytes));
-    
-            // If the template array is empty, skip the matching logic
-            if (templateArray.isEmpty()) {
-                // No existing templates to compare with, proceed with registration of the new template
-                String newTemplateB64 = Base64.getEncoder().encodeToString(probeTemplate.toByteArray());
-    
-                JSONObject response = new JSONObject();
-                response.put("id", id);
-                response.put("message", "New fingerprint template constructed.");
-                response.put("data", newTemplateB64);
-                response.put("score", 100);
-                return response.toString();
+
+            // 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);
+                return response.toString();  // Return the response as a JSON string
             }
-    
-            // Compare with existing templates (if any)
-            for (int i = 0; i < templateArray.length(); i++) {
-                String templateB64 = templateArray.getString(i);
-                byte[] templateBytes = Base64.getDecoder().decode(templateB64);
-                FingerprintTemplate candidate = new FingerprintTemplate(templateBytes);
-    
+
+            // Compare with existing templates
+            double bestScore = 0;
+            String matchedPerson = null;
+
+            for (FingerprintCompareListItem entry : templateArray) {
+                String personName = entry.getName();
+                FingerprintTemplate candidate = entry.getFingerprint();
+
                 double score = new FingerprintMatcher(probeTemplate).match(candidate);
-                if (score >= MATCH_THRESHOLD) {
-                    JSONObject response = new JSONObject();
-                    response.put("id", id);
-                    response.put("message", "Fingerprint already registered.");
-                    response.put("score", score);
-                    response.put("data", JSONObject.NULL);
-                    return response.toString();
+                if (score > bestScore) {
+                    bestScore = score;
+                    matchedPerson = personName;
                 }
             }
-    
-            // No match: register new
-            String newTemplateB64 = Base64.getEncoder().encodeToString(probeTemplate.toByteArray());
-    
-            JSONObject response = new JSONObject();
-            response.put("id", id);
-            response.put("message", "New fingerprint template constructed.");
-            response.put("data", newTemplateB64);
-            response.put("score", 100);
-            return response.toString();
-    
+
+            // 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();
+            } else {
+                // Register new template
+                String response = buildJavaResponse(id, "Registration", "Success", "New fingerprint template constructed.", probeTemplate, 100.0, personInfo, fingerPosition);
+                return response.toString();
+            }
+
         } catch (Exception e) {
-            JSONObject error = new JSONObject();
-            error.put("error", "Registration failed: " + e.getMessage());
-            return error.toString();
+            // Handle errors during registration
+            String errorResponse = buildJavaResponse(id, "Registration", "Failed", "Template Construction Failed: " + e.getMessage(), null, 0.0, personInfo, fingerPosition);
+            return errorResponse.toString();
         }
     }
-    
-    
 
-    private static String handleVerification(JSONObject data) {
+    public static String handleVerification(String id, String imageBase64, FingerprintCompareListItem[] templateArray, PersonFingerprintData personInfo, int fingerPosition) {
         try {
-            // logic here
+            // 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));
+
+            double bestScore = 0;
+            int matchedFingerprintPosition = 0; // just put 0 as default value for now
+            String matchedPerson = null;
+            FingerprintTemplate matchedFingerprintTemplate = null;
+
+            for (int i = 0; i < templateArray.length; i++) {
+                FingerprintCompareListItem entry = templateArray[i];
+                String personName = entry.getName();
+                int fpPosition = entry.getFingerPosition();
+                FingerprintTemplate candidateTemplate = entry.getFingerprint();
+
+                // Maybe there's no need to check? will see about it later
+                if (candidateTemplate == null) {
+                    continue;
+                }
+
+                double score = new FingerprintMatcher(probeTemplate).match(candidateTemplate);
+
+                if (score > bestScore) {
+                    bestScore = score;
+                    matchedFingerprintPosition = fpPosition;
+                    matchedPerson = personName;
+                    matchedFingerprintTemplate = candidateTemplate;
+                }
+            }
+
+            if (bestScore >= MATCH_THRESHOLD) {
+                // Match found
+                Fingerprint matchedFingerprint = new Fingerprint(matchedPerson, matchedFingerprintPosition, Base64.getEncoder().encodeToString(matchedFingerprintTemplate.toByteArray()));
+                List<Fingerprint> fingerprints = Collections.singletonList(matchedFingerprint);
+                PersonFingerprintData matchedData = new PersonFingerprintData(
+                        personInfo.getId(),
+                        matchedPerson,
+                        personInfo.getOrg(),
+                        personInfo.getCode(),
+                        fingerprints
+                );
+                // JavaResponse response = new JavaResponse(id, "Verification", "Match found.", matchedData, bestScore);
+                String response = buildJavaResponse(id, "Verification", "Registered", "Match found.", matchedFingerprintTemplate, bestScore, matchedData, matchedFingerprintPosition);
+                return response.toString();
+            } else {
+                // No match
+                PersonFingerprintData noMatchData = new PersonFingerprintData(
+                        personInfo.getId(),
+                        personInfo.getName(),
+                        personInfo.getOrg(),
+                        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
+                return response.toString();
+            }
+
         } catch (Exception e) {
+            PersonFingerprintData errorData = new PersonFingerprintData(
+                    personInfo.getId(),
+                    personInfo.getName(),
+                    personInfo.getOrg(),
+                    personInfo.getCode(),
+                    new ArrayList<Fingerprint>()
+            );
+            String errorResponse = buildJavaResponse(id, "Verification", "Failed", "No Match found.", null, 0, personInfo, fingerPosition); // defaul value
+            return errorResponse.toString();
         }
-        return null;
     }
 
-    public static String handleExtractTemplate(String id, String base64) {
+    public static String buildJavaResponse(
+            String id,
+            String operation,
+            String status,
+            String message,
+            FingerprintTemplate fingerprintTemplate,
+            double score,
+            PersonFingerprintData personInfo,
+            int fingerPosition) {
+
+        // Convert the FingerprintTemplate to a base64-encoded string (assuming `FingerprintTemplate` has a way to do this)
+        String templateBase64 = (fingerprintTemplate != null) ? Base64.getEncoder().encodeToString(fingerprintTemplate.toByteArray()) : "";
+
+        // Construct the fingerprint data (if there is a fingerprint template)
+        Fingerprint fingerprint = new Fingerprint(personInfo.getName(), fingerPosition, templateBase64);
+
+        // Add the fingerprint to the personInfo
+        personInfo.addFingerprint(fingerprint);
+
+        // Build the JavaResponse
+        JavaResponse javaResponse = new JavaResponse(id, operation, status, message, personInfo, score);
+        System.out.println("Java Response: " + javaResponse);
+
+        // Serialize JavaResponse to JSON string using Jackson
         try {
-            byte[] imageBytes = Base64.getDecoder().decode(base64);
-            BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageBytes));
-    
-            if (image == null) {
-                throw new IllegalArgumentException("Invalid image data.");
-            }
-    
-            FingerprintTemplate template = new FingerprintTemplate(new FingerprintImage(imageBytes));
-    
-            JSONObject response = new JSONObject();
-            response.put("id", id);
-            response.put("message", "Fingerprint template successfully extracted.");
-            response.put("data", Base64.getEncoder().encodeToString(template.toByteArray())); // optional
-    
-            return response.toString();
-    
+            ObjectMapper mapper = new ObjectMapper();
+            String jsonResponse = mapper.writeValueAsString(javaResponse);
+            return jsonResponse;
         } catch (Exception e) {
-            JSONObject error = new JSONObject();
-            error.put("id", id);
-            error.put("error", "Template extraction failed: " + e.getMessage());
-            return error.toString();
+            // Handle exception if serialization fails
+            e.printStackTrace();
+            return "{\"error\":\"Failed to serialize response\"}";
         }
     }
-    
+
 }

+ 31 - 0
src/main/java/com/example/Fingerprint.java

@@ -0,0 +1,31 @@
+package com.example;
+
+public class Fingerprint {
+    private String name;
+    private int fpPosition;
+    private String fpTemplate;
+
+    // Constructor
+    public Fingerprint(String name, int fpPosition, String fpTemplate) {
+        this.name = name;
+        this.fpPosition = fpPosition;
+        this.fpTemplate = fpTemplate;
+    }
+
+    // Getters and Setters
+    public int getFingerPosition() {
+        return fpPosition;
+    }
+
+    public void setFingerPosition(int fpPosition) {
+        this.fpPosition = fpPosition;
+    }
+
+    public String getTemplate() {
+        return fpTemplate;
+    }
+
+    public void setTemplate(String fpTemplate) {
+        this.fpTemplate = fpTemplate;
+    }
+}

+ 43 - 0
src/main/java/com/example/FingerprintCompareListItem.java

@@ -0,0 +1,43 @@
+package com.example;
+
+import com.machinezoo.sourceafis.FingerprintTemplate;
+
+public class FingerprintCompareListItem {
+
+    private String name;
+    private int fpPosition;
+    private FingerprintTemplate fpTemplate;
+
+    public FingerprintCompareListItem(String name, int fpPosition, FingerprintTemplate fpTemplate) {
+        this.name = name;
+        this.fpPosition = fpPosition;
+        this.fpTemplate = fpTemplate;
+    }
+
+    // Getters and Setters
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    // Getters and Setters
+    public int getFingerPosition() {
+        return fpPosition;
+    }
+
+    public void setFingerPosition(int fpPosition) {
+        this.fpPosition = fpPosition;
+    }
+
+    public FingerprintTemplate getFingerprint() {
+        return fpTemplate;
+    }
+
+    public void setFingerprint(FingerprintTemplate fpTemplate) {
+        this.fpTemplate = fpTemplate;
+    }
+
+}

+ 21 - 0
src/main/java/com/example/FingerprintImage.java

@@ -0,0 +1,21 @@
+package com.example;
+
+import java.awt.image.BufferedImage;
+
+public class FingerprintImage {
+    private byte[] imageBytes;
+
+    // Constructor
+    public FingerprintImage(byte[] imageBytes) {
+        this.imageBytes = imageBytes;
+    }
+
+    // Getter and Setter
+    public byte[] getImageBytes() {
+        return imageBytes;
+    }
+
+    public void setImageBytes(byte[] imageBytes) {
+        this.imageBytes = imageBytes;
+    }
+}

+ 72 - 0
src/main/java/com/example/JavaResponse.java

@@ -0,0 +1,72 @@
+package com.example;
+
+public class JavaResponse {
+
+    private String id;
+    private String operation;
+    private String status;
+    private String message;
+    private PersonFingerprintData data;
+    private Double score;
+
+    // Constructor
+    public JavaResponse(String id, String operation, String status, String message, PersonFingerprintData data, Double score) {
+        // logic here
+        this.id = id;
+        this.operation = operation;
+        this.status = status;
+        this.message = message;
+        this.data = data;
+        this.score = score;
+    }
+
+    // Getters and Setters
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getOperation() {
+        return operation;
+    }
+
+    public void setOperation(String status) {
+        this.status = status;
+    }
+
+    public String getStatus() {
+        return status;
+    }
+
+    public void setStatus(String status) {
+        this.status = status;
+    }
+
+    public String getMessage() {
+        return message;
+    }
+
+    public void setMessage(String message) {
+        this.message = message;
+    }
+
+    public PersonFingerprintData getData() {
+        return data;
+    }
+
+    public void setData(PersonFingerprintData data) {
+        this.data = data;
+    }
+
+    public Double getScore() {
+        return score;
+    }
+
+    public void setData(Double score) {
+        this.score = score;
+    }
+
+}

+ 0 - 25
src/main/java/com/example/Models.java

@@ -1,25 +0,0 @@
-package com.example;
-
-import java.sql.Date;
-import java.util.List;
-
-public class Models {
-
-    public class FpVerificationPayload {
-        public String id;
-        public String cmd;
-        public Date date;
-        public Object data;
-        public String fpTemplate; // base64 string
-        public List<String> fpTemplateArray; // list of base64 strings
-        public String message;
-    }
-
-    public class FpVerificationResponse {
-        public String id;
-        public String message;
-        public String data;
-        public Double score;
-    }
-
-}

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

@@ -0,0 +1,71 @@
+package com.example;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class PersonFingerprintData {
+
+    private String id;
+    private String name;
+    private String org;
+    private String code;
+    private List<Fingerprint> fingerprints;
+
+    // Constructor
+    public PersonFingerprintData(String id, String name, String org, String code, List<Fingerprint> fingerprints) {
+        this.id = id;
+        this.name = name;
+        this.org = org;
+        this.code = code;
+        this.fingerprints = new ArrayList<Fingerprint>(); // ✅ Fixed typo
+    }
+
+    // Getters and Setters
+    public String getId() {
+        return id;
+    }
+
+    public void setId(String id) {
+        this.id = id;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public String getOrg() {
+        return org;
+    }
+
+    public void setOrg(String org) {
+        this.org = org;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+    public void setCode(String code) {
+        this.code = code;
+    }
+
+    public List<Fingerprint> getFingerprints() {
+        return fingerprints;
+    }
+
+    public void setFingerprints(List<Fingerprint> fingerprints) {
+        this.fingerprints = fingerprints;
+    }
+
+    public void addFingerprint(Fingerprint fingerprint) {
+        // if (this.fingerprints == null) {
+        //     this.fingerprints = new ArrayList<Fingerprint>();
+        // }
+        this.fingerprints.add(fingerprint);
+    }
+
+}

+ 5 - 3
target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst

@@ -1,8 +1,10 @@
+com\example\FingerprintCompareListItem.class
 com\example\Main.class
 com\example\ClientHandler.class
 com\example\EventHandler.class
-com\example\Models.class
+com\example\Fingerprint.class
+com\example\JavaResponse.class
+com\example\FingerprintImage.class
 com\example\TCPServer.class
-com\example\Models$FpVerificationResponse.class
+com\example\PersonFingerprintData.class
 com\example\TCPClient.class
-com\example\Models$FpVerificationPayload.class

+ 5 - 1
target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst

@@ -1,6 +1,10 @@
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\ClientHandler.java
 E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\EventHandler.java
+E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\Fingerprint.java
+E:\Task\Fingerprint\microservices\libs\java\FingerprintDataVerification\src\main\java\com\example\FingerprintCompareListItem.java
+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\Models.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