Example usage for com.mongodb BasicDBList get

List of usage examples for com.mongodb BasicDBList get

Introduction

In this page you can find the example usage for com.mongodb BasicDBList get.

Prototype

public Object get(final String key) 

Source Link

Document

Gets a value at an index.

Usage

From source file:com.ikanow.infinit.e.api.knowledge.processing.ScoringUtils_MultiCommunity.java

License:Open Source License

@SuppressWarnings("unchecked")
private static <T> HashSet<T> combineElements(HashSet<T> combinorSet, TypeErasureWorkaround.Type type,
        BasicDBList masterEls, T masterEl, TempDocBucket slave, BasicDBList slaveEls, T slaveEl) {
    int nSlaveEls = 0;
    if (null == slaveEl) {
        slaveEl = ((nSlaveEls = slaveEls.size()) > 0) ? (T) slaveEls.get(0) : null;
    }//from w ww .ja  v a 2  s  .co  m
    if ((null == combinorSet) && (null == slave.dupList) && (masterEls.size() < 2)) { // most of the time, only combining 2 objects 
        //DEBUG PRINT:
        //System.out.println("community_combineDuplicateDocs.combineElements#1: " + slaveEl.toString() + " vs " +  masterEl.toString());

        if (null != slaveEl) {
            if ((masterEl == null) || !slaveEl.equals(masterEl)) {
                masterEls.add(slaveEl);
            }
            if (nSlaveEls > 1) { // (pretty inelegant way of doing this never mind, it's only in 2 places)
                for (int i = 1; i < nSlaveEls; ++i) {
                    slaveEl = (T) slaveEls.get(i);
                    if ((masterEl == null) || !slaveEl.equals(masterEl)) {
                        masterEls.add(slaveEl);
                    }
                }
            } //TESTED
        }
    } //TESTED
    else { // Slower version, needed because >1 duplicate so it gets a bit messy...
        if (null == combinorSet) {
            combinorSet = (HashSet<T>) TypeErasureWorkaround.newSet(type);
            combinorSet.add(masterEl);
            int nMasterEls = masterEls.size();
            for (int i = 1; i < nMasterEls; ++i) {
                combinorSet.add((T) masterEls.get(i));
            }
        } //TESTED
        combinorSet.add(slaveEl);
        if (nSlaveEls > 1) { // (pretty inelegant way of doing this never mind, it's only in 2 places)
            for (int i = 1; i < nSlaveEls; ++i) {
                combinorSet.add((T) slaveEls.get(i));
            }
        } //TESTED
          //DEBUG PRINT:
          //System.out.println("community_combineDuplicateDocs.combineElements#2: " + slaveEl.toString() + " vs " +  masterEl.toString());
    } //TESTED      
    return combinorSet;
}

From source file:com.ikanow.infinit.e.api.knowledge.SearchHandler.java

License:Open Source License

/**
 * Performs a reverse geolookup, takes a lat/lon and returns a list of nearby
 * locations/*from  w w w .j  a  v a  2  s.c  om*/
 * 
 * @param latitude
 * @param longitude
 * @return
 */
private List<SearchSuggestPojo> reverseGeoLookup(Double latitude, Double longitude) {
    List<SearchSuggestPojo> locations = null;

    BasicDBList results = runGeoNear(latitude, longitude);

    if (results != null) {
        locations = new ArrayList<SearchSuggestPojo>();
        if (results.size() > 0) {
            for (int i = 0; i < 10 && i < results.size(); i++) {
                BasicDBObject result = (BasicDBObject) results.get(i);
                Double distance = result.getDouble("dis");
                BasicDBObject obj = (BasicDBObject) result.get("obj");
                locations.add(buildLocation(obj, distance));
            }
        }
    }
    return locations;
}

From source file:com.ikanow.infinit.e.core.mapreduce.HadoopJobRunner.java

License:Open Source License

