<commit_before>/*
 * Copyright 2014 <NAME> <<EMAIL>>..
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mongocom.management;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mongocom.annotations.Document;
import com.mongocom.annotations.Internal;
import com.mongocom.annotations.ObjectId;
import com.mongocom.annotations.Reference;
import com.mongodb.BasicDBList;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import java.io.Closeable;
import org.bson.types.BasicBSONList;

/**
 *
 * @author <NAME> <<EMAIL>>.
 */
public final class CollectionManager implements Closeable {

    private final MongoClient client;
    private DB db;

    //TODO: a better way to manage db connection
    protected CollectionManager(MongoClient client, String dataBase) {
        this.client = client;
        if (dataBase != null && !dataBase.equals("")) {
            this.db = client.getDB(dataBase);
        } else {
            this.db = client.getDB(client.getDatabaseNames().get(0));
        }
    }

    public void useDB(String dbName) {
        db = client.getDB(dbName);
    }

    public <A extends Object> long count(Class<A> collectionClass) {
        return count(collectionClass, new MongoQuery());
    }

    public <A extends Object> long count(Class<A> collectionClass, MongoQuery query) {
        long ret = 0l;
        try {
            A result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            ret = db.getCollection(collName).count(query.getQuery());
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ret;
    }

    public <A extends Object> List<A> find(Class<A> collectionClass) {
        return find(collectionClass, new MongoQuery());
    }

    public <A extends Object> List<A> find(Class<A> collectionClass, MongoQuery query) {
        List<A> resultSet = new ArrayList<>();
        DBCursor cursor = null;
        try {
            A obj = collectionClass.newInstance();
            String collName = reflectAnnotation(obj);
            cursor = db.getCollection(collName).find(query.getQuery(), query.getConstraits());
            if (query.getSkip() > 0) {
                cursor = cursor.skip(query.getSkip());
            }
            if (query.getLimit() > 0) {
                cursor = cursor.limit(query.getLimit());
            }
            while (cursor.hasNext()) {
                DBObject objDB = cursor.next();
                fillFields(obj, objDB);
                resultSet.add(obj);
                obj = collectionClass.newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            cursor.close();
        }
        return resultSet;
    }

    private <A extends Object> void fillFields(A obj, DBObject objDB) throws IllegalAccessException, IllegalArgumentException, SecurityException, InstantiationException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            String fieldName = f.getName();
            Object fieldContent = objDB.get(fieldName);
            if (fieldContent instanceof BasicBSONList) {
                List<Object> list = new ArrayList<>();
                for (Object item : (BasicBSONList) fieldContent) {
                    if (f.isAnnotationPresent(Internal.class)) {
                        Object t = f.getType().getComponentType().newInstance();
                        fillFields(t, (DBObject) item);
                        list.add(t);
                    }
                }
                f.set(obj, list);
            }
            if (fieldContent != null && f.isAnnotationPresent(ObjectId.class)) {
                f.set(obj, ((BasicDBObject) fieldContent).getString("_id"));
            } else if (fieldContent != null && f.isAnnotationPresent(Reference.class)) {
                f.set(obj, findById(f.getType(), ((org.bson.types.ObjectId) fieldContent).toString()));
            } else if (fieldContent == null && f.getType().isPrimitive()) {

            } else {
                f.set(obj, fieldContent);

            }
        }
    }

