Commit b5a6a663 authored by Zane Safi Mroue's avatar Zane Safi Mroue
Browse files

Added functionality for database interaction with ObjectSet.java. Fixed server...

Added functionality for database interaction with ObjectSet.java. Fixed server issues, ran unit tests
parent 23b0c6d0
Loading
Loading
Loading
Loading
+55 −2
Original line number Diff line number Diff line
package org.group8;

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello world!");
        MongoDBInteraction dbInteraction = new MongoDBInteraction();

        // Test PointSet Operations
        String pointSetId = "set101";
        PointSet testPointSet = new PointSet(new Point(1.0f, 2.0f, 3.0f));
        System.out.println("Attempting to update/insert PointSet with ID: " + pointSetId);
        dbInteraction.update(pointSetId, testPointSet);
        System.out.println("PointSet Added/Updated");

        System.out.println("Attempting to retrieve PointSet with ID: " + pointSetId);
        PointSet retrievedPointSet = dbInteraction.retrieve(pointSetId);
        if (retrievedPointSet != null && !retrievedPointSet.getPoints().isEmpty()) {
            System.out.println("PointSet Retrieved Successfully");
        } else {
            System.out.println("PointSet Retrieve Failed");
        }

//        System.out.println("Attempting to delete PointSet with ID: " + pointSetId);
//        dbInteraction.delete(pointSetId);
//        PointSet deletedPointSet = dbInteraction.retrieve(pointSetId);
//        if (deletedPointSet == null) {
//            System.out.println("PointSet Successfully Deleted");
//        } else {
//            System.out.println("PointSet Delete Failed");
//        }

        // Test ObjectSet Operations
        ObjectSet objectSet = new ObjectSet();
        System.out.println("Creating and populating ObjectSet with two PointSets.");
        objectSet.makeObject(new Point(1, 2, 3), new Point(4, 5, 6));
        objectSet.makeObject(new Point(7, 8, 9), new Point(10, 11, 12));

        int index = 1;
        System.out.println("Attempting to update/insert ObjectSet at index: " + index);
        dbInteraction.updateObjectSet(index, objectSet);
        System.out.println("ObjectSet Add/Update Completed");

        System.out.println("Attempting to retrieve ObjectSet at index: " + index);
        ObjectSet retrievedObjectSet = dbInteraction.retrieveObjectSet(index);
        if (retrievedObjectSet != null && !retrievedObjectSet.objects.isEmpty()) {
            System.out.println("ObjectSet Retrieved Successfully");
        } else {
            System.out.println("ObjectSet Retrieve Failed");
        }