private String getQueryOrProcessing(String query, QuerySpec querySpec) {
    if (query.equals("") || query.equals("null") || query == null)
        query = "{}";
    DBObject dbo = (DBObject) com.mongodb.util.JSON.parse(query);
    try {//from www  . j av  a  2  s  . c o  m
        BasicDBList dbl = (BasicDBList) dbo;
        //is a list
        if (querySpec == QuerySpec.QUERY) {
            return dbl.get(0).toString();
        } else if (querySpec == QuerySpec.POSTPROC) {
            if (dbl.size() > 1) {
                if (null == dbl.get(1)) // (only query and fields are specified) 
                    return null;
                else
                    return dbl.get(1).toString();
            } else
                return null;
        } else if (querySpec == QuerySpec.INPUTFIELDS) {
            if (dbl.size() > 2)
                return dbl.get(2).toString();
            else
                return null;
        } else
            return null;
    } catch (Exception ex) {
        try {
            //is just a an object
            if (querySpec == QuerySpec.QUERY)
                return dbo.toString();
            else
                return null;
        } catch (Exception e) {
            if (querySpec == QuerySpec.QUERY)
                return "{}";
            else
                return null;
        }
    }
}

From source file:com.ikanow.infinit.e.processing.custom.utils.InfiniteHadoopUtils.java

License:Open Source License

public static String getQueryOrProcessing(String query, QuerySpec querySpec) {
    if (query.equals("") || query.equals("null") || query == null)
        query = "{}";
    DBObject dbo = null;/*from   ww  w . j a v a2 s.  c o m*/
    try {
        dbo = (DBObject) com.mongodb.util.JSON.parse(query);
        BasicDBList dbl = (BasicDBList) dbo;
        //is a list
        if (querySpec == QuerySpec.QUERY) {
            return dbl.get(0).toString();
        } else if (querySpec == QuerySpec.POSTPROC) {
            if (dbl.size() > 1) {
                if (null == dbl.get(1)) // (only query and fields are specified) 
                    return null;
                else
                    return dbl.get(1).toString();
            } else
                return null;
        } else if (querySpec == QuerySpec.INPUTFIELDS) {
            if (dbl.size() > 2)
                return dbl.get(2).toString();
            else
                return null;
        } else
            return null;
    } catch (Exception ex) {
        try {
            //is just a an object
            if (querySpec == QuerySpec.QUERY)
                return dbo.toString();
            else if (querySpec == QuerySpec.INPUTFIELDS)
                return ((BasicDBObject) dbo.get("$fields")).toString();
            else if (querySpec == QuerySpec.POSTPROC)
                return ((BasicDBObject) dbo.get("$output")).toString();
            else
                return null;
        } catch (Exception e) // (malformed query gets you here)
        {
            if (querySpec == QuerySpec.QUERY)
                throw new RuntimeException("Malformed query: " + query);
            else
                return null;
        }
    }
}

From source file:com.impetus.client.mongodb.DocumentObjectMapper.java

License:Apache License

/**
 * Setter for column value, by default converted from string value, in case
 * of map it is automatically converted into map using BasicDBObject.
 * //  w w w  .j  a  v  a2  s.co  m
 * @param document
 *            mongo document
 * @param entityObject
 *            searched entity.
 * @param column
 *            column field.
 */
