Commit 5dc68eb7 authored by Rohan  Kumar's avatar Rohan Kumar
Browse files

Merge branch 'Database' into 'master'

Updated database and server code

See merge request ec504/ec504_projects/group8!9
parents 73ea3e76 c7d065f6
Loading
Loading
Loading
Loading

Main.java

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

public class Main {

    public static void main(String[] args) {
        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");
//        }
    }
}

MongoDBConnector.java

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

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.Arrays;
//THIS IS A CONNECTION TEST
public class MongoDBConnector {

    public static void main(String[] args) {
        // Replace credentials and dbname with actual values
        final String uri = "mongodb+srv://Cluster03790:dlVzT2Z2bEh9@cluster03790.tk4cwyy.mongodb.net/myFirstDatabase?retryWrites=true&w=majority";

        try (MongoClient mongoClient = MongoClients.create(uri)) {
            // Connect to the MongoDB cluster and access a database
            MongoDatabase database = mongoClient.getDatabase("myFirstDatabase");

            // Access a collection
            MongoCollection<Document> collection = database.getCollection("testCollection");

            // Create a document to insert
            Document doc = new Document("name", "MongoDB")
                    .append("type", "database")
                    .append("count", 1)
                    .append("versions", Arrays.asList("v3.2", "v4.0", "v4.2"))
                    .append("info", new Document("x", 203).append("y", 102));

            // Insert the document into the collection
            collection.insertOne(doc);

            // Retrieve and print the first document from the collection
            Document myDoc = collection.find().first();
            System.out.println(myDoc.toJson());
        } catch (Exception e) {
            System.err.println("An error occurred: " + e);
        }
    }
}
+135 −0
Original line number Diff line number Diff line
package org.group8;

import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.ReplaceOptions;
import org.bson.Document;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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> 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.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()) {
            pointsList.add(new Document("x", p.getX())
                    .append("y", p.getY())
                    .append("z", p.getZ()));
        }
        return new Document("setId", setId)
                .append("points", pointsList);
    }

    public void update(String setId, PointSet pointSet) {
        Document doc = pointSetToDocument(setId, pointSet);
        ReplaceOptions options = new ReplaceOptions().upsert(true);
        pointCollection.replaceOne(Filters.eq("setId", setId), doc, options);
        cache.put(setId, pointSet);
    }

    public PointSet retrieve(String setId) {
        PointSet cachedPointSet = cache.get(setId);
        if (cachedPointSet != null) {
            return cachedPointSet;
        }
        Document query = new Document("setId", setId);
        Document doc = pointCollection.find(query).first();
        if (doc != null) {
            PointSet pointSet = convertDocumentToPointSet(doc);
            cache.put(setId, pointSet);
            return pointSet;
        }
        return null;
    }

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

    private PointSet convertDocumentToPointSet(Document doc) {
        List<Document> pointsList = (List<Document>) doc.get("points");
        PointSet pointSet = new PointSet();
        for (Document pointDoc : pointsList) {
            float x = pointDoc.getDouble("x").floatValue();
            float y = pointDoc.getDouble("y").floatValue();
            float z = pointDoc.getDouble("z").floatValue();
            pointSet.addPoint(new Point(x, y, z));
        }
        return pointSet;
    }

    // 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");
//    }
//}

Point.java

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

public class Point {

    // index
    static int count = 0;

    // members
    private float x;
    private float y;
    private float z;
    final int idx;

    // METHODS

    /*
    Object Constructor of a feature in 3D
     */
    public Point(float xx, float yy, float zz){
        this.x = xx;
        this.y = yy;
        this.z = zz;
        this.idx = count++;
    }

    /**
     * helper function for equals overriding
     * @param aa : first point
     * @param bb : second point
     * @param err : error between aa and bb that is acceptable
     * @return true if points are close enough
     */
    public static boolean equals(Point aa, Point bb, float err){
        return (aa.x - bb.x < err) && (aa.y - bb.y < err) && (aa.z - bb.z < err);
    }

    @Override
    public boolean equals(Object o){
        if(getClass() != o.getClass()){
            return false;
        }
        Point p = (Point) o;
        return Point.equals(this, p, (float) 0.05);
    }

    @Override
    public int hashCode() {
        float res = this.x + this.y + this.z;
        return Float.hashCode(res);
    }
    @Override
    public String toString() {
        return "Point(" + this.x + " ," + this.y + " ," + this.z + ")";
    }

    public float getX() {
        return x;
    }
    public float getY() {
        return y;
    }
    public float getZ() {
        return z;
    }

}

PointSet.java

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

import java.util.*;

public class PointSet {

    static final int NUM_REPS = 10;
    Set<Point> pset;
    Point[] reps;

    /**
     *
     * @param pp : the points that this PointSet will contain
     */
    public PointSet(Point ...pp){
        pset = new HashSet<>();

        // add every point blankly to pointset
        pset.addAll(Arrays.asList(pp));
        reps = new Point[NUM_REPS];
    }

    public void addPoint(Point p){
        pset.add(p);
    }

    public void addAll(Point ...p) {
        Collections.addAll(pset, p);
    }

    public void addAll(List<Point> p) {
        pset.addAll(p);
    }

    public Point[] getSetReps(){
        return this.reps;
    }

    public List<Point> getPoints(){
        return new ArrayList<>(pset);
    }

    /**
     * This method is called on a specific Point, and updates the Point via
     * some disjoint sets' method.
     */
    public void updateReps(){
        // get first NUM_REPS from pset for now, will make more efficient later
        Iterator<Point> iter = this.pset.iterator();
        for(int i = 0; i < NUM_REPS; i++){

            // early exit if we have less than NUM_REPS points in the current object
            if(i == this.pset.size()) {
                return;
            }

            reps[i] = iter.next();
        }
    }

}
Loading