    public <A extends Object> A findOne(Class<A> collectionClass) {
        A result = null;
        try {
            result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            DBObject obj = db.getCollection(collName).findOne();
            if (obj == null) {
                return null;
            }
            fillFields(result, obj);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public <A extends Object> A findOne(Class<A> collectionClass, MongoQuery query) {
        A result = null;
        try {
            result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            DBObject obj = db.getCollection(collName).findOne(query.getQuery(), query.getConstraits());
            if (obj == null) {
                return null;
            }
            fillFields(result, obj);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public <A extends Object> A findById(Class<A> collectionClass, String id) {
        return findOne(collectionClass, new MongoQuery("_id", new org.bson.types.ObjectId(id)));
    }

    public void remove(Object document) {
        try {
            BasicDBObject obj = fillDBObject(document);
            String collName = reflectAnnotation(document);
            db.getCollection(collName).remove(obj);<commit_msg>fix some bugs on find documents with internal/reference<commit_after>/*
 * Copyright 2014 <NAME> <<EMAIL>>..
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mongocom.management;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mongocom.annotations.Document;
import com.mongocom.annotations.Internal;
import com.mongocom.annotations.ObjectId;
import com.mongocom.annotations.Reference;
import com.mongodb.BasicDBList;
import com.mongodb.MongoClient;
import com.mongodb.WriteConcern;
import java.io.Closeable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.bson.types.BasicBSONList;

/**
 *
 * @author <NAME> <<EMAIL>>.
 */
public final class CollectionManager implements Closeable {

    private final MongoClient client;
    private DB db;

    //TODO: a better way to manage db connection
    protected CollectionManager(MongoClient client, String dataBase) {
        this.client = client;
        if (dataBase != null && !dataBase.equals("")) {
            this.db = client.getDB(dataBase);
        } else {
            this.db = client.getDB(client.getDatabaseNames().get(0));
        }
    }

    public void useDB(String dbName) {
        db = client.getDB(dbName);
    }

    public <A extends Object> long count(Class<A> collectionClass) {
        return count(collectionClass, new MongoQuery());
    }

    public <A extends Object> long count(Class<A> collectionClass, MongoQuery query) {
        long ret = 0l;
        try {
            A result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            ret = db.getCollection(collName).count(query.getQuery());
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return ret;
    }

    public <A extends Object> List<A> find(Class<A> collectionClass) {
        return find(collectionClass, new MongoQuery());
    }

    public <A extends Object> List<A> find(Class<A> collectionClass, MongoQuery query) {
        List<A> resultSet = new ArrayList<>();
        DBCursor cursor = null;
        try {
            A obj = collectionClass.newInstance();
            String collName = reflectAnnotation(obj);
            cursor = db.getCollection(collName).find(query.getQuery(), query.getConstraits());
            if (query.getSkip() > 0) {
                cursor = cursor.skip(query.getSkip());
            }
            if (query.getLimit() > 0) {
                cursor = cursor.limit(query.getLimit());
            }
            while (cursor.hasNext()) {
                DBObject objDB = cursor.next();
                fillFields(obj, objDB);
                resultSet.add(obj);
                obj = collectionClass.newInstance();
            }
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            cursor.close();
        }
        return resultSet;
    }

    private <A extends Object> void fillFields(A obj, DBObject objDB) throws IllegalAccessException, IllegalArgumentException, SecurityException, InstantiationException {
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field f : fields) {
            f.setAccessible(true);
            String fieldName = f.getName();
            Object fieldContent = objDB.get(fieldName);
            if (fieldContent instanceof BasicBSONList) {
                Class<?> fieldArgClass = null;
                ParameterizedType genericFieldType = (ParameterizedType) f.getGenericType();
                Type[] fieldArgTypes = genericFieldType.getActualTypeArguments();
                for (Type fieldArgType : fieldArgTypes) {
                    fieldArgClass = (Class<?>) fieldArgType;
                }
                List<Object> list = new ArrayList<>();
                boolean isInternal = f.isAnnotationPresent(Internal.class);
                for (Object item : (BasicBSONList) fieldContent) {
                    if (isInternal) {
                        Object t = fieldArgClass.newInstance();
                        fillFields(t, (DBObject) item);
                        list.add(t);
                    } else {
                        list.add(item);
                    }
                }
                f.set(obj, list);
            } else if (fieldContent != null && f.isAnnotationPresent(ObjectId.class)) {
                f.set(obj, ((BasicDBObject) fieldContent).getString("_id"));
            } else if (fieldContent != null && f.isAnnotationPresent(Reference.class)) {
                f.set(obj, findById(f.getType(), ((org.bson.types.ObjectId) fieldContent).toString()));
            } else if (fieldContent == null && f.getType().isPrimitive()) {

            } else {
                f.set(obj, fieldContent);

            }
        }
    }

    public <A extends Object> A findOne(Class<A> collectionClass) {
        A result = null;
        try {
            result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            DBObject obj = db.getCollection(collName).findOne();
            if (obj == null) {
                return null;
            }
            fillFields(result, obj);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public <A extends Object> A findOne(Class<A> collectionClass, MongoQuery query) {
        A result = null;
        try {
            result = collectionClass.newInstance();
            String collName = reflectAnnotation(result);
            DBObject obj = db.getCollection(collName).findOne(query.getQuery(), query.getConstraits());
            if (obj == null) {
                return null;
            }
            fillFields(result, obj);
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | InstantiationException ex) {
            Logger.getLogger(CollectionManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    public <A extends Object> A findById(Class<A> collectionClass, String id) {
        return findOne(collectionClass, new MongoQuery("_id", id));
    }

    public void remove(Object document) {
        try {
            BasicDBObject obj = fillDBObject(document);
            String collName = reflectAnnotation(document);
            db.getCollection(collName).remove(obj);
{'fraction_non_alphanumeric': 0.10411013303329142, 'fraction_numerical': 0.0015884572109338805, 'mean_word_length': 2.477560414269275, 'pattern_counts': {'":': 0, '<': 59, '<?xml version=': 0, '>': 63, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4553640', 'n_tokens_mistral': 3936, 'n_tokens_neox': 3818, 'n_words': 976}