static void setFieldValue(DBObject document, Object entityObject, Attribute column, boolean isLob) {
    Object value = null;

    if (document != null) {
        value = isLob
                ? ((DBObject) document.get("metadata")).get(((AbstractAttribute) column).getJPAColumnName())
                : document.get(((AbstractAttribute) column).getJPAColumnName());
    }
    if (value != null) {
        Class javaType = column.getJavaType();
        try {
            switch (AttributeType.getType(javaType)) {
            case MAP:
                PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),
                        ((BasicDBObject) value).toMap());
                break;
            case SET:
                List collectionValues = Arrays.asList(((BasicDBList) value).toArray());
                PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),
                        new HashSet(collectionValues));
                break;
            case LIST:
                PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(),
                        Arrays.asList(((BasicDBList) value).toArray()));
                break;
            case POINT:

                BasicDBList list = (BasicDBList) value;

                Object xObj = list.get(0);
                Object yObj = list.get(1);

                if (xObj != null && yObj != null) {
                    try {
                        double x = Double.parseDouble(xObj.toString());
                        double y = Double.parseDouble(yObj.toString());

                        Point point = new Point(x, y);
                        PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), point);
                    } catch (NumberFormatException e) {
                        log.error(
                                "Error while reading geolocation data for column {} ; Reason - possible corrupt data, Caused by : .",
                                column, e);
                        throw new EntityReaderException("Error while reading geolocation data for column "
                                + column + "; Reason - possible corrupt data.", e);
                    }
                }
                break;
            case ENUM:
                EnumAccessor accessor = new EnumAccessor();
                value = accessor.fromString(javaType, value.toString());
                PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), value);
                break;
            case PRIMITIVE:
                value = MongoDBUtils.populateValue(value, value.getClass());
                value = MongoDBUtils.getTranslatedObject(value, value.getClass(), javaType);
                PropertyAccessorHelper.set(entityObject, (Field) column.getJavaMember(), value);
                break;
            }
        } catch (PropertyAccessException paex) {
            log.error("Error while setting column {} value, caused by : .",
                    ((AbstractAttribute) column).getJPAColumnName(), paex);
            throw new PersistenceException(paex);
        }
    }
}

From source file:com.impetus.kundera.mongodb.MongoDBDataHandler.java

License:Apache License

public Object getEntityFromDocument(EntityManagerImpl em, Class<?> entityClass, EntityMetadata m,
        DBObject document) {/*from   w  w w .  j  a  va 2s . c o  m*/
    Object entity = null;
    try {
        entity = entityClass.newInstance();

        //Populate entity columns
        List<Column> columns = m.getColumnsAsList();
        for (Column column : columns) {
            PropertyAccessorHelper.set(entity, column.getField(), document.get(column.getName()));
        }

        //Populate embedded relationship object
        List<Relation> relations = m.getRelations();

        for (Relation relation : relations) {
            Class<?> embeddedEntityClass = relation.getTargetEntity(); //Embedded entity class
            Field embeddedPropertyField = relation.getProperty(); //Mapped to this property               
            boolean optional = relation.isOptional(); // Is it optional? TODO: Where to use this?                           

            EntityMetadata relMetadata = em.getMetadataManager().getEntityMetadata(embeddedEntityClass);
            relMetadata.addColumn(relMetadata.getIdColumn().getName(), relMetadata.getIdColumn()); //Add PK column

            Object embeddedObject = document.get(embeddedPropertyField.getName());

            if (embeddedObject != null) {
                if (relation.isUnary()) {
                    BasicDBObject relDBObj = (BasicDBObject) embeddedObject;
                    Object embeddedEntity = new MongoDBDataHandler().getEntityFromDocument(em,
                            embeddedEntityClass, relMetadata, relDBObj);
                    PropertyAccessorHelper.set(entity, embeddedPropertyField, embeddedEntity);
                } else if (relation.isCollection()) {
                    BasicDBList relList = (BasicDBList) embeddedObject; //List of embedded objects

                    Collection<Object> embeddedEntities = null; //Collection of embedded entities
                    if (relation.getPropertyType().equals(Set.class)) {
                        embeddedEntities = new HashSet<Object>();
                    } else if (relation.getPropertyType().equals(List.class)) {
                        embeddedEntities = new ArrayList<Object>();
                    }

                    for (int i = 0; i < relList.size(); i++) {
                        BasicDBObject relObj = (BasicDBObject) relList.get(i);
                        Object embeddedEntity = new MongoDBDataHandler().getEntityFromDocument(em,
                                embeddedEntityClass, relMetadata, relObj);
                        embeddedEntities.add(embeddedEntity);
                    }

                    PropertyAccessorHelper.set(entity, embeddedPropertyField, embeddedEntities);
                }
            }

        }

    } catch (InstantiationException e) {
        log.error("Error while instantiating " + entityClass + ". Details:" + e.getMessage());
        return entity;
    } catch (IllegalAccessException e) {
        log.error("Error while Getting entity from Document. Details:" + e.getMessage());
        return entity;
    } catch (PropertyAccessException e) {
        log.error("Error while Getting entity from Document. Details:" + e.getMessage());
        return entity;
    }
    return entity;
}

