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:org.restheart.handlers.schema.JsonSchemaTransformer.java

License:Open Source License

@Override
public void tranform(HttpServerExchange exchange, RequestContext context, final DBObject contentToTransform,
        DBObject args) {/*from ww w.  j  av  a 2s .c  o m*/
    if (context.getType() == RequestContext.TYPE.SCHEMA) {
        if (context.getMethod() == RequestContext.METHOD.GET) {
            unescapeSchema(context.getResponseContent());
        } else if (context.getMethod() == RequestContext.METHOD.PUT
                || context.getMethod() == RequestContext.METHOD.PATCH) {

            // generate id as specs mandates
            SchemaStoreURL uri = new SchemaStoreURL(context.getDBName(), context.getDocumentId());

            context.getContent().put("id", uri.toString());

            // escape all $ prefixed keys
            escapeSchema(contentToTransform);

            // add (overwrite) $schema field
            contentToTransform.put("_$schema", "http://json-schema.org/draft-04/schema#");
        }
    } else if (context.getType() == RequestContext.TYPE.SCHEMA_STORE) {
        if (context.getMethod() == RequestContext.METHOD.POST) {
            // generate id as specs mandates
            Object schemaId;

            if (context.getContent().get("_id") == null) {
                schemaId = new ObjectId();
                context.getContent().put("id", schemaId);
            } else {
                schemaId = context.getContent().get("_id");
            }

            SchemaStoreURL uri = new SchemaStoreURL(context.getDBName(), schemaId);

            context.getContent().put("id", uri.toString());

            // escape all $ prefixed keys
            escapeSchema(contentToTransform);

            // add (overwrite) $schema field
            contentToTransform.put("_$schema", "http://json-schema.org/draft-04/schema#");
        } else if (context.getMethod() == RequestContext.METHOD.GET) {
            // apply transformation on embedded schemas

            BasicDBObject _embedded = (BasicDBObject) context.getResponseContent().get("_embedded");

            if (_embedded != null) {
                // execute the logic on children documents
                BasicDBList docs = (BasicDBList) _embedded.get("rh:schema");

                if (docs != null) {
                    docs.keySet().stream().map((k) -> (DBObject) docs.get(k)).forEach((doc) -> {
                        unescapeSchema(doc);
                    });
                }
            }
        }
    }
}

From source file:org.sdsai.dsds.mongo.MongoUtils.java

License:Open Source License

public static <T> T fromDBObjectHelper(DBObject dbo, final String fieldName, final Class<T> returnType)
        throws Exception {
    logger.debug("Converting {}:{}", fieldName, returnType.getName());

    //logger.debug("-->{}", dbo);

    if (returnType.isPrimitive()) {
        @SuppressWarnings("unchecked")
        final T t = (T) getPrimitive((BasicDBObject) dbo, fieldName, returnType);
        return t;
    }//from ww w .j a  v a 2 s .  c o  m

    if (isValueOfAble(returnType)) {
        @SuppressWarnings("unchecked")
        final T t = (T) returnType.getMethod("valueOf", String.class).invoke(null,
                dbo.get(fieldName).toString());
        return t;
    }

    if (returnType.isArray()) {
        final BasicDBList dblist = (BasicDBList) dbo.get("list");
        // FIXME

        return null;
    }

    if (Collection.class.isAssignableFrom(returnType)) {
        dbo = (DBObject) dbo.get(fieldName);
        final BasicDBList dblist = (BasicDBList) dbo.get("list");

        @SuppressWarnings("unchecked")
        final Collection<Object> c = (Collection<Object>) objectFactory
                .newInstance(dbo.get("Class").toString());

        for (int i = 0; i < dblist.size(); i++) {
            Object tmpo = dblist.get(i);

            if (tmpo instanceof DBObject)
                tmpo = fromDBObjectHelper((DBObject) tmpo);
            ;

            c.add(tmpo);
        }

        @SuppressWarnings("unchecked")
        final T t = (T) c;
        return t;
    }

    if (Map.class.isAssignableFrom(returnType)) {
        dbo = (DBObject) dbo.get(fieldName);
        final BasicDBObject dbmap = (BasicDBObject) dbo.get("map");

        @SuppressWarnings("unchecked")
        final Map<String, Object> map = (Map<String, Object>) objectFactory
                .newInstance(dbo.get("Class").toString());

        for (final String tmpFieldName : dbmap.keySet()) {
            Object tmpo = dbmap.get(tmpFieldName);

            if (tmpo instanceof DBObject)
                tmpo = fromDBObjectHelper((DBObject) tmpo);

            map.put(fieldName, tmpo);
        }

        @SuppressWarnings("unchecked")
        final T t = (T) map;
        return t;
    }

    // user object.

    @SuppressWarnings("unchecked")
    final T t = (T) fromDBObjectHelper((DBObject) dbo.get(fieldName));
    return t;
}