//        System.out.println("Attempting to delete ObjectSet at index: " + index);
//        dbInteraction.deleteObjectSet(index);
//        ObjectSet deletedObjectSet = dbInteraction.retrieveObjectSet(index);
//        if (deletedObjectSet == null) {
//            System.out.println("ObjectSet Successfully Deleted");
//        } else {
//            System.out.println("ObjectSet Delete Failed");
//        }
    }
}
+60 −15
Original line number Diff line number Diff line
@@ -17,16 +17,19 @@ public class MongoDBInteraction {
    private static final String uri = "mongodb+srv://Cluster03790:dlVzT2Z2bEh9@cluster03790.tk4cwyy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";
    private MongoClient mongoClient;
    private MongoDatabase database;
    private MongoCollection<Document> collection;
    private Map<String, PointSet> cache; // In-memory cache
    private MongoCollection<Document> pointCollection;
    private MongoCollection<Document> objectCollection;
    private Map<String, PointSet> cache; // In-memory cache for PointSets

    public MongoDBInteraction() {
        this.mongoClient = MongoClients.create(uri);
        this.database = mongoClient.getDatabase("Objects");
        this.collection = database.getCollection("pointSets");
        this.pointCollection = database.getCollection("pointSets");
        this.objectCollection = database.getCollection("objectSets");
        this.cache = new HashMap<>();
    }

    // PointSet management methods
    private Document pointSetToDocument(String setId, PointSet pointSet) {
        List<Document> pointsList = new ArrayList<>();
        for (Point p : pointSet.getPoints()) {
@@ -34,7 +37,6 @@ public class MongoDBInteraction {
                    .append("y", p.getY())
                    .append("z", p.getZ()));
        }

        return new Document("setId", setId)
                .append("points", pointsList);
    }
@@ -42,7 +44,7 @@ public class MongoDBInteraction {
    public void update(String setId, PointSet pointSet) {
        Document doc = pointSetToDocument(setId, pointSet);
        ReplaceOptions options = new ReplaceOptions().upsert(true);
        collection.replaceOne(Filters.eq("setId", setId), doc, options);
        pointCollection.replaceOne(Filters.eq("setId", setId), doc, options);
        cache.put(setId, pointSet);
    }

@@ -51,9 +53,8 @@ public class MongoDBInteraction {
        if (cachedPointSet != null) {
            return cachedPointSet;
        }

        Document query = new Document("setId", setId);
        Document doc = collection.find(query).first();
        Document doc = pointCollection.find(query).first();
        if (doc != null) {
            PointSet pointSet = convertDocumentToPointSet(doc);
            cache.put(setId, pointSet);
@@ -63,7 +64,7 @@ public class MongoDBInteraction {
    }

    public void delete(String setId) {
        collection.deleteOne(Filters.eq("setId", setId));
        pointCollection.deleteOne(Filters.eq("setId", setId));
        cache.remove(setId);
    }

@@ -79,12 +80,56 @@ public class MongoDBInteraction {
        return pointSet;
    }

    public static void main(String[] args) {
        MongoDBInteraction dbInteraction = new MongoDBInteraction();
        PointSet pointSet = new PointSet(new Point(1, 2, 3), new Point(4, 5, 6), new Point(7, 3, 1));
        dbInteraction.update("set13", pointSet);
        PointSet retrieved = dbInteraction.retrieve("set13");
        System.out.println("Retrieved Point Set: " + retrieved.getPoints());
        dbInteraction.delete("set13");
    // ObjectSet management methods
    private Document objectSetToDocument(int index, ObjectSet objectSet) {
        List<Document> pointSetsList = new ArrayList<>();
        int setId = 1;
        for (PointSet ps : objectSet.objects) {
            Document pointSetDoc = pointSetToDocument(String.valueOf(setId++), ps);
            pointSetsList.add(pointSetDoc);
        }
        return new Document("index", index)
                .append("objectSets", pointSetsList);
    }


    public void updateObjectSet(int index, ObjectSet objectSet) {
        Document doc = objectSetToDocument(index, objectSet);
        ReplaceOptions options = new ReplaceOptions().upsert(true);
        objectCollection.replaceOne(Filters.eq("index", index), doc, options);
    }

    public ObjectSet retrieveObjectSet(int index) {
        Document query = new Document("index", index);
        Document doc = objectCollection.find(query).first();
        if (doc != null) {
            return convertDocumentToObjectSet(doc);
        }
        return null;
    }

    public void deleteObjectSet(int index) {
        objectCollection.deleteOne(Filters.eq("index", index));
    }

    private ObjectSet convertDocumentToObjectSet(Document doc) {
        List<Document> pointSetsDocs = (List<Document>) doc.get("objectSets");
        ObjectSet objectSet = new ObjectSet();
        for (Document pointSetDoc : pointSetsDocs) {
            PointSet pointSet = convertDocumentToPointSet(pointSetDoc);
            objectSet.objects.add(pointSet);
        }
        return objectSet;
    }
}


//public static void main(String[] args) {
//        MongoDBInteraction dbInteraction = new MongoDBInteraction();
//        PointSet pointSet = new PointSet(new Point(1, 2, 3), new Point(4, 5, 6), new Point(7, 3, 1));
//        dbInteraction.update("set13", pointSet);
//        PointSet retrieved = dbInteraction.retrieve("set13");
//        System.out.println("Retrieved Point Set: " + retrieved.getPoints());
//        dbInteraction.delete("set13");
//    }
//}
+39 −38
Original line number Diff line number Diff line
package org.group8;

import com.google.gson.Gson;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import org.bson.Document;
import java.util.ArrayList;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.List;

import static spark.Spark.*;

public class Server {
@@ -16,53 +14,56 @@ public class Server {

        MongoDBInteraction dbInteraction = new MongoDBInteraction();

        get("/pointset/:setId", (request, response) -> {
        // Customize Gson to handle the specifics of your data structure
        Gson gson = new GsonBuilder().create();

        // ObjectSet GET endpoint
        get("/objectset/:index", (request, response) -> {
            response.type("application/json");
            String setId = request.params(":setId");
            PointSet pointSet = dbInteraction.retrieve(setId);
            try {
                int index = Integer.parseInt(request.params(":index"));
                ObjectSet objectSet = dbInteraction.retrieveObjectSet(index);

            if (pointSet != null) {
                return pointSetToJson(pointSet);
                if (objectSet != null) {
                    // Manually serialize the static list
                    return gson.toJson(ObjectSet.objects);
                } else {
                    response.status(404);
                    return "{}";
                }
            } catch (NumberFormatException e) {
                response.status(400);
                return "{\"error\":\"Invalid index format\"}";
            } catch (Exception e) {
                response.status(500);
                return "{\"error\":\"Internal Server Error\"}";
            }
        });

        post("/pointset/:setId", (request, response) -> {
            try {
        // ObjectSet POST endpoint
        post("/objectset/:index", (request, response) -> {
            response.type("application/json");
                String setId = request.params(":setId");
                PointSet pointSet = jsonToPointSet(request.body());
                dbInteraction.update(setId, pointSet);
                return pointSetToJson(pointSet);
            try {
                int index = Integer.parseInt(request.params(":index"));
                // Assume JSON is being sent correctly formatted to match the static list structure
                List<PointSet> receivedObjects = gson.fromJson(request.body(), new TypeToken<List<PointSet>>(){}.getType());
                ObjectSet.objects = receivedObjects; // Directly set the static list
                dbInteraction.updateObjectSet(index, new ObjectSet()); // Pass a new ObjectSet instance that will use the updated static list
                return gson.toJson(ObjectSet.objects);
            } catch (Exception e) {
                e.printStackTrace();
                response.status(500);
                return "Internal Server Error: " + e.getMessage();
                return "{\"error\":\"Internal Server Error: " + e.getMessage() + "\"}";
            }
        });


        delete("/pointset/:setId", (request, response) -> {
            String setId = request.params(":setId");
            dbInteraction.delete(setId);
        // ObjectSet DELETE endpoint
        delete("/objectset/:index", (request, response) -> {
            int index = Integer.parseInt(request.params(":index"));
            dbInteraction.deleteObjectSet(index);
            response.status(204);
            return "";
        });
    }

    private static String pointSetToJson(PointSet pointSet) {
        Gson gson = new Gson();
        return gson.toJson(pointSet);
    }

    private static PointSet jsonToPointSet(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, PointSet.class);
    }
}


ServerTest.java

0 → 100644
+55 −0
Original line number Diff line number Diff line
package org.group8;

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;

public class ServerTest {

    public static void main(String[] args) {
        // Start Unirest instance (optional if using newer versions)
        Unirest.config().defaultBaseUrl("http://localhost:8080");

        // Ensure your server is running before executing this main method
        try {
            testGetObjectSet();
            //testPostObjectSet();
            //testDeleteObjectSet();
        } finally {
            Unirest.shutDown();
        }
    }

    private static void testGetObjectSet() {
        System.out.println("Testing GET /objectset/:index");
        HttpResponse<String> response = Unirest.get("/objectset/1").asString();
        if (response.getStatus() == 200) {
            System.out.println("Success: " + response.getBody());
        } else {
            System.out.println("Failed: HTTP status " + response.getStatus());
        }
    }

//    private static void testPostObjectSet() {
//        System.out.println("Testing POST /objectset/:index");
//        String json = "{\"objects\":[{\"points\":[{\"x\":1,\"y\":2,\"z\":3},{\"x\":4,\"y\":5,\"z\":6}]}]}";
//        HttpResponse<String> response = Unirest.post("/objectset/2")
//                .header("Content-Type", "application/json")
//                .body(json)
//                .asString();
//        if (response.getStatus() == 200) {
//            System.out.println("Success: " + response.getBody());
//        } else {
//            System.out.println("Failed: HTTP status " + response.getStatus());
//        }
//    }
//
//    private static void testDeleteObjectSet() {
//        System.out.println("Testing DELETE /objectset/:index");
//        HttpResponse<String> response = Unirest.delete("/objectset/1").asString();
//        if (response.getStatus() == 204) {
//            System.out.println("Success: ObjectSet deleted successfully.");
//        } else {
//            System.out.println("Failed: HTTP status " + response.getStatus());
//        }
//    }
}