From source file:com.jaspersoft.mongodb.importer.MongoDbSimpleImporter.java

License:Open Source License

private void populate(MongoDbConnection connection, String collectionName, Resource scriptResource)
        throws JRException {
    DBCollection collection = null;// ww  w  . j av  a  2  s . co m
    DB mongoDatabase = null;
    try {
        mongoDatabase = connection.getMongoDatabase();
        if (!mongoDatabase.collectionExists(collectionName)) {
            logger.info("Collection \"" + collectionName + "\" doesn't exist");
            DBObject options = new BasicDBObject("capped", false);
            collection = mongoDatabase.createCollection(collectionName, options);
        } else {
            logger.info("Collection \"" + collectionName + "\" exists");
            collection = mongoDatabase.getCollectionFromString(collectionName);
            collection.drop();
            logger.info("Collection \"" + collectionName + "\" was cleaned up");
        }
    } catch (MongoException e) {
        logger.error(e);
    }

    if (mongoDatabase == null) {
        throw new JRException(
                "Failed connection to mongoDB database: " + connection.getMongoURIObject().getDatabase());
    }

    FileInputStream fileInputStream = null;
    InputStreamReader inputStreamReader = null;
    BufferedReader reader = null;
    try {
        inputStreamReader = new InputStreamReader(scriptResource.getInputStream());
        reader = new BufferedReader(inputStreamReader);
        StringBuilder stringBuilder = new StringBuilder();
        String currentLine;
        while ((currentLine = reader.readLine()) != null) {
            stringBuilder.append(currentLine);
        }
        Object parseResult = JSON.parse(stringBuilder.toString());
        if (!(parseResult instanceof BasicDBList)) {
            throw new JRException(
                    "Unsupported type: " + parseResult.getClass().getName() + ". It must be a list");
        }
        BasicDBList list = (BasicDBList) parseResult;
        List<DBObject> objectsList = new ArrayList<DBObject>();
        for (int index = 0; index < list.size(); index++) {
            objectsList.add((DBObject) list.get(index));
        }
        collection.insert(objectsList);
        logger.info("Collection count: " + collection.count() + "\nSuccessfully populated collection: "
                + collectionName);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
    } catch (IOException e) {
        logger.error(e);
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
        if (inputStreamReader != null) {
            try {
                inputStreamReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.joyfulmongo.db.javadriver.JFDBUtil.java

License:Apache License

public static JSONArray toJSONArray(BasicDBList list) {
    JSONArray array = new JSONArray();

    for (int i = 0; i < list.size(); i++) {
        Object o = list.get(i);
        if (o instanceof BasicDBList) {
            JSONArray subarray = toJSONArray((BasicDBList) o);
            array.put(subarray);//from ww w . ja v  a  2 s.c o m
        } else if (o instanceof DBObject) {
            JSONObject json = toJSONObject((DBObject) o);
            array.put(json);
        } else {
            array.put(o);
        }
    }

    return array;
}

From source file:com.linuxbox.enkive.message.search.mongodb.MongoMessageSearchService.java

License:Open Source License

protected DBObject buildQueryObject(Map<String, String> fields)
        throws MessageSearchException, EmptySearchResultsException {
    BasicDBList conjunctionList = new BasicDBList();

    for (MongoMessageQueryBuilder queryBuilder : queryBuilders) {
        DBObject query = queryBuilder.buildQueryPortion(fields);
        if (null != query) {
            conjunctionList.add(query);// w  ww . j  a va  2 s .  c o m
        }
    }

    DBObject result;

    if (conjunctionList.isEmpty()) {
        throw new EmptySearchResultsException("No understandable search terms specified.");
    } else if (conjunctionList.size() == 1) {
        result = (DBObject) conjunctionList.get(0);
    } else {
        result = new BasicDBObject();
        result.put("$and", conjunctionList);
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("MongoDB message search query is: " + result);
    }

    return result;
}

From source file:com.mongodash.dao.mapper.SettingsDBObjectMapper.java

@Override
public Settings mapDBObject(BasicDBObject object) {
    Settings settings = null;//from   w ww  .j  a  v  a2  s  . co m
    String _id = object.getString(Config.COMMON_FIELDS._id.name());
    if (SETTINGS_KEY.email.name().equals(_id)) {
        settings = new EmailSettings();
        if (object != null) {
            ((EmailSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((EmailSettings) settings).setServer(object.getString("server"));
            ((EmailSettings) settings).setPort(object.getString("port"));
            ((EmailSettings) settings).setSender(object.getString("sender"));
            if (object.containsField("username") && object.containsField("password")) {
                ((EmailSettings) settings).setUsername(object.getString("username"));
                ((EmailSettings) settings).setPassword(PasswordUtil.decrypt(object.getString("password")));
            }
            ((EmailSettings) settings).setSsl(object.getBoolean("ssl"));
        }
    } else if (SETTINGS_KEY.ldap.name().equals(_id)) {
        settings = new LdapSettings();
        if (object != null) {
            ((LdapSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((LdapSettings) settings).setHost(object.getString("host"));
            ((LdapSettings) settings).setPort(object.getString("port"));
            ((LdapSettings) settings).setAdminDn(object.getString("adminDn"));
            ((LdapSettings) settings).setAdminPassword(object.getString("adminPassword"));
            ((LdapSettings) settings).setBaseDn(object.getString("baseDn"));
            ((LdapSettings) settings).setLoginAttribute(object.getString("loginAttr"));
            ((LdapSettings) settings).setSecure(object.getBoolean("secure"));
        }
    } else if (SETTINGS_KEY.alerts.name().equals(_id)) {
        settings = new AlertSettings();
        if (object != null) {
            ((AlertSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((AlertSettings) settings).setEmailSubject(object.getString("emailSubject"));
            ((AlertSettings) settings).setEmailRecipients(object.getString("emailRecipients"));
        }
    } else if (SETTINGS_KEY.notifications.name().equals(_id)) {
        settings = new NotificationSettings();
        if (object != null) {
            ((NotificationSettings) settings).setEnabled(object.getBoolean("enabled"));
            ((NotificationSettings) settings).setEmailEnabled(object.getBoolean("emailEnabled"));
            ((NotificationSettings) settings).setEmailSubject(object.getString("emailSubject"));
            ((NotificationSettings) settings).setEmailRecipients(object.getString("emailRecipients"));
            if (object.containsField("enabledNotifications")) {
                BasicDBList list = (BasicDBList) object.get("enabledNotifications");
                List<String> enabledNotifications = new ArrayList<String>();
                for (int i = 0; i < list.size(); i++) {
                    enabledNotifications.add((String) list.get(i));
                }
                ((NotificationSettings) settings).setEnabledNotifications(enabledNotifications);
            }
        }
    } else if (SETTINGS_KEY.licenseKey.name().equals(_id)) {
        settings = new LicenseKeySettings();
        if (object != null) {
            ((LicenseKeySettings) settings).setPrivateKey(object.getString("privateKey"));
            ((LicenseKeySettings) settings).setPublicKey(object.getString("publicKey"));
        }
    }
    return settings;
}