From source file:org.sipfoundry.commons.userdb.ValidUsers.java

License:Open Source License

/**
 * Loading all users into memory is an extremely expensive call for large systems (10K-50K user system).
 * Consider refactoring your code to not call this method.
 *
 * @return/*from   w w  w  .j a  v  a  2s  .  co m*/
 */
public List<User> getValidUsers() {
    List<User> users = new ArrayList<User>();
    try {
        DBCursor cursor = getEntityCollection().find(QueryBuilder.start(VALID_USER).is(Boolean.TRUE).get());
        Iterator<DBObject> objects = cursor.iterator();
        while (objects.hasNext()) {
            DBObject validUser = objects.next();
            if (!validUser.get(ID).toString().startsWith("User")) {
                BasicDBList aliasesObj = (BasicDBList) validUser.get(ALIASES);
                if (aliasesObj != null) {
                    for (int i = 0; i < aliasesObj.size(); i++) {
                        DBObject aliasObj = (DBObject) aliasesObj.get(i);
                        users.add(extractValidUserFromAlias(aliasObj));
                    }
                }
            } else {
                users.add(extractValidUser(validUser));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return users;
}

From source file:org.sipfoundry.commons.userdb.ValidUsers.java

License:Open Source License

/**
 * See if a given user_name is valid (aka it can be dialed and reach a user)
 *
 * @param userNname//ww w  .  j  a  v a 2  s . c om
 *
 * @return user found or null
 */
public User getUser(String userName) {
    if (userName == null) {
        return null;
    }
    DBObject queryUserName = QueryBuilder.start(VALID_USER).is(Boolean.TRUE).and(UID).is(userName).get();
    DBObject result = getEntityCollection().findOne(queryUserName);
    if (result != null) {
        return extractValidUser(result);
    }

    // check aliases
    BasicDBObject elemMatch = new BasicDBObject();
    elemMatch.put(ALIAS_ID, userName);
    BasicDBObject alias = new BasicDBObject();
    alias.put("$elemMatch", elemMatch);
    BasicDBObject queryAls = new BasicDBObject();
    queryAls.put(ALIASES, alias);
    queryAls.put(VALID_USER, Boolean.TRUE);
    DBObject aliasResult = getEntityCollection().findOne(queryAls);
    if (aliasResult == null) {
        return null;
    }
    if (!aliasResult.get(ID).toString().startsWith("User")) {
        BasicDBList aliases = (BasicDBList) aliasResult.get(ALIASES);
        for (int i = 0; i < aliases.size(); i++) {
            DBObject aliasObj = (DBObject) aliases.get(i);
            if (getStringValue(aliasObj, ALIAS_ID).equals(userName)) {
                return extractValidUserFromAlias(aliasObj);
            }
        }
    }
    return extractValidUser(aliasResult);
}

From source file:org.sipfoundry.commons.userdb.ValidUsers.java

License:Open Source License

public List<String> getImGroupnamesForUser(String jid) {
    BasicDBObject query = new BasicDBObject();
    query.put(IM_ENABLED, true);//ww w .jav a2s  .c om
    query.put(IM_ID, jid);
    List<String> names = new ArrayList<String>();
    DBObject user = getEntityCollection().findOne(query);
    if (user != null) {
        BasicDBList groupList = (BasicDBList) user.get(GROUPS);
        for (int i = 0; i < groupList.size(); i++) {
            names.add((String) groupList.get(i));
        }
    }
    return names;
}

From source file:org.sipfoundry.commons.userdb.ValidUsers.java

License:Open Source License

private static User extractUser(DBObject obj) {
    if (obj == null) {
        return null;
    }//from w  w w .j  a va2s .  co  m

    User user = new User();
    user.setSysId(getStringValue(obj, ID));
    user.setIdentity(getStringValue(obj, IDENTITY));
    user.setUserName(getStringValue(obj, UID));
    user.setDisplayName(getStringValue(obj, DISPLAY_NAME));
    user.setUri(getStringValue(obj, CONTACT));
    user.setPasstoken(getStringValue(obj, HASHED_PASSTOKEN));
    user.setPintoken(getStringValue(obj, PINTOKEN));
    user.setVoicemailPintoken(getStringValue(obj, VOICEMAIL_PINTOKEN));

    BasicDBList permissions = (BasicDBList) obj.get(PERMISSIONS);
    if (permissions != null) {
        user.setInDirectory(permissions.contains(IMDB_PERM_AA));
        user.setHasVoicemail(permissions.contains(IMDB_PERM_VOICEMAIL));
        user.setCanRecordPrompts(permissions.contains(IMDB_PERM_RECPROMPTS));
        user.setCanTuiChangePin(permissions.contains(IMDB_PERM_TUICHANGEPIN));
    }

    user.setUserBusyPrompt(Boolean.valueOf(getStringValue(obj, USERBUSYPROMPT)));
    user.setMoh(getStringValue(obj, MOH));
    user.setVoicemailTui(getStringValue(obj, VOICEMAILTUI));
    user.setEmailAddress(getStringValue(obj, EMAIL));
    if (obj.keySet().contains(NOTIFICATION)) {
        user.setEmailFormat(getStringValue(obj, NOTIFICATION));
    }
    user.setAttachAudioToEmail(Boolean.valueOf(getStringValue(obj, ATTACH_AUDIO)));

    user.setAltEmailAddress(getStringValue(obj, ALT_EMAIL));
    if (obj.keySet().contains(ALT_NOTIFICATION)) {
        user.setAltEmailFormat(getStringValue(obj, ALT_NOTIFICATION));
    }
    user.setAltAttachAudioToEmail(Boolean.valueOf(getStringValue(obj, ALT_ATTACH_AUDIO)));

    BasicDBList aliasesObj = (BasicDBList) obj.get(ALIASES);
    if (aliasesObj != null) {
        Vector<String> aliases = new Vector<String>();
        for (int i = 0; i < aliasesObj.size(); i++) {
            DBObject aliasObj = (DBObject) aliasesObj.get(i);
            if (aliasObj.get(RELATION).toString().equals(ALIAS)) {
                aliases.add(aliasObj.get(ALIAS_ID).toString());
            }
        }
        user.setAliases(aliases);
    }

    if (obj.keySet().contains(SYNC)) {
        ImapInfo imapInfo = new ImapInfo();
        imapInfo.setSynchronize(Boolean.valueOf(getStringValue(obj, SYNC)));
        imapInfo.setHost(getStringValue(obj, HOST));
        imapInfo.setPort(getStringValue(obj, PORT));
        imapInfo.setUseTLS(Boolean.valueOf(getStringValue(obj, TLS)));
        imapInfo.setAccount(getStringValue(obj, ACCOUNT));
        imapInfo.setPassword(getStringValue(obj, PASSWD));
        user.setImapInfo(imapInfo);
        if (imapInfo.isSynchronize()) {
            user.setEmailFormat(EmailFormats.FORMAT_IMAP);
            user.setAttachAudioToEmail(true);
        }
        // // If account isn't set, use the e-mail username
        if (imapInfo.getAccount() == null || imapInfo.getAccount().length() == 0) {
            if (user.getEmailAddress() != null) {
                imapInfo.setAccount(user.getEmailAddress().split("@")[0]);
            }
        }
    }

    // contact info related data
    user.setCellNum(getStringValue(obj, CELL_PHONE_NUMBER));
    user.setHomeNum(getStringValue(obj, HOME_PHONE_NUMBER));
    user.setConfEntryIM(getStringValue(obj, CONF_ENTRY_IM));
    user.setConfExitIM(getStringValue(obj, CONF_EXIT_IM));
    user.setVMEntryIM(getStringValue(obj, LEAVE_MESSAGE_BEGIN_IM));
    user.setVMExitIM(getStringValue(obj, LEAVE_MESSAGE_END_IM));
    user.setCallIM(getStringValue(obj, CALL_IM));
    user.setCallFromAnyIM(getStringValue(obj, CALL_FROM_ANY_IM));
    user.setImEnabled(Boolean.valueOf(getStringValue(obj, IM_ENABLED)));
    user.setJid(getStringValue(obj, IM_ID));
    user.setAltJid(getStringValue(obj, ALT_IM_ID));
    user.setImDisplayName(getStringValue(obj, IM_DISPLAY_NAME));
    user.setOnthePhoneMessage(getStringValue(obj, IM_ON_THE_PHONE_MESSAGE));
    user.setAdvertiseOnCallStatus(Boolean.valueOf(getStringValue(obj, IM_ADVERTISE_ON_CALL_STATUS)));
    user.setShowOnCallDetails(Boolean.valueOf(getStringValue(obj, IM_SHOW_ON_CALL_DETAILS)));
    user.setCompanyName(getStringValue(obj, COMPANY_NAME));
    user.setJobDepartment(getStringValue(obj, JOB_DEPT));
    user.setJobTitle(getStringValue(obj, JOB_TITLE));
    user.setFaxNumber(getStringValue(obj, FAX_NUMBER));

    // office details
    user.setOfficeStreet(getStringValue(obj, OFFICE_STREET));
    user.setOfficeCity(getStringValue(obj, OFFICE_CITY));
    user.setOfficeState(getStringValue(obj, OFFICE_STATE));
    user.setOfficeZip(getStringValue(obj, OFFICE_ZIP));
    user.setOfficeCountry(getStringValue(obj, OFFICE_COUNTRY));

    // home details
    user.setHomeCity(getStringValue(obj, HOME_CITY));
    user.setHomeState(getStringValue(obj, HOME_STATE));
    user.setHomeZip(getStringValue(obj, HOME_ZIP));
    user.setHomeCountry(getStringValue(obj, HOME_COUNTRY));
    user.setHomeStreet(getStringValue(obj, HOME_STREET));

    user.setAvatar(getStringValue(obj, AVATAR));

    // active greeting related data
    if (obj.keySet().contains(ACTIVEGREETING)) {
        user.setActiveGreeting(getStringValue(obj, ACTIVEGREETING));
    }

    user.setPlayDefaultVmOption(Boolean.valueOf(getStringValue(obj, PLAY_DEFAULT_VM)));

    // personal attendant related data
    if (obj.keySet().contains(PERSONAL_ATT)) {
        BasicDBObject pao = (BasicDBObject) obj.get(PERSONAL_ATT);
        String operator = getStringValue(pao, OPERATOR);
        String language = getStringValue(pao, LANGUAGE);
        Map<String, String> menu = new HashMap<String, String>();
        StringBuilder validDigits = new StringBuilder(10);
        BasicDBList buttonsList = (BasicDBList) pao.get(BUTTONS);
        if (buttonsList != null) {
            for (int i = 0; i < buttonsList.size(); i++) {
                DBObject button = (DBObject) buttonsList.get(i);
                if (button != null) {
                    menu.put(getStringValue(button, DIALPAD), getStringValue(button, ITEM));
                    validDigits.append(getStringValue(button, DIALPAD));
                }
            }
        }
        user.setPersonalAttendant(new PersonalAttendant(language, operator, menu, validDigits.toString()));
    }

    // distribution lists
    if (obj.keySet().contains(DISTRIB_LISTS)) {
        Distributions distribs = new Distributions();
        BasicDBList distribList = (BasicDBList) obj.get(DISTRIB_LISTS);
        if (distribList != null) {
            for (int i = 0; i < distribList.size(); i++) {
                DBObject distrib = (DBObject) distribList.get(i);
                if (distrib != null) {
                    distribs.addList(getStringValue(distrib, DIALPAD),
                            StringUtils.split(getStringValue(distrib, ITEM), " "));
                }
            }
        }
        user.setDistributions(distribs);
    }

    if (user.isInDirectory()) {
        buildDialPatterns(user);
    }

    return user;
}

From source file:org.sipfoundry.sipxconfig.mongo.MongoReplicaSetManager.java

License:Open Source License

public void checkState() {
    try {/*ww  w  . j a v  a  2  s.c  o  m*/
        BasicBSONObject ret = MongoUtil.runCommand(m_localDb.getDb(), CHECK_COMMAND);
        boolean initialized = false;
        if (ret != null) {
            BasicDBList members = (BasicDBList) ret.get(MEMBERS);
            if (members != null) {
                BasicDBObject primary = (BasicDBObject) members.get(0);
                if (primary != null) {
                    initialized = true;
                    String host = primary.getString(HOST);
                    String expected = format(m_primaryFqdn + ':' + MongoSettings.SERVER_PORT);
                    if (!expected.equals(host)) {
                        String rename = format(RENAME_PRIMARY_COMMAND, expected);
                        MongoUtil.runCommand(m_localDb.getDb(), rename);
                    }
                }
            }
        }

        if (!initialized) {
            initialize();
        }
    } catch (Exception ex) {
        LOG.error("Failed to check replica set state!");
    }

}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

License:Apache License

@SuppressWarnings({ "unchecked" })
protected Object getValueInternal(MongoPersistentProperty prop, DBObject dbo, StandardEvaluationContext ctx,
        String spelExpr) {/* w  w  w . ja v a  2  s  .c om*/

    Object o;
    if (null != spelExpr) {
        Expression x = spelExpressionParser.parseExpression(spelExpr);
        o = x.getValue(ctx);
    } else {

        Object dbObj = dbo.get(prop.getKey());

        if (dbObj == null) {
            return null;
        }

        Class<?> propertyType = prop.getType();
        Class<?> customTarget = getCustomTarget(dbObj.getClass(), propertyType);

        if (customTarget != null) {
            return conversionService.convert(dbObj, propertyType);
        }

        if (dbObj instanceof DBRef) {
            dbObj = ((DBRef) dbObj).fetch();
        }
        if (dbObj instanceof DBObject) {
            if (prop.isMap() && dbObj instanceof DBObject) {

                // We have to find a potentially stored class to be used first.
                Class<?> toType = findTypeToBeUsed((DBObject) dbObj);
                Map<String, Object> m = new LinkedHashMap<String, Object>();

                for (Map.Entry<String, Object> entry : ((Map<String, Object>) ((DBObject) dbObj).toMap())
                        .entrySet()) {
                    if (entry.getKey().equals(CUSTOM_TYPE_KEY)) {
                        continue;
                    }
                    if (null != entry.getValue() && entry.getValue() instanceof DBObject) {
                        m.put(entry.getKey(), read((null != toType ? toType : prop.getMapValueType()),
                                (DBObject) entry.getValue()));
                    } else {
                        m.put(entry.getKey(), entry.getValue());
                    }
                }
                return m;
            } else if (prop.isArray() && dbObj instanceof BasicDBObject
                    && ((DBObject) dbObj).keySet().size() == 0) {
                // It's empty
                return Array.newInstance(prop.getComponentType(), 0);
            } else if (prop.isCollection() && dbObj instanceof BasicDBList) {
                BasicDBList dbObjList = (BasicDBList) dbObj;
                List<Object> items = new LinkedList<Object>();
                for (int i = 0; i < dbObjList.size(); i++) {
                    Object dbObjItem = dbObjList.get(i);
                    if (dbObjItem instanceof DBRef) {
                        items.add(read(prop.getComponentType(), ((DBRef) dbObjItem).fetch()));
                    } else if (dbObjItem instanceof DBObject) {
                        items.add(read(prop.getComponentType(), (DBObject) dbObjItem));
                    } else {
                        items.add(dbObjItem);
                    }
                }
                List<Object> itemsToReturn = new LinkedList<Object>();
                for (Object obj : items) {
                    itemsToReturn.add(obj);
                }
                return itemsToReturn;
            }

            Class<?> toType = findTypeToBeUsed((DBObject) dbObj);

            // It's a complex object, have to read it in
            if (toType != null) {
                dbo.removeField(CUSTOM_TYPE_KEY);
                o = read(toType, (DBObject) dbObj);
            } else {
                o = read(mappingContext.getPersistentEntity(prop.getTypeInformation()), (DBObject) dbObj);
            }
        } else {
            o = dbObj;
        }
    }
    return o;
}

From source file:org.springframework.data.document.mongodb.convert.MappingMongoConverter.java

License:Apache License

protected <T> List<?> unwrapList(BasicDBList dbList, TypeInformation<T> targetType) {
    List<Object> rootList = new LinkedList<Object>();
    for (int i = 0; i < dbList.size(); i++) {
        Object obj = dbList.get(i);
        if (obj instanceof BasicDBList) {
            rootList.add(unwrapList((BasicDBList) obj, targetType.getComponentType()));
        } else if (obj instanceof DBObject) {
            rootList.add(read(targetType, (DBObject) obj));
        } else {/*from w  ww .j  av a 2s  .  c o  m*/
            rootList.add(obj);
        }
    }
    return rootList;
}

From source file:org.springframework.data.mongodb.core.convert.CustomMappingMongoConverter.java

private Object readCollectionOrArray(TypeInformation<?> targetType, BasicDBList sourceValue, ObjectPath path) {

    Assert.notNull(targetType, "Target type must not be null!");
    Assert.notNull(path, "Object path must not be null!");

    Class<?> collectionType = targetType.getType();

    if (sourceValue.isEmpty()) {
        return getPotentiallyConvertedSimpleRead(new HashSet<Object>(), collectionType);
    }//from w ww .  ja v  a2 s. co  m

    TypeInformation<?> componentType = targetType.getComponentType();
    Class<?> rawComponentType = componentType == null ? null : componentType.getType();

    collectionType = Collection.class.isAssignableFrom(collectionType) ? collectionType : List.class;
    Collection<Object> items = targetType.getType().isArray() ? new ArrayList<Object>()
            : CollectionFactory.createCollection(collectionType, rawComponentType, sourceValue.size());

    for (int i = 0; i < sourceValue.size(); i++) {

        Object dbObjItem = sourceValue.get(i);

        if (dbObjItem instanceof DBRef) {
            //CHANGE STARTS
            if (DBRef.class.equals(rawComponentType)) {
                items.add(dbObjItem);
            } else {
                items.add(readAndConvertDBRef((DBRef) dbObjItem, componentType, path, rawComponentType));
            }
            // CHANGE ENDS
        } else if (dbObjItem instanceof DBObject) {
            items.add(read(componentType, (DBObject) dbObjItem, path));
        } else {
            items.add(getPotentiallyConvertedSimpleRead(dbObjItem, rawComponentType));
        }
    }

    return getPotentiallyConvertedSimpleRead(items, targetType.getType());
}