com.mongodb.DBCollection

Here are the examples of the java api com.mongodb.DBCollection taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

132 Examples 7

19 Source : PasswordsDbMongo.java
with GNU General Public License v2.0
from yeriomin

clreplaced PreplacedwordsDbMongo implements PreplacedwordsDbInterface {

    static private final String FIELD_EMAIL = "email";

    static private final String FIELD_PreplacedWORD = "preplacedword";

    private DBCollection collection;

    public PreplacedwordsDbMongo(Properties config) {
        String host = config.getProperty(Server.PROPERTY_MONGODB_HOST, "");
        int port = Integer.parseInt(config.getProperty(Server.PROPERTY_MONGODB_PORT, "0"));
        String username = config.getProperty(Server.PROPERTY_MONGODB_USERNAME, "");
        String preplacedword = config.getProperty(Server.PROPERTY_MONGODB_PreplacedWORD, "");
        String databaseNameStorage = config.getProperty(Server.PROPERTY_MONGODB_DB, "");
        String collectionName = config.getProperty(Server.PROPERTY_MONGODB_COLLECTION, "");
        Mongo mongo;
        try {
            mongo = new Mongo(host, port);
        } catch (UnknownHostException e) {
            Server.LOG.error("UnknownHostException: " + e.getMessage());
            return;
        }
        DB mongoDb = mongo.getDB(databaseNameStorage);
        if (!mongoDb.authenticate(username, preplacedword.toCharArray())) {
            Server.LOG.error("Failed to authenticate against db: " + databaseNameStorage);
            return;
        }
        collection = mongoDb.getCollection(collectionName);
    }

    @Override
    public String getRandomEmail() {
        List<String> emails = new ArrayList<>();
        collection.find().forEach((DBObject dbObject) -> emails.add((String) dbObject.get(FIELD_EMAIL)));
        return emails.get(new Random().nextInt(emails.size()));
    }

    @Override
    public String get(String email) {
        BasicDBObject query = new BasicDBObject(FIELD_EMAIL, email);
        DBObject object = collection.findOne(query);
        String preplacedword = null;
        if (null != object) {
            preplacedword = (String) object.get(FIELD_PreplacedWORD);
        }
        return preplacedword;
    }

    @Override
    public void put(String email, String preplacedword) {
        DBObject object = new BasicDBObject();
        object.put(FIELD_EMAIL, email);
        object.put(FIELD_PreplacedWORD, preplacedword);
        collection.insert(object);
    }
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

public Object selectVar(DBCollection collection) {
    if (null == this.count) {
        DBObject result = selectOne(collection);
        return result;
    } else {
        return getQueryCount(collection);
    }
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

public DBObject selectOne(DBCollection collection) {
    DBObject fields = getFields();
    DBObject query = getQuery();
    DBObject orderByObject = getOrderByObject();
    // 日志
    log(fields, query, orderByObject);
    if (null == fields && null == orderByObject) {
        return collection.findOne(query);
    } else if (null != fields && null == orderByObject) {
        return collection.findOne(query, fields);
    } else {
        return collection.findOne(query, fields, orderByObject);
    }
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

public DBCursor selectSet(DBCollection collection) {
    DBObject fields = getFields();
    DBObject query = getQuery();
    DBObject orderByObject = getOrderByObject();
    DBCursor cursor = null;
    // 日志
    log(fields, query, orderByObject);
    if (null != query && null == fields) {
        cursor = collection.find(query);
    } else if (null == query && null != fields) {
        cursor = collection.find(new BasicDBObject(), fields);
    } else if (null != fields && null != query) {
        cursor = collection.find(query, fields);
    } else {
        cursor = collection.find();
    }
    if (null != orderByObject) {
        cursor.sort(orderByObject);
    }
    if (null != this.limit) {
        if (null == this.limit.getOffset()) {
            cursor.limit(this.limit.getRowCount());
        } else {
            cursor.limit(this.limit.getRowCount());
            cursor.skip(this.limit.getOffset());
        }
    }
    return cursor;
}

19 Source : SelectVo.java
with GNU General Public License v3.0
from xsonorg

private long getQueryCount(DBCollection collection) {
    DBObject query = getQuery();
    if (null == query) {
        return collection.count();
    } else {
        return collection.count(query);
    }
}

19 Source : MarcMongodbClientTest.java
with GNU General Public License v3.0
from pkiraly

// @Test
public void testGetCollection() throws UnknownHostException {
    MarcMongodbClient client = new MarcMongodbClient("localhost", 27017, "sub_last_print");
    DBCollection collection = client.getCollection("marc");
    replacedertNotNull(collection);
    replacedertEquals(0, collection.count());
}

19 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * The main purpose of this sample is to demonstrate the use of a CustomStore
 * for an OAuth Provider. It is provided as-is.
 *
 * It uses a MongoDB back end.
 */
public clreplaced CustomStoreSample implements OAuthStore {

    public final static String MONGO_PROPS_FILE = "mongoDB.props";

    private String dbName = "default";

    private String dbHost = "localhost";

    private String dbUser = "user";

    private String dbPwd = "preplacedword";

    private int dbPort = 27017;

    String uid = "defaultUID";

    private DB db = null;

    private DBCollection clientCollection = null;

    private DBCollection tokenCollection = null;

    private DBCollection consentCollection = null;

    // Collection types in the database
    static String OAUTHCLIENT = "OauthClient";

    static String OAUTHTOKEN = "OauthToken";

    static String OAUTHCONSENT = "OauthConsent";

    // Keys in the database
    final static String LOOKUPKEY = "LOOKUPKEY";

    final static String UNIQUEID = "UNIQUEID";

    final static String COMPONENTID = "COMPONENTID";

    final static String TYPE = "TYPE";

    final static String SUBTYPE = "SUBTYPE";

    final static String CREATEDAT = "CREATEDAT";

    final static String LIFETIME = "LIFETIME";

    // long
    final static String EXPIRES = "EXPIRES";

    final static String TOKENSTRING = "TOKENSTRING";

    final static String CLIENTID = "CLIENTID";

    final static String USERNAME = "USERNAME";

    final static String SCOPE = "SCOPE";

    final static String REDIRECTURI = "REDIRECTURI";

    final static String STATEID = "STATEID";

    final static String EXTENDEDFIELDS = "EXTENDEDFIELDS";

    final static String PROPS = "PROPS";

    final static String RESOURCE = "RESOURCE";

    final static String PROVIDERID = "PROVIDERID";

    final static String CLIENTSECRET = "CLIENTSECRET";

    final static String DISPLAYNAME = "DISPLAYNAME";

    final static String ENABLED = "ENABLED";

    final static String METADATA = "METADATA";

    private final static int RETRY_COUNT = 3;

    public CustomStoreSample() {
        System.out.println("CustomStoreSample init");
    }

    /**
     * Simple helper method to get a connection to mongoDB.
     *
     * It is not a general recommendation for all CustomStore implementations.
     *
     * @return
     */
    private synchronized DB getDB() {
        if (db == null) {
            getDatabaseConfig();
            MongoClient mongoClient = null;
            try {
                System.out.println("CustomStoreSample connecting to the " + dbName + " database at " + dbHost + ":" + dbPort + " using table modifier " + uid);
                List<MongoCredential> credentials = Collections.emptyList();
                MongoCredential credential = MongoCredential.createCredential(dbUser, dbName, dbPwd.toCharArray());
                credentials = Collections.singletonList(credential);
                MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder().connectTimeout(30000);
                optionsBuilder.socketTimeout(10000);
                optionsBuilder.socketKeepAlive(true);
                MongoClientOptions clientOptions = optionsBuilder.build();
                mongoClient = new MongoClient(new ServerAddress(dbHost, dbPort), credentials, clientOptions);
                db = mongoClient.getDB(dbName);
                System.out.println("CustomStoreSample connected to the database");
                OAUTHCLIENT = OAUTHCLIENT + uid;
                OAUTHTOKEN = OAUTHTOKEN + uid;
                OAUTHCONSENT = OAUTHCONSENT + uid;
                // for test purposes, double check the starting state of the database
                DBCollection col = getClientCollection();
                DBCursor result = col.find();
                if (result.hasNext()) {
                    System.out.println("Database is pre-populated with clients: " + OAUTHCLIENT);
                    while (result.hasNext()) {
                        DBObject dbo = result.next();
                        System.out.println("Client: " + (String) dbo.get(PROVIDERID) + " " + (String) dbo.get(CLIENTID));
                    }
                } else {
                    System.out.println("Database is not pre-populated with clients: " + OAUTHCLIENT);
                }
            } catch (UnknownHostException e) {
                System.out.println("CustomStoreSample failed connecting to the database " + e);
                e.printStackTrace();
                throw new IllegalStateException("CustomStoreSample Database is not connected at " + dbHost + ":" + dbPort + ", cannot process requests. Failure is " + e, e);
            }
        }
        return db;
    }

    private DBCollection getClientCollection() {
        if (clientCollection == null) {
            clientCollection = getDB().getCollection(OAUTHCLIENT);
        }
        return clientCollection;
    }

    private DBCollection getTokenCollection() {
        if (tokenCollection == null) {
            tokenCollection = getDB().getCollection(OAUTHTOKEN);
        }
        return tokenCollection;
    }

    private DBCollection getConsentCollection() {
        if (consentCollection == null) {
            consentCollection = getDB().getCollection(OAUTHCONSENT);
        }
        return consentCollection;
    }

    /**
     * This helper method uses a properties file to get the database connection
     * parameters. It was done this way to support local testing of both Bell
     * and User Feature configurations.
     *
     * It is not a general recommendation for all CustomStore implementations.
     */
    private void getDatabaseConfig() {
        File f = new File(MONGO_PROPS_FILE);
        if (!f.exists()) {
            throw new IllegalStateException("CustomStoreSample Database config file " + MONGO_PROPS_FILE + " was not found. This may be normal during server startup");
        }
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charset.forName("UTF8")));
            try {
                String line;
                while ((line = br.readLine()) != null) {
                    if (line.startsWith("#") || line.trim().equals("")) {
                        continue;
                    }
                    String[] prop = line.split(":");
                    if (prop.length != 2) {
                        System.out.println("CustomStoreSample Exception key:value syntax of properties in " + MONGO_PROPS_FILE + ", line is: " + line);
                    } else {
                        if (prop[0].equals("DBNAME")) {
                            dbName = prop[1];
                        } else if (prop[0].equals("HOST")) {
                            dbHost = prop[1];
                        } else if (prop[0].equals("PWD")) {
                            dbPwd = prop[1];
                        } else if (prop[0].equals("PORT")) {
                            dbPort = Integer.parseInt(prop[1]);
                        } else if (prop[0].equals("USER")) {
                            dbUser = prop[1];
                        } else if (prop[0].equals("UID")) {
                            uid = prop[1];
                        } else {
                            System.out.println("CustomStoreSample Unexpected property in " + MONGO_PROPS_FILE + ": " + prop[0]);
                        }
                    }
                }
                System.out.println("CustomStoreSample Table mod is " + uid);
            } finally {
                br.close();
            }
        } catch (IOException e) {
            throw new IllegalStateException("Database config could not be retrieved from " + MONGO_PROPS_FILE, e);
        }
    }

    @Override
    public void create(OAuthClient oauthClient) throws OAuthStoreException {
        for (int i = 0; i < RETRY_COUNT; i++) {
            try {
                DBCollection col = getClientCollection();
                col.insert(createClientDBObjectHelper(oauthClient));
            } catch (Exception e) {
                if (i < RETRY_COUNT && isNetworkFailure(e)) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                    }
                } else {
                    throw new OAuthStoreException("Failed to process create on OAuthClient " + oauthClient.getClientId(), e);
                }
            }
        }
    }

    private BasicDBObject createClientDBObjectHelper(OAuthClient oauthClient) {
        BasicDBObject d = new BasicDBObject(CLIENTID, oauthClient.getClientId());
        d.append(PROVIDERID, oauthClient.getProviderId());
        d.append(CLIENTSECRET, oauthClient.getClientSecret());
        d.append(DISPLAYNAME, oauthClient.getDisplayName());
        d.append(ENABLED, oauthClient.isEnabled());
        d.append(METADATA, oauthClient.getClientMetadata());
        return d;
    }

    @Override
    public void create(OAuthToken oauthToken) throws OAuthStoreException {
        try {
            DBCollection col = getTokenCollection();
            col.insert(createTokenDBObjectHelper(oauthToken));
            System.out.println("CustomStoreSample create Token " + oauthToken.getTokenString());
        } catch (Exception e) {
            throw new OAuthStoreException("Failed to process create on OAuthToken " + oauthToken.getClientId(), e);
        }
    }

    private BasicDBObject createTokenDBObjectHelper(OAuthToken oauthToken) {
        BasicDBObject d = new BasicDBObject(LOOKUPKEY, oauthToken.getLookupKey());
        d.append(UNIQUEID, oauthToken.getUniqueId());
        d.append(PROVIDERID, oauthToken.getProviderId());
        d.append(TYPE, oauthToken.getType());
        d.append(SUBTYPE, oauthToken.getSubType());
        d.append(CREATEDAT, oauthToken.getCreatedAt());
        d.append(LIFETIME, oauthToken.getLifetimeInSeconds());
        d.append(EXPIRES, oauthToken.getExpires());
        d.append(TOKENSTRING, /* PreplacedwordUtil.preplacedwordEncode( */
        oauthToken.getTokenString());
        d.append(CLIENTID, oauthToken.getClientId());
        d.append(USERNAME, oauthToken.getUsername());
        d.append(SCOPE, oauthToken.getScope());
        d.append(REDIRECTURI, oauthToken.getRedirectUri());
        d.append(STATEID, oauthToken.getStateId());
        d.append(PROPS, oauthToken.getTokenProperties());
        return d;
    }

    @Override
    public void create(OAuthConsent oauthConsent) throws OAuthStoreException {
        try {
            DBCollection col = getConsentCollection();
            col.insert(createConsentDBObjectHelper(oauthConsent));
        } catch (Exception e) {
            throw new OAuthStoreException("Failed to process create on OAuthConsent " + oauthConsent.getClientId(), e);
        }
    }

    private BasicDBObject createConsentDBObjectHelper(OAuthConsent oauthConsent) {
        BasicDBObject d = new BasicDBObject(CLIENTID, oauthConsent.getClientId());
        d.append(USERNAME, oauthConsent.getUser());
        d.append(SCOPE, oauthConsent.getScope());
        d.append(RESOURCE, oauthConsent.getResource());
        d.append(PROVIDERID, oauthConsent.getProviderId());
        d.append(EXPIRES, oauthConsent.getExpires());
        d.append(PROPS, oauthConsent.getConsentProperties());
        return d;
    }

    @Override
    public OAuthClient readClient(String providerId, String clientId) throws OAuthStoreException {
        OAuthClient client = null;
        for (int i = 0; i < RETRY_COUNT; i++) {
            try {
                client = innerReadClient(providerId, clientId);
                break;
            } catch (Exception e) {
                if (i < RETRY_COUNT && isNetworkFailure(e)) {
                    try {
                        System.out.println("CustomStoreSample readClient hit a failure, trying again " + e.getMessage());
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                    }
                } else {
                    throw e;
                }
            }
        }
        return client;
    }

    private OAuthClient innerReadClient(String providerId, String clientId) throws OAuthStoreException {
        try {
            DBCollection col = getClientCollection();
            BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
            d.append(PROVIDERID, providerId);
            DBObject dbo = col.findOne(d);
            if (dbo == null) {
                System.out.println("CustomStoreSample readClient Did not find clientId " + clientId + " under " + providerId);
                return null;
            }
            System.out.println("CustomStoreSample readClient Found clientId " + clientId + " under " + providerId + " _id " + dbo.get("_id"));
            return createOAuthClientHelper(dbo);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed to readClient " + clientId + " under " + providerId, e);
        }
    }

    private OAuthClient createOAuthClientHelper(DBObject dbo) {
        return new OAuthClient((String) dbo.get(PROVIDERID), (String) dbo.get(CLIENTID), (String) dbo.get(CLIENTSECRET), (String) dbo.get(DISPLAYNAME), (boolean) dbo.get(ENABLED), (String) dbo.get(METADATA));
    }

    @Override
    public Collection<OAuthClient> readAllClients(String providerId, String attribute) throws OAuthStoreException {
        Collection<OAuthClient> results = null;
        try {
            DBCollection col = getClientCollection();
            DBCursor cursor = null;
            if (attribute == null || attribute.isEmpty()) {
                cursor = col.find(new BasicDBObject(PROVIDERID, providerId));
            } else {
                System.out.println("CustomStoreSample Attribute on readAllClients not implemented");
            // TODO Need to create query to check for all clients that
            // contain 'attribute' in metadata.
            }
            if (cursor != null && cursor.size() > 0) {
                results = new HashSet<OAuthClient>();
                while (cursor.hasNext()) {
                    DBObject dbo = cursor.next();
                    results.add(createOAuthClientHelper(dbo));
                }
            }
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on readAllClients found under " + providerId, e);
        }
        return results;
    }

    @Override
    public OAuthToken readToken(String providerId, String lookupKey) throws OAuthStoreException {
        for (int i = 0; i < RETRY_COUNT; i++) {
            try {
                DBCollection col = getTokenCollection();
                DBObject dbo = col.findOne(createTokenKeyHelper(providerId, lookupKey));
                if (dbo == null) {
                    System.out.println("CustomStoreSample readToken Did not find lookupKey " + lookupKey);
                    return null;
                }
                System.out.println("CustomStoreSample readToken Found lookupKey " + lookupKey + " under " + providerId + " _id " + dbo.get("_id"));
                return createOAuthTokenHelper(dbo);
            } catch (Exception e) {
                if (i < RETRY_COUNT && isNetworkFailure(e)) {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e1) {
                    }
                } else {
                    throw new OAuthStoreException("CustomStoreSample Failed to readToken " + lookupKey, e);
                }
            }
        }
        throw new OAuthStoreException("CustomStoreSample Failed to readToken after " + RETRY_COUNT + "tries: " + lookupKey);
    }

    private OAuthToken createOAuthTokenHelper(DBObject dbo) {
        return new OAuthToken((String) dbo.get(LOOKUPKEY), (String) dbo.get(UNIQUEID), (String) dbo.get(PROVIDERID), (String) dbo.get(TYPE), (String) dbo.get(SUBTYPE), (long) dbo.get(CREATEDAT), (int) dbo.get(LIFETIME), (long) dbo.get(EXPIRES), (String) dbo.get(TOKENSTRING), (String) dbo.get(CLIENTID), (String) dbo.get(USERNAME), (String) dbo.get(SCOPE), (String) dbo.get(REDIRECTURI), (String) dbo.get(STATEID), (String) dbo.get(PROPS));
    }

    @Override
    public Collection<OAuthToken> readAllTokens(String providerId, String username) throws OAuthStoreException {
        try {
            DBCollection col = getTokenCollection();
            BasicDBObject d = new BasicDBObject(USERNAME, username);
            d.append(PROVIDERID, providerId);
            DBCursor result = col.find(d);
            Collection<OAuthToken> collection = null;
            while (result.hasNext()) {
                DBObject dbo = result.next();
                if (collection == null) {
                    collection = new ArrayList<OAuthToken>();
                }
                collection.add(createOAuthTokenHelper(dbo));
            }
            return collection;
        } catch (Exception e) {
            throw new OAuthStoreException("Failed to readAllTokens for " + username + " under " + providerId, e);
        }
    }

    @Override
    public int countTokens(String providerId, String username, String clientId) throws OAuthStoreException {
        try {
            DBCollection col = getTokenCollection();
            BasicDBObject d = new BasicDBObject(USERNAME, username);
            d.append(PROVIDERID, providerId);
            d.append(CLIENTID, clientId);
            // mongoDB returns as a long
            return (int) col.count(d);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on countTokens for " + username, e);
        }
    }

    @Override
    public OAuthConsent readConsent(String providerId, String username, String clientId, String resource) throws OAuthStoreException {
        try {
            DBCollection col = getConsentCollection();
            DBObject dbo = col.findOne(createConsentKeyHelper(providerId, username, clientId, resource));
            if (dbo == null) {
                System.out.println("CustomStoreSample readConsent Did not find username " + username);
                return null;
            }
            System.out.println("CustomStoreSample readConsent Found clientId " + clientId + " under " + providerId + " _id " + dbo.get("_id"));
            return new OAuthConsent(clientId, (String) dbo.get(USERNAME), (String) dbo.get(SCOPE), resource, providerId, (long) dbo.get(EXPIRES), (String) dbo.get(PROPS));
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on readConsent for " + username, e);
        }
    }

    @Override
    public void update(OAuthClient oauthClient) throws OAuthStoreException {
        try {
            DBCollection col = getClientCollection();
            col.update(createClientKeyHelper(oauthClient), createClientDBObjectHelper(oauthClient), false, false);
            System.out.println("CustomStoreSample update on " + oauthClient.getClientId());
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on update for OAuthClient for " + oauthClient.getClientId(), e);
        }
    }

    @Override
    public void update(OAuthToken oauthToken) throws OAuthStoreException {
        try {
            DBCollection col = getTokenCollection();
            col.update(createTokenKeyHelper(oauthToken), createTokenDBObjectHelper(oauthToken), false, false);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on update for OAuthToken for " + oauthToken.getClientId(), e);
        }
    }

    @Override
    public void update(OAuthConsent oauthConsent) throws OAuthStoreException {
        try {
            DBCollection col = getConsentCollection();
            col.update(createConsentKeyHelper(oauthConsent), createConsentDBObjectHelper(oauthConsent), false, false);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on update for OAuthConsent for " + oauthConsent.getClientId(), e);
        }
    }

    @Override
    public void deleteClient(String providerId, String clientId) throws OAuthStoreException {
        try {
            DBCollection col = getClientCollection();
            WriteResult wr = col.remove(createClientKeyHelper(providerId, clientId));
            System.out.println("CustomStoreSample deleteClient requested on clientId " + clientId + " under " + providerId);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on delete for OAuthClient for " + clientId, e);
        }
    }

    @Override
    public void deleteToken(String providerId, String lookupKey) throws OAuthStoreException {
        try {
            DBCollection col = getTokenCollection();
            col.remove(createTokenKeyHelper(providerId, lookupKey));
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on delete for OAuthToken for " + lookupKey, e);
        }
    }

    @Override
    public void deleteTokens(String providerId, long timestamp) throws OAuthStoreException {
        try {
            System.out.println("CustomStoreSample deleteTokens request for " + providerId + " expiring before " + timestamp);
            DBCollection col = getTokenCollection();
            System.out.println("CustomStoreSample deleteTokens before " + col.count());
            BasicDBObject query = new BasicDBObject();
            query.put(EXPIRES, new BasicDBObject("$lt", timestamp));
            query.put(PROVIDERID, providerId);
            col.remove(query);
            System.out.println("CustomStoreSample deleteTokens after " + col.count());
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on deleteTokens for time after " + timestamp, e);
        }
    }

    @Override
    public void deleteConsent(String providerId, String username, String clientId, String resource) throws OAuthStoreException {
        try {
            DBCollection col = getConsentCollection();
            BasicDBObject db = new BasicDBObject(CLIENTID, clientId);
            db.put(USERNAME, username);
            db.put(PROVIDERID, providerId);
            db.put(RESOURCE, resource);
            col.remove(db);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on delete for Consent for " + username, e);
        }
    }

    @Override
    public void deleteConsents(String providerId, long timestamp) throws OAuthStoreException {
        try {
            DBCollection col = getConsentCollection();
            BasicDBObject query = new BasicDBObject();
            query.put(EXPIRES, new BasicDBObject("$lt", timestamp));
            query.put(PROVIDERID, providerId);
            col.remove(query);
        } catch (Exception e) {
            throw new OAuthStoreException("Failed on deleteConsents for time after " + timestamp, e);
        }
    }

    private BasicDBObject createClientKeyHelper(OAuthClient oauthClient) {
        return createClientKeyHelper(oauthClient.getProviderId(), oauthClient.getClientId());
    }

    private BasicDBObject createClientKeyHelper(String providerId, String clientId) {
        BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
        d.append(PROVIDERID, providerId);
        return d;
    }

    private BasicDBObject createTokenKeyHelper(OAuthToken oauthToken) {
        return createTokenKeyHelper(oauthToken.getProviderId(), oauthToken.getLookupKey());
    }

    private BasicDBObject createTokenKeyHelper(String providerId, String lookupKey) {
        BasicDBObject d = new BasicDBObject(LOOKUPKEY, lookupKey);
        d.append(PROVIDERID, providerId);
        return d;
    }

    private BasicDBObject createConsentKeyHelper(OAuthConsent oauthConsent) {
        return createConsentKeyHelper(oauthConsent.getClientId(), oauthConsent.getUser(), oauthConsent.getResource(), oauthConsent.getProviderId());
    }

    private BasicDBObject createConsentKeyHelper(String providerId, String username, String clientId, String resource) {
        BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
        d.append(USERNAME, username);
        d.append(RESOURCE, resource);
        d.append(PROVIDERID, providerId);
        return d;
    }

    private boolean isNetworkFailure(Exception e) {
        Throwable causeBy = e;
        while (causeBy != null) {
            if (causeBy instanceof IOException) {
                System.out.println("Hit an IOException: " + causeBy);
                return true;
            } else {
                causeBy = e.getCause();
            }
        }
        return false;
    }
}

19 Source : NoAuthMongoClientWrapper.java
with Apache License 2.0
from apache

protected MongoCollectionWrapper wrap(DBCollection collection) {
    return new DefaultMongoCollectionWrapper(collection);
}

19 Source : DefaultMongoCollectionWrapper.java
with Apache License 2.0
from apache

public clreplaced DefaultMongoCollectionWrapper implements MongoCollectionWrapper {

    private final DBCollection collection;

    public DefaultMongoCollectionWrapper(DBCollection collection) {
        this.collection = collection;
    }

    @Override
    public MongoCursorWrapper find(DBObject dbObject, DBObject dbObject2) throws MongoDbException {
        return wrap(collection.find(dbObject, dbObject2));
    }

    @Override
    public Cursor aggregate(List<? extends DBObject> pipeline, AggregationOptions options) {
        return collection.aggregate(pipeline, options);
    }

    @Override
    public Cursor aggregate(DBObject firstP, DBObject[] remainder) {
        AggregationOptions options = AggregationOptions.builder().build();
        List<DBObject> pipeline = new ArrayList<>();
        pipeline.add(firstP);
        Collections.addAll(pipeline, remainder);
        return aggregate(pipeline, options);
    }

    @Override
    public MongoCursorWrapper find() throws MongoDbException {
        return wrap(collection.find());
    }

    @Override
    public void drop() throws MongoDbException {
        collection.drop();
    }

    @Override
    public WriteResult update(DBObject updateQuery, DBObject insertUpdate, boolean upsert, boolean multi) throws MongoDbException {
        return collection.update(updateQuery, insertUpdate, upsert, multi);
    }

    @Override
    public WriteResult insert(List<DBObject> m_batch) throws MongoDbException {
        return collection.insert(m_batch);
    }

    @Override
    public MongoCursorWrapper find(DBObject query) throws MongoDbException {
        return wrap(collection.find(query));
    }

    @Override
    public void dropIndex(BasicDBObject mongoIndex) throws MongoDbException {
        collection.dropIndex(mongoIndex);
    }

    @Override
    public void createIndex(BasicDBObject mongoIndex) throws MongoDbException {
        collection.createIndex(mongoIndex);
    }

    @Override
    public void createIndex(BasicDBObject mongoIndex, BasicDBObject options) throws MongoDbException {
        collection.createIndex(mongoIndex, options);
    }

    @Override
    public WriteResult remove() throws MongoDbException {
        return remove(new BasicDBObject());
    }

    @Override
    public WriteResult remove(DBObject query) throws MongoDbException {
        return collection.remove(query);
    }

    @Override
    public WriteResult save(DBObject toTry) throws MongoDbException {
        return collection.save(toTry);
    }

    @Override
    public long count() throws MongoDbException {
        return collection.count();
    }

    @Override
    public List distinct(String key) throws MongoDbException {
        return collection.distinct(key);
    }

    protected MongoCursorWrapper wrap(DBCursor cursor) {
        return new DefaultCursorWrapper(cursor);
    }
}

19 Source : MongoSelectQuery.java
with Apache License 2.0
from 597365581

public Object run(DB db) throws Exception {
    DBCollection collection = db.getCollection(this.collectionName);
    if (this.distinctField != null) {
        return runDistinct(collection);
    }
    if (this.aggregateQuery) {
        System.out.println("Running aggregate query.");
        return runAggregate(collection);
    }
    return runFind(collection);
}

19 Source : MongoSelectQuery.java
with Apache License 2.0
from 597365581

private Object runDistinct(DBCollection collection) {
    List results = collection.distinct(this.distinctField, this.query);
    if (this.count)
        return Integer.valueOf(results.size());
    return results;
}

19 Source : BingCacheMongoDB.java
with GNU General Public License v3.0
from 20n

public clreplaced BingCacheMongoDB {

    // the Bing Search collection is located in a separate database
    private DBCollection dbBingCache;

    private String hostname;

    private int port;

    private String database;

    private DB mongoDB;

    private static final String BING_CACHE_COLLECTION_NAME = "cache";

    private static final String WARNING_MESSAGE = "\nWARNING!!!\n" + "No \"cache\" collection seems to exist in the \"bingsearch\" Mongo database.\n" + "Bing Cache queries should be found in a MongoDB instance running on Chimay on port 27777.\n" + "Please check that Chimay (Or your provided database) can be accessed from the host you are running the Bing Searcher on.\n" + "Note that it is possible to restore the Bing Search cache dump living on the NAS with " + "the \"mongorestore\" command.\n" + "If you don't take any action before continuing, all queries will be counted against our " + "monthly transaction quota.\n" + "Please enter [y] to continue, or [n] if you want to abort:";

    public BingCacheMongoDB(String hostname, int port, String database) {
        this.hostname = hostname;
        this.port = port;
        this.database = database;
        init();
    }

    public void init() {
        try {
            MongoClient mongo = new MongoClient(hostname, port);
            mongoDB = mongo.getDB(database);
        } catch (UnknownHostException e) {
            throw new IllegalArgumentException("Invalid host for Mongo Bing Cache server.");
        } catch (MongoException e) {
            throw new IllegalArgumentException("Could not initialize Mongo driver.");
        }
        if (!mongoDB.getCollectionNames().contains(BING_CACHE_COLLECTION_NAME) || mongoDB.getCollection(BING_CACHE_COLLECTION_NAME).count() == 0) {
            System.out.println(WARNING_MESSAGE);
            if (!askConfirmationWhenCacheEmpty()) {
                System.out.println("Aborting the run.");
                System.exit(1);
            }
        }
        this.dbBingCache = mongoDB.getCollection(BING_CACHE_COLLECTION_NAME);
    }

    private boolean askConfirmationWhenCacheEmpty() {
        try (Scanner reader = new Scanner(System.in)) {
            String userDecision = reader.next();
            if (userDecision.equals("n")) {
                return false;
            } else if (userDecision.equals("y")) {
                return true;
            }
        }
        System.out.println("Incorrect input! Please enter either [y] or [n]. Asking again...");
        return askConfirmationWhenCacheEmpty();
    }

    public BasicDBObject getNameSearchResultDBObjectFromName(String formattedName) {
        BasicDBObject whereQuery = new BasicDBObject();
        BasicDBObject allFields = new BasicDBObject();
        whereQuery.put("name", formattedName);
        return (BasicDBObject) dbBingCache.findOne(whereQuery, allFields);
    }

    public void cacheNameSearchResult(NameSearchResults nameSearchResults) {
        BasicDBObject nameSearchResultDBObject = new BasicDBObject();
        nameSearchResultDBObject.put("name", nameSearchResults.getName());
        Long totalCountSearchResults = nameSearchResults.getTotalCountSearchResults();
        if (totalCountSearchResults >= 0) {
            nameSearchResultDBObject.put("totalCountSearchResults", totalCountSearchResults);
        }
        Set<SearchResult> topSearchResults = nameSearchResults.getTopSearchResults();
        if (topSearchResults != null) {
            BasicDBList topSearchResultsList = new BasicDBList();
            for (SearchResult topSearchResult : topSearchResults) {
                topSearchResultsList.add(topSearchResult.getBasicDBObject());
            }
            nameSearchResultDBObject.put("topSearchResults", topSearchResultsList);
        }
        dbBingCache.save(nameSearchResultDBObject);
    }

    public void updateTotalCountSearchResults(String formattedName, NameSearchResults nameSearchResults) {
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("name", formattedName);
        // Update the existing doreplacedent in the cache
        BasicDBObject newTotalCountSearchResults = new BasicDBObject();
        newTotalCountSearchResults.append("$set", new BasicDBObject().append("totalCountSearchResults", nameSearchResults.getTotalCountSearchResults()));
        dbBingCache.update(whereQuery, newTotalCountSearchResults);
    }

    public void updateTopSearchResults(String formattedName, NameSearchResults nameSearchResults) {
        BasicDBObject whereQuery = new BasicDBObject();
        whereQuery.put("name", formattedName);
        // Transform Set into BasicDBList for storage
        BasicDBList topSearchResultsList = new BasicDBList();
        for (SearchResult topSearchResult : nameSearchResults.getTopSearchResults()) {
            topSearchResultsList.add(topSearchResult.getBasicDBObject());
        }
        // Update the existing doreplacedent in the cache
        BasicDBObject newTopSearchResults = new BasicDBObject();
        newTopSearchResults.append("$set", new BasicDBObject().append("topSearchResults", topSearchResultsList));
        dbBingCache.update(whereQuery, newTopSearchResults);
    }
}

18 Source : MarcMongodbClientTest.java
with GNU General Public License v3.0
from pkiraly

// @Test
public void testInsert() throws UnknownHostException {
    MarcMongodbClient client = new MarcMongodbClient("localhost", 27017, "sub_last_print");
    DBCollection collection = client.getCollection("marc");
    BasicDBObject doc = createTestObject();
    collection.insert(doc);
    replacedertNotNull(collection);
    replacedertEquals(1, collection.count());
    collection.remove(new BasicDBObject("name", "MongoDB"));
    replacedertEquals(0, collection.count());
}

18 Source : MarcMongodbClientTest.java
with GNU General Public License v3.0
from pkiraly

// @Test
public void testFindOne() throws UnknownHostException {
    MarcMongodbClient client = new MarcMongodbClient("localhost", 27017, "sub_last_print");
    DBCollection collection = client.getCollection("marc");
    BasicDBObject doc = createTestObject();
    collection.insert(doc);
    replacedertEquals(1, collection.count());
    DBObject myDoc = collection.findOne();
    replacedertEquals("MongoDB", myDoc.get("name"));
    replacedertEquals("database", myDoc.get("type"));
    replacedertEquals(1, myDoc.get("count"));
    replacedertEquals(BasicDBObject.clreplaced, myDoc.get("info").getClreplaced());
    replacedertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
    replacedertEquals(203, ((BasicDBObject) myDoc.get("info")).get("x"));
    replacedertEquals(Integer.clreplaced, ((BasicDBObject) myDoc.get("info")).get("x").getClreplaced());
    System.out.println(myDoc);
    collection.remove(new BasicDBObject("name", "MongoDB"));
}

18 Source : MongoWrapper.java
with GNU General Public License v3.0
from NightscoutFoundation

public boolean WriteToMongo(BasicDBObject bdbo) {
    DBCollection coll;
    try {
        coll = openMongoDb();
        coll.insert(bdbo);
    } catch (UnknownHostException e) {
        Log.e(TAG, "WriteToMongo caught UnknownHostException! ", e);
        return false;
    } catch (MongoException e) {
        Log.e(TAG, "WriteToMongo caught MongoException! ", e);
        return false;
    } catch (Exception e) {
        Log.e(TAG, "WriteToMongo caught Exception! ", e);
        closeMongoDb();
        return false;
    } finally {
        closeMongoDb();
    }
    return true;
}

18 Source : MongoWrapper.java
with GNU General Public License v3.0
from NightscoutFoundation

// records will be marked by their timestamp
public List<LibreWifiData> ReadFromMongoLibre(int numberOfRecords) {
    System.out.println("Starting to read from mongodb");
    List<LibreWifiData> trd_list = new LinkedList<LibreWifiData>();
    DBCollection coll;
    LibreWifiData lastTrd = null;
    try {
        coll = openMongoDb();
        BasicDBObject query = new BasicDBObject("BlockBytes", new BasicDBObject("$exists", true));
        DBCursor cursor = coll.find(query);
        cursor.sort(new BasicDBObject("CaptureDateTime", -1));
        try {
            while (cursor.hasNext() && trd_list.size() < numberOfRecords) {
                // System.out.println(cursor.next());
                Log.d(TAG, "Read a libre object from mongodb");
                LibreWifiData trd = new LibreWifiData((BasicDBObject) cursor.next());
                // Do our best to fix the relative time...
                trd.RelativeTime = new Date().getTime() - trd.CaptureDateTime;
                // since we are reading it from the db, it was uploaded...
                trd.Uploaded = 1;
                if (!LibreWifiReader.almostEquals(lastTrd, trd)) {
                    lastTrd = trd;
                    trd_list.add(0, trd);
                    System.out.println(trd.toString());
                } else {
                    Log.e(TAG, "Error, read a value from mongo, but it seems duplicate" + trd.toString());
                }
            }
        } finally {
            cursor.close();
        }
    } catch (UnknownHostException e) {
        Log.e(TAG, "ReadFromMongo: caught UnknownHostException! ", e);
        return null;
    } catch (MongoException e) {
        Log.e(TAG, "ReadFromMongo: caught MongoException! ", e);
        return trd_list;
    } catch (Exception e) {
        Log.e(TAG, "ReadFromMongo: caught Exception! ", e);
        closeMongoDb();
        return null;
    } finally {
        closeMongoDb();
    }
    return trd_list;
}

18 Source : MongoWrapper.java
with GNU General Public License v3.0
from NightscoutFoundation

// records will be marked by their timestamp
public List<TransmitterRawData> ReadFromMongo(int numberOfRecords) {
    System.out.println("Starting to read from mongodb");
    List<TransmitterRawData> trd_list = new LinkedList<TransmitterRawData>();
    DBCollection coll;
    TransmitterRawData lastTrd = null;
    try {
        coll = openMongoDb();
        BasicDBObject query = new BasicDBObject("RawValue", new BasicDBObject("$exists", true));
        DBCursor cursor = coll.find(query);
        cursor.sort(new BasicDBObject("CaptureDateTime", -1));
        try {
            while (cursor.hasNext() && trd_list.size() < numberOfRecords) {
                // System.out.println(cursor.next());
                Log.d(TAG, "Read an object from mongodb");
                TransmitterRawData trd = new TransmitterRawData((BasicDBObject) cursor.next());
                // Do our best to fix the relative time...
                trd.RelativeTime = new Date().getTime() - trd.CaptureDateTime;
                // since we are reading it from the db, it was uploaded...
                trd.Uploaded = 1;
                if (lastTrd == null) {
                    trd_list.add(0, trd);
                    lastTrd = trd;
                    System.out.println(trd.toTableString());
                } else if (!WixelReader.almostEquals(lastTrd, trd)) {
                    lastTrd = trd;
                    trd_list.add(0, trd);
                    System.out.println(trd.toTableString());
                }
            }
        } finally {
            cursor.close();
        }
    } catch (UnknownHostException e) {
        Log.e(TAG, "ReadFromMongo: caught UnknownHostException! ", e);
        return null;
    } catch (MongoException e) {
        Log.e(TAG, "ReadFromMongo: caught MongoException! ", e);
        return trd_list;
    } catch (Exception e) {
        Log.e(TAG, "ReadFromMongo: caught Exception! ", e);
        closeMongoDb();
        return null;
    } finally {
        closeMongoDb();
    }
    return trd_list;
}

18 Source : Boot.java
with Apache License 2.0
from devops-dojo

/**
 * @author zutherb
 */
public clreplaced Boot {

    private final static MongoClient MONGO_CLIENT;

    private final static DBCollection DB_COLLECTION;

    static {
        try {
            MONGO_CLIENT = new MongoClient("localhost");
            DB shopDB = MONGO_CLIENT.getDB("shop");
            DB_COLLECTION = shopDB.getCollection("order");
        } catch (UnknownHostException e) {
            throw new RuntimeException("Order Service could not be started", e);
        }
    }

    public static void main(String[] args) {
        put("/submitOrder", "application/json", (request, response) -> {
            String body = request.body();
            if (!isNullOrEmpty(body)) {
                DBObject order = (DBObject) JSON.parse(body);
                DB_COLLECTION.save(order);
                response.status(HttpStatus.CREATED_201);
                return "";
            }
            response.status(HttpStatus.BAD_REQUEST_400);
            return "";
        });
    }
}

18 Source : NoAuthMongoClientWrapper.java
with Apache License 2.0
from apache

/**
 * Return a list of custom "lastErrorModes" (if any) defined in the replica set configuration
 * object on the server. These can be used as the "w" setting for the write concern in addition to
 * the standard "w" values of <number> or "majority".
 *
 * @return a list of the names of any custom "lastErrorModes"
 * @throws MongoDbException if a problem occurs
 */
public List<String> getLastErrorModes() throws MongoDbException {
    List<String> customLastErrorModes = new ArrayList<>();
    DB local = getDb(LOCAL_DB);
    if (local != null) {
        try {
            DBCollection replset = local.getCollection(REPL_SET_COLLECTION);
            if (replset != null) {
                DBObject config = replset.findOne();
                extractLastErrorModes(config, customLastErrorModes);
            }
        } catch (Exception e) {
            throw new MongoDbException(e);
        }
    }
    return customLastErrorModes;
}

18 Source : KerberosMongoClientWrapper.java
with Apache License 2.0
from apache

@Override
protected MongoCollectionWrapper wrap(DBCollection collection) {
    return KerberosInvocationHandler.wrap(MongoCollectionWrapper.clreplaced, authContext, new KerberosMongoCollectionWrapper(collection, authContext));
}

18 Source : MongoDBStore.java
with Apache License 2.0
from apache

/**
 * Creates a connection to MongoDB using the given credentials.
 *
 * @param mongoDB the {@link MongoDB} facade to connect to;
 * @param userName the (optional) user name to use;
 * @param preplacedword the (optional) preplacedword to use.
 * @throws MongoException in case the connection or authentication failed.
 */
private void connectToDB(MongoDB mongoDB, String userName, String preplacedword) throws MongoException {
    if (!mongoDB.connect(userName, preplacedword)) {
        throw new MongoException("Failed to connect to MongoDB! Authentication failed!");
    }
    DBCollection collection = mongoDB.getCollection();
    if (collection == null) {
        throw new MongoException("Failed to connect to MongoDB! No collection returned!");
    }
    collection.ensureIndex(new BasicDBObject(NAME, 1).append("unique", true));
}

18 Source : MongoSelectQuery.java
with Apache License 2.0
from 597365581

private Object runAggregate(DBCollection collection) {
    List pipeline = buildAggregatePipeline();
    AggregationOutput cursor = collection.aggregate(pipeline);
    return cursor.results();
}

18 Source : MongoSelectQuery.java
with Apache License 2.0
from 597365581

private Object runFind(DBCollection collection) {
    DBCursor cursor = collection.find(this.query, this.projections);
    if (this.orderBy.size() > 0) {
        cursor.sort(this.orderBy);
    }
    if (!this.isFlattening) {
        if (this.limit != null)
            cursor.limit(this.limit.intValue());
        if (this.offset != null) {
            cursor.skip(this.offset.intValue());
        }
    }
    if (this.count) {
        int i = cursor.count();
        cursor.close();
        return Integer.valueOf(i);
    }
    return cursor;
}

18 Source : ServerConnection.java
with Apache License 2.0
from 597365581

public List<DBObject> getIndexes(String colName) throws SQLException {
    try {
        DBCollection col = this.db.getCollection(colName);
        return col.getIndexInfo();
    } catch (Exception var3) {
        throw new SQLException("Collection not found: " + colName);
    }
}

18 Source : MongoExecutor.java
with Apache License 2.0
from 597365581

private int numberToSample(DBCollection collection) {
    long count = -1L;
    try {
        count = collection.count();
    } catch (Exception var5) {
        System.out.println("Error while sampling collection: " + collection.getName());
    }
    return count <= 10L ? -1 : (int) Math.ceil((double) count * this.SAMPLE_FRACTION);
}

18 Source : ReachablesProjectionUpdate.java
with GNU General Public License v3.0
from 20n

public void updateDatabase(DBCollection reachables) {
    for (String product : products) {
        // The query object for this product
        BasicDBObject newProductQuery = new BasicDBObject().append(INCHI_KEY, product);
        // DB list of the substrates of this projection
        BasicDBList substrateList = new BasicDBList();
        substrateList.addAll(substrates);
        // DB list of the one RO replacedociated with this projection
        BasicDBList roList = new BasicDBList();
        roList.addAll(ros);
        // The full entry to be added to the product's precursor list
        BasicDBObject precursorEntry = new BasicDBObject().append(SUBSTRATES_KEY, substrateList).append(RO_KEY, roList);
        // The command to push the precursor entry onto the precursor list
        BasicDBObject precursors = new BasicDBObject();
        precursors.append("$push", new BasicDBObject(PRECURSOR_KEY, precursorEntry));
        // Do the update!
        reachables.update(newProductQuery, precursors, UPSERT, NO_MULTI);
    }
}

17 Source : UpdateVo.java
with GNU General Public License v3.0
from xsonorg

public int update(DBCollection collection, WriteConcern writeConcern) {
    DBObject query = new BasicDBObject();
    DBObject update = new BasicDBObject();
    if (null != this.condition) {
        this.condition.setQuery(query, null);
    }
    boolean hreplacedet = false;
    boolean hasInc = false;
    DBObject setObject = new BasicDBObject();
    DBObject incObject = new BasicDBObject();
    for (int i = 0, n = setColumns.size(); i < n; i++) {
        ColumnUpdateVo columnUpdateVo = setColumns.get(i);
        ValueVo valueVo = columnUpdateVo.getValueVo();
        if (ColumnUpdateType.NORMAL == columnUpdateVo.getType()) {
            setObject.put(columnUpdateVo.getName(), valueVo.getValue());
            hreplacedet = true;
        } else if (ColumnUpdateType.ADD == columnUpdateVo.getType()) {
            // updateSetting.put("$inc", new BasicDBObject(columnUpdateVo.getName(), valueVo.getValue()));
            incObject.put(columnUpdateVo.getName(), valueVo.getValue());
            hasInc = true;
        } else {
            if (ValueType.INTEGER == valueVo.getType()) {
                int val = ((Integer) valueVo.getValue()).intValue();
                // updateSetting.put("$inc", new BasicDBObject(columnUpdateVo.getName(), -val));
                incObject.put(columnUpdateVo.getName(), -val);
            } else if (ValueType.DOUBLE == valueVo.getType()) {
                double val = ((Double) valueVo.getValue()).doubleValue();
                // updateSetting.put("$inc", new BasicDBObject(columnUpdateVo.getName(), -val));
                incObject.put(columnUpdateVo.getName(), -val);
            } else {
                throw new SqlParseException("When updating a minus operation, invalid data type: " + valueVo.getType());
            }
            hasInc = true;
        }
    }
    if (hreplacedet) {
        update.put("$set", setObject);
    }
    if (hasInc) {
        update.put("$inc", incObject);
    }
    // 日志显示
    log(query, update);
    // upsert: 如果未找到记录是否插入
    // multi:是否更新多条
    // WriteResult result = collection.update(query, update, false, true, WriteConcern.ACKNOWLEDGED);
    // WriteResult result = collection.update(query, update, false, true, MongoComponent.getInstance().getDefaultWriteConcern());
    WriteResult result = collection.update(query, update, false, true, writeConcern);
    // System.out.println(query.toString());
    // System.out.println(update.toString());
    return result.getN();
}

17 Source : OccasionResourceTest.java
with Eclipse Public License 1.0
from OpenLiberty

/**
 * The main junit test clreplaced for the Occasion Service
 */
public clreplaced OccasionResourceTest {

    private static MongoClient mongoClient;

    private static DB db;

    private static DBCollection collection;

    private static final String clazz = OccasionResourceTest.clreplaced.getName();

    private static final Logger logger = Logger.getLogger(clazz);

    private static final String occasionServiceURL = System.getProperty("liberty.test.occasion.service.url");

    private static final int mongoPort = Integer.parseInt(System.getProperty("mongo.test.port"));

    private static final String mongoHostname = System.getProperty("mongo.test.hostname");

    @Rule
    public TestName name = new TestName();

    /**
     * Connect to the Occasions database and set the collection
     */
    @BeforeClreplaced
    public static void beforeClreplaced() throws UnknownHostException {
        String method = "beforeClreplaced";
        logger.entering(clazz, method);
        mongoClient = new MongoClient(mongoHostname, mongoPort);
        db = mongoClient.getDB("gifts-occasion");
        collection = db.getCollection("occasions");
        logger.exiting(clazz, method);
    }

    /**
     * Cleanup the database
     */
    @AfterClreplaced
    public static void cleanup() {
        String method = "cleanup";
        logger.entering(clazz, method);
        db.dropDatabase();
        mongoClient.close();
        logger.exiting(clazz, method);
    }

    /**
     * Let each test start with a blank db.
     */
    @Before
    public void beforeTest() {
        logger.entering(clazz, name.getMethodName());
        logger.fine(collection.remove(new BasicDBObject()).toString());
        logger.exiting(clazz, name.getMethodName());
    }

    /**
     * Test the get GET call failure with a bad groupId
     */
    @Test
    public void testGETBadGroup() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload for occasion 1
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0001", 20));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        "1111", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0001", /* recipient ID  */
        "0997", contributions);
        collection.insert(occasion.toDbo());
        // build the json payload for occasion 2
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0002", 50));
        contributions.add(new Occasion.Contribution("0003", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-09-30", /* group ID      */
        "2222", /* interval      */
        "annual", /* occasion name */
        "Jill Doe's Birthday", /* organizer ID  */
        "0002", /* recipient ID  */
        "0998", contributions);
        collection.insert(occasion.toDbo());
        // get the ID
        occasion = new Occasion(collection.findOne(occasion.toDbo()));
        // build the json payload for occasion 3
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("9999", 20));
        contributions.add(new Occasion.Contribution("8888", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2018-01-31", /* group ID      */
        "3333", /* interval      */
        "annual", /* occasion name */
        "Jason Doe's Birthday", /* organizer ID  */
        "8888", /* recipient ID  */
        "9999", contributions);
        collection.insert(occasion.toDbo());
        // verify that there are 3 occsions in the db
        long expectedCount = 3;
        long count = collection.count();
        replacedertTrue("The check that all occasions are in the db failed. Expected: " + expectedCount + "\n\nResult:\n\n" + count, count == expectedCount);
        // confirm that we get a server 400
        testEndpoint("/?groupId=xxxx", "GET", "", 200);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test the get GET call by creating some occasions and then listing one of them.
     */
    @Test
    public void testGET() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload for occasion 1
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0001", 20));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        "1111", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0001", /* recipient ID  */
        "0997", contributions);
        collection.insert(occasion.toDbo());
        // build the json payload for occasion 2
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0002", 50));
        contributions.add(new Occasion.Contribution("0003", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-09-30", /* group ID      */
        "2222", /* interval      */
        "annual", /* occasion name */
        "Jill Doe's Birthday", /* organizer ID  */
        "0002", /* recipient ID  */
        "0998", contributions);
        collection.insert(occasion.toDbo());
        // get the ID
        occasion = new Occasion(collection.findOne(occasion.toDbo()));
        String expectedFinal = occasion.toString();
        String occasionToGet = occasion.getId().toString();
        // build the json payload for occasion 3
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("9999", 20));
        contributions.add(new Occasion.Contribution("8888", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2018-01-31", /* group ID      */
        "3333", /* interval      */
        "annual", /* occasion name */
        "Jason Doe's Birthday", /* organizer ID  */
        "8888", /* recipient ID  */
        "9999", contributions);
        collection.insert(occasion.toDbo());
        // verify that there are 3 occsions in the db
        long expectedCount = 3;
        long count = collection.count();
        replacedertTrue("The check that all occasions are in the db failed. Expected: " + expectedCount + "\n\nResult:\n\n" + count, count == expectedCount);
        // confirm that we can retrieve just one
        testEndpoint("/" + occasionToGet, "GET", expectedFinal, 200);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Send a basic POST request to create and occasion with a json payload
     */
    @Test
    public void testPOST() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload for occasion
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0001", 20));
        contributions.add(new Occasion.Contribution("0002", 50));
        contributions.add(new Occasion.Contribution("0003", 50));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        "0001", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0001", /* recipient ID  */
        "2999", contributions);
        String responseString = testEndpointJson("/", "POST", occasion.toString(), "", 200);
        String id = (String) ((DBObject) JSON.parse(responseString)).get(Occasion.OCCASION_ID_KEY);
        logger.fine("id = " + id);
        ObjectId oid = new ObjectId(id);
        BasicDBObject queryObj = new BasicDBObject(Occasion.OCCASION_ID_KEY, oid);
        DBObject dbo = collection.findOne(queryObj);
        logger.fine("After findOne with dbo: " + dbo);
        String expected = new Occasion(dbo).getId().toString();
        replacedertTrue("Mismatch in " + name.getMethodName() + ". Expected:\n\n" + expected + "\n\nRecieved:\n\n" + responseString, responseString.contains(expected));
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Similar to testPOST, but this test sends a payload with an id field
     */
    @Test(expected = IllegalArgumentException.clreplaced)
    public void testPOSTWithId() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0004", 21));
        contributions.add(new Occasion.Contribution("0005", 51));
        contributions.add(new Occasion.Contribution("0006", 52));
        Occasion occasion = new Occasion(/* ID            */
        new ObjectId("1000"), /* date          */
        "2117-07-31", /* group ID      */
        "0002", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0004", /* recipient ID  */
        "0006", contributions);
        // expecting 400 because POST is for creating a new occasion and should not include an ID
        testEndpointJson("/", "POST", occasion.toString(), "IllegalArgumentException", 400);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Call POST with garbage, expecting a response code 400
     */
    @Test
    public void testPOSTFailure() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        testEndpointJson("/", "POST", null, "", 400);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test basic PUT call to update an occasion with a json payload.
     *
     * <p>First it creates an occasion then it updates it
     */
    @Test
    public void testPUT() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0007", 22));
        contributions.add(new Occasion.Contribution("0008", 53));
        contributions.add(new Occasion.Contribution("0009", 54));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        "0003", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0007", /* recipient ID  */
        "0097", contributions);
        // create the initial occasion.  Need to use POST and not put it in the
        // database directly, or else the orchestrator won't know about it and will
        // throw an NPE.
        String responseString = testEndpointJson("/", "POST", occasion.toString(), "", 200);
        String id = (String) ((DBObject) JSON.parse(responseString)).get(Occasion.OCCASION_ID_KEY);
        logger.fine("id = " + id);
        DBObject dbo = collection.findOne(new BasicDBObject(Occasion.OCCASION_ID_KEY, new ObjectId(id)));
        occasion = new Occasion(dbo);
        String jsonUpdate = Json.createObjectBuilder().add(Occasion.OCCASION_NAME_KEY, "Johnny D's Birthday").build().toString();
        // update the expected string
        occasion.setName("Johnny D's Birthday");
        // update the occasion
        testEndpointJson("/" + occasion.getId(), "PUT", jsonUpdate, "", 200);
        DBObject resultDbo = collection.findOne(new BasicDBObject(Occasion.OCCASION_ID_KEY, occasion.getId()));
        Occasion resultOccasion = new Occasion(resultDbo);
        replacedertTrue(name.getMethodName() + ": PUT result does not match. Expected:\n\n" + occasion.toString() + "\n\nResult:\n\n" + resultOccasion + "\n\n", occasion.equals(resultOccasion));
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test PUT failure. Expects to get a response code 400.
     */
    @Test
    public void testPUTFailure() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        testEndpointJson("/xxxx", "PUT", null, "", 400);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test the deletion of an existing occasion. Add it, then delete it.
     */
    @Test
    public void testDELETE() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        // build the json payload
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0010", 23));
        contributions.add(new Occasion.Contribution("0011", 55));
        contributions.add(new Occasion.Contribution("0012", 56));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        "0004", /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0010", /* recipient ID  */
        "9999", contributions);
        // create the initial occasion.  Need to use POST and not put it in the
        // database directly, or else the orchestrator won't know about it and will
        // throw an NPE.
        String responseString = testEndpointJson("/", "POST", occasion.toString(), "", 200);
        String id = (String) ((DBObject) JSON.parse(responseString)).get(Occasion.OCCASION_ID_KEY);
        logger.fine("id = " + id);
        DBObject dbo = collection.findOne(new BasicDBObject(Occasion.OCCASION_ID_KEY, new ObjectId(id)));
        occasion = new Occasion(dbo);
        testEndpoint("/" + id, "DELETE", "", 200);
        dbo = (BasicDBObject) collection.findOne(new BasicDBObject(Occasion.OCCASION_ID_KEY, occasion.getId()));
        replacedertTrue("DBObject should be null. Instead it was:\n\n" + dbo, null == dbo);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test the failure of the DELETE call. Expecting a response code 400.
     */
    @Test
    public void testDELETEFailure() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        testEndpoint("/xxxx", "DELETE", "", 400);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Test the ability to retrieve a list of occasions for a given group
     */
    @Test
    public void testOccasionsForGroup() {
        logger.entering(clazz, name.getMethodName(), "\n\n+ + + + + Entering " + name.getMethodName() + "\n\n");
        String groupId = "3333";
        /*
     * build the json payload for the occasions
     */
        JsonBuilderFactory factory = Json.createBuilderFactory(null);
        // collect the expected output in this
        JsonArrayBuilder resultsBuilder = factory.createArrayBuilder();
        // build the json payload for occasion 1
        List<Occasion.Contribution> contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0001", 20));
        Occasion occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-07-31", /* group ID      */
        // different ID than the others in this test so it's omitted
        "1111", // from the results
        /* interval      */
        "annual", /* occasion name */
        "John Doe's Birthday", /* organizer ID  */
        "0001", /* recipient ID  */
        "9998", contributions);
        // insert the occasion into the db
        collection.insert(occasion.toDbo());
        // occasion1 belongs to a different group. omitted from expected results
        // build the json payload for occasion 2
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("0002", 50));
        contributions.add(new Occasion.Contribution("0003", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2117-09-30", /* group ID      */
        groupId, /* interval      */
        "annual", /* occasion name */
        "Jill Doe's Birthday", /* organizer ID  */
        "0002", /* recipient ID  */
        "9997", contributions);
        // insert the occasion into the db and add the result to the expected result array
        collection.insert(occasion.toDbo());
        occasion = new Occasion(collection.findOne(occasion.toDbo()));
        resultsBuilder.add(occasion.toJson());
        // build the json payload for occasion 3
        contributions = new ArrayList<>();
        contributions.add(new Occasion.Contribution("9999", 20));
        contributions.add(new Occasion.Contribution("8888", 50));
        occasion = new Occasion(/* ID            */
        null, /* date          */
        "2018-01-31", /* group ID      */
        groupId, /* interval      */
        "annual", /* occasion name */
        "Jason Doe's Birthday", /* organizer ID  */
        "9999", /* recipient ID  */
        "9996", contributions);
        // insert the occasion into the db and add the result to the expected result array
        collection.insert(occasion.toDbo());
        occasion = new Occasion(collection.findOne(occasion.toDbo()));
        resultsBuilder.add(occasion.toJson());
        testEndpoint("/?groupId=" + groupId, "GET", resultsBuilder.build().toString(), 200);
        logger.exiting(clazz, name.getMethodName(), "\n\n- - - - - Exiting " + name.getMethodName() + "\n\n");
    }

    /**
     * Helper method for testing request success/failure
     *
     * @param endpoint the resource to call
     * @param requestType the http method to invoke
     * @param expectedOutput the response string we expect from the server to preplaced the test
     * @param expectedResponseCode the response code we expect from the server to preplaced the test
     */
    public void testEndpoint(String endpoint, String requestType, String expectedOutput, int expectedResponseCode) {
        String method = "testEndpoint";
        logger.entering(clazz, method);
        logger.fine("  endpoint: " + endpoint);
        logger.fine("  requestType: " + requestType);
        logger.fine("  expectedOutput: " + expectedOutput);
        logger.fine("  expectedResponseCode: " + expectedResponseCode);
        // build the url
        String url = occasionServiceURL + endpoint;
        logger.fine("url: " + url);
        // make the call and check the response
        Response response = sendRequest(url, requestType);
        int responseCode = response.getStatus();
        logger.fine("responseCode: " + responseCode);
        replacedertTrue("Incorrect response code: " + responseCode + "\nexpected response code: " + expectedResponseCode, responseCode == expectedResponseCode);
        String responseString = response.readEnreplacedy(String.clreplaced);
        logger.fine("testEndpoint responseString: " + responseString);
        response.close();
        replacedertTrue("Incorrect response, response is: \n\n" + responseString + "\n\n expected: \n\n" + expectedOutput + "\n\n", responseString.contains(expectedOutput));
        logger.exiting(clazz, method, "\n\n- - - - - Exiting " + method + "\n\n");
    }

    /**
     * Helper method for testing requests that are supposed to succeed
     *
     * @param endpoint the resource to call
     * @param requestType the http method to invoke
     * @param json the json payload to send
     * @param expectedOutput the response string we expect from the server to preplaced the test
     * @param expectedResponseCode the response code we expect from the server to preplaced the test
     * @return the response
     */
    public String testEndpointJson(String endpoint, String requestType, String json, String expectedOutput, int expectedResponseCode) {
        String method = "testEndpointJson";
        logger.entering(clazz, method);
        logger.fine("  endpoint: " + endpoint);
        logger.fine("  requestType: " + requestType);
        logger.fine("  json: " + json);
        logger.fine("  expectedOutput: " + expectedOutput);
        logger.fine("  expectedResponseCode: " + expectedResponseCode);
        // build url
        String url = occasionServiceURL + endpoint;
        logger.fine("url: " + url);
        String responseString = "";
        try {
            // make the call and check the response
            Response response = sendRequestJson(url, requestType, json);
            int responseCode = response.getStatus();
            logger.fine("responseCode: " + responseCode);
            replacedertTrue("Incorrect response code: " + responseCode + "\nexpected response code: " + expectedResponseCode, responseCode == expectedResponseCode);
            responseString = response.readEnreplacedy(String.clreplaced);
            response.close();
            logger.fine("testEndpointJson responseString: " + responseString);
            replacedertTrue("Incorrect response, response is: \n\n" + responseString + "\n\n expected: \n\n" + expectedOutput + "\n\n", responseString.contains(expectedOutput));
        } catch (Throwable t) {
            // some tests deliberately preplaced garbage
            replacedertTrue("In " + method + " with unexpected exception: " + t.getMessage(), t instanceof IllegalArgumentException && expectedOutput.equals("IllegalArgumentException"));
        }
        logger.exiting(clazz, method, "\n\n- - - - - Exiting " + method + " with: " + responseString + "\n\n");
        return responseString;
    }

    /**
     * Helper method to send a simple http request without a payload
     *
     * @param url the url to call
     * @param requestType the http method to invoke
     * @return the response from the server
     */
    public Response sendRequest(String url, String requestType) {
        String method = "sendRequest";
        logger.entering(clazz, method);
        logger.fine("  url: " + url);
        logger.fine("  requestType: " + requestType);
        String jwt = null;
        try {
            jwt = new JWTVerifier().createJWT("fred");
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Invocation.Builder invoBuild = target.request();
        invoBuild.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);
        Response response = invoBuild.build(requestType).invoke();
        logger.exiting(clazz, method, "\n\n- - - - - Exiting " + method + " with: " + response + "\n\n");
        return response;
    }

    /**
     * Helper method for sending requests with a json payload.
     *
     * @param url the url to call
     * @param requestType the http method to invoke
     * @param json the json payload to send
     * @return the response from the server
     */
    public Response sendRequestJson(String url, String requestType, String json) {
        String method = "sendRequestJson";
        logger.entering(clazz, method);
        logger.fine("  url: " + url);
        logger.fine("  requestType: " + requestType);
        logger.fine("  json: " + json);
        String jwt = null;
        try {
            jwt = new JWTVerifier().createJWT("fred");
        } catch (Throwable t) {
            throw new RuntimeException(t);
        }
        Client client = ClientBuilder.newClient();
        WebTarget target = client.target(url);
        Invocation.Builder invoBuild = target.request(MediaType.APPLICATION_JSON_TYPE);
        // Allowing for null payload to get a 400 response code
        Enreplacedy<String> data;
        if (null == json || json.isEmpty()) {
            data = Enreplacedy.enreplacedy("", MediaType.APPLICATION_JSON_TYPE);
        } else {
            data = Enreplacedy.enreplacedy(json, MediaType.APPLICATION_JSON_TYPE);
        }
        invoBuild.header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt);
        Response response = invoBuild.build(requestType, data).invoke();
        logger.exiting(clazz, method, "\n\n- - - - - Exiting " + method + " with: " + response.readEnreplacedy(String.clreplaced) + "\n\n");
        return response;
    }
}

17 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void deleteToken(String providerId, String lookupKey) throws OAuthStoreException {
    try {
        DBCollection col = getTokenCollection();
        col.remove(createTokenKeyHelper(providerId, lookupKey));
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on delete for OAuthToken for " + lookupKey, e);
    }
}

17 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public int countTokens(String providerId, String username, String clientId) throws OAuthStoreException {
    try {
        DBCollection col = getTokenCollection();
        BasicDBObject d = new BasicDBObject(USERNAME, username);
        d.append(PROVIDERID, providerId);
        d.append(CLIENTID, clientId);
        // mongoDB returns as a long
        return (int) col.count(d);
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on countTokens for " + username, e);
    }
}

17 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private void clearAllClients() throws Exception {
    System.out.println("clearAllClients: ");
    try {
        DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
        System.out.println("oAuth20MongoSetup Collection " + col.getName());
        col.remove(new BasicDBObject());
        DBCursor cursor = col.find();
        if (cursor != null && cursor.size() > 0) {
            if (cursor.hasNext()) {
                System.out.println("clearAllClients: table not cleared as expected, future tests may have unexpected results.");
            }
        }
    } catch (Throwable x) {
        System.out.println("clearAllClients unexpected exception" + x.getMessage());
    }
}

17 Source : oAuth20MongoSetup.java
with Eclipse Public License 1.0
from OpenLiberty

private String getSecretType(String clientId, String providerId) throws Exception {
    DBCollection col = mongoDB.getCollection(OAUTHCLIENT + uid);
    BasicDBObject d = new BasicDBObject(CLIENTID, clientId);
    d.append(PROVIDERID, providerId == null ? DEFAULT_COMPID : providerId);
    DBObject dbo = col.findOne(d);
    if (dbo == null) {
        System.out.println("getSecretType: Could not find client " + clientId + " providerId " + providerId);
        return "null_client";
    }
    String cs = (String) dbo.get(CLIENTSECRET);
    System.out.println("oAuth20MongoSetup " + cs);
    if (cs == null) {
        return "null_secret";
    } else if (cs.equals("")) {
        return "empty_secret";
    } else if (cs.startsWith("{xor}")) {
        return "xor";
    } else if (cs.startsWith("{hash}")) {
        return "hash";
    } else {
        return "plain";
    }
}

17 Source : MongoTestServlet.java
with Eclipse Public License 1.0
from OpenLiberty

public static void insert(DB db, String key, String data) throws IOException {
    System.out.println("inserting key=" + key + " data=" + data + " to dbName=" + db.getName());
    DBCollection col = db.getCollection(COLLECTION);
    BasicDBObject d = new BasicDBObject(KEY, key);
    d.append(DATA, data);
    col.insert(d);
}

17 Source : MongoTestServlet.java
with Eclipse Public License 1.0
from OpenLiberty

public static void find(DB db, String key, String expectedValue) throws IOException {
    DBCollection col = db.getCollection(COLLECTION);
    DBObject dbo = col.findOne(new BasicDBObject(KEY, key));
    String actualValue = (String) dbo.get(DATA);
    System.out.println("found key=" + key + " value=" + actualValue + " from dbName=" + db.getName());
    replacedertEquals(expectedValue, actualValue);
}

17 Source : MongoWrapper.java
with GNU General Public License v3.0
from NightscoutFoundation

// Unfortunately, this also throws other exceptions that are not doreplacedetned...
public DBCollection openMongoDb() throws UnknownHostException {
    MongoClientURI dbUri = new MongoClientURI(dbUriStr_ + "?socketTimeoutMS=180000");
    mongoClient_ = new MongoClient(dbUri);
    DB db = mongoClient_.getDB(dbName_);
    DBCollection coll = db.getCollection(collection_);
    // create index on "i", ascending
    coll.createIndex(new BasicDBObject(index_, 1));
    return coll;
}

17 Source : PokemonMaster.java
with Apache License 2.0
from newrelic

@Trace
public DBObject demoFindOne(String type) throws InterruptedException {
    DB db = mongoClient.getDB(dbName);
    DBCollection coll = db.getCollection(collectionName);
    BasicDBObject query = new BasicDBObject("type", type);
    return coll.findOne(query);
}

17 Source : PokemonMaster.java
with Apache License 2.0
from newrelic

@Trace
public DBObject demoFindAndModify(String type) throws InterruptedException {
    DB db = mongoClient.getDB(dbName);
    DBCollection coll = db.getCollection(collectionName);
    BasicDBObject query = new BasicDBObject("type", type);
    return coll.findAndModify(query, new BasicDBObject("type", "ice"));
}

17 Source : MongodbInputDiscoverFieldsImpl.java
with Apache License 2.0
from apache

private static Iterator<DBObject> setUpPipelineSample(String query, int numDocsToSample, DBCollection collection) throws HopException {
    query = query + ", {$limit : " + numDocsToSample + "}";
    List<DBObject> samplePipe = jsonPipelineToDBObjectList(query);
    Cursor cursor = collection.aggregate(samplePipe, AggregationOptions.builder().build());
    return cursor;
}

17 Source : MongoDBStore.java
with Apache License 2.0
from apache

@Override
public Role removeRole(String roleName) throws MongoException {
    DBCollection coll = getCollection();
    Role role = getRole(roleName);
    if (role == null) {
        return null;
    }
    WriteResult result = coll.remove(getTemplateObject(role));
    if (result.getLastError() != null) {
        result.getLastError().throwOnError();
    }
    return role;
}

17 Source : MongoExecutor.java
with Apache License 2.0
from 597365581

public Attribute[] getSchema(SourceDatabase database, SourceTable table, DBCollection collection, HashMap<String, Subtable> subtables) {
    Attribute[] ret = null;
    int count = this.numberToSample(collection);
    if (count != -1) {
        ret = guessFromRandomRecords(collection, database, table, this.numberToSample(collection), subtables);
    } else {
        ret = guessFromAllRecords(collection, database, table, subtables);
    }
    return ret;
}

16 Source : DeleteVo.java
with GNU General Public License v3.0
from xsonorg

public int delete(DBCollection collection, WriteConcern writeConcern) {
    DBObject query = new BasicDBObject();
    if (null != condition) {
        this.condition.setQuery(query, null);
    }
    log(query);
    // WriteResult result = collection.remove(query, WriteConcern.ACKNOWLEDGED);
    WriteResult result = collection.remove(query, writeConcern);
    // collection.remove(query)
    // System.out.println(query.toString());
    return result.getN();
}

16 Source : MongoActuator.java
with GNU General Public License v3.0
from xsonorg

// public InsertReturn insertReturn(String dsKey, String sql) {
// InsertVo insertVo = (InsertVo) sqlParser.parse(sql);
// DBCollection collection = MongoSupport.getCollection(dsKey, insertVo.getTable());
// int rowCount = insertVo.insert(collection);
// return new InsertReturn(rowCount, null);
// // DBCollection collection = db.getCollection("user");
// // DBObject object = new BasicDBObject();
// // object.put("name", "aaa");
// // object.put("age", 11);
// // collection.save(object);搜索
// // System.out.println(object.get("_id"));
// // /ObjectId id = (ObjectId)doc.get( "_id" );
// }
public int update(String dsKey, String sql) {
    UpdateVo updateVo = (UpdateVo) sqlParser.parse(sql);
    DBCollection collection = MongoSupport.getCollection(dsKey, updateVo.getTable());
    return updateVo.update(collection, MongoSupport.getDefaultWriteConcern(dsKey));
}

16 Source : MongoDataHandler.java
with Apache License 2.0
from wso2

/**
 * This method reads the data for a given collection.
 * Returns a list of DataEntry objects.
 *
 * @param tableName Name of the table
 * @return EnreplacedyCollection
 * @see DataEntry
 */
@Override
public List<ODataEntry> readTable(String tableName) {
    List<ODataEntry> entryList = new ArrayList<>();
    DBCollection readResult = jongo.getDatabase().getCollection(tableName);
    Iterator<DBObject> cursor = readResult.find();
    DBObject doreplacedentData;
    String tempValue;
    while (cursor.hasNext()) {
        ODataEntry dataEntry;
        doreplacedentData = cursor.next();
        tempValue = doreplacedentData.toString();
        Iterator<?> keys = new JSONObject(tempValue).keys();
        dataEntry = createDataEntryFromResult(tempValue, keys);
        // Set Etag to the enreplacedy
        dataEntry.addValue(ETAG, ODataUtils.generateETag(this.configId, tableName, dataEntry));
        entryList.add(dataEntry);
    }
    return entryList;
}

16 Source : MarcMongodbClientTest.java
with GNU General Public License v3.0
from pkiraly

// @Test
public synchronized void testImport() throws URISyntaxException, IOException, InterruptedException {
    MarcMongodbClient client = new MarcMongodbClient("localhost", 27017, "sub_last_print");
    DBCollection collection = client.getCollection("marc");
    replacedertEquals(0, collection.count());
    boolean insert = true;
    if (insert) {
        JsonPathCache<? extends XmlFieldInstance> cache;
        List<String> records = FileUtils.readLines("general/marc.json");
        for (String record : records) {
            cache = new JsonPathCache<>(record);
            Object jsonObject = jsonProvider.parse(record);
            String id = cache.get("$.controlfield.[?(@.tag == '001')].content").get(0).getValue();
            String x003 = cache.get("$.controlfield.[?(@.tag == '003')].content").get(0).getValue();
            BasicDBObject doc = new BasicDBObject("type", "marcjson").append("id", id).append("x003", x003).append("record", record);
            collection.insert(doc);
        }
        replacedertEquals(674, collection.count());
    }
    collection.remove(new BasicDBObject("type", "marcjson"));
    replacedertEquals(0, collection.count());
}

16 Source : MongoAdminService.java
with Apache License 2.0
from PaaS-TA

public DB createDatabase(String databaseName) throws MongoServiceException {
    try {
        DB db = client.getDB(databaseName);
        // save into a collection to force DB creation.
        DBCollection col = db.createCollection("foo", null);
        BasicDBObject obj = new BasicDBObject();
        obj.put("foo", "bar");
        col.insert(obj);
        // drop the collection so the db is empty
        col.drop();
        return db;
    } catch (MongoException e) {
        // try to clean up and fail
        try {
            deleteDatabase(databaseName);
        } catch (MongoServiceException ignore) {
        }
        throw handleException(e);
    }
}

16 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void create(OAuthClient oauthClient) throws OAuthStoreException {
    for (int i = 0; i < RETRY_COUNT; i++) {
        try {
            DBCollection col = getClientCollection();
            col.insert(createClientDBObjectHelper(oauthClient));
        } catch (Exception e) {
            if (i < RETRY_COUNT && isNetworkFailure(e)) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e1) {
                }
            } else {
                throw new OAuthStoreException("Failed to process create on OAuthClient " + oauthClient.getClientId(), e);
            }
        }
    }
}

16 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void deleteConsent(String providerId, String username, String clientId, String resource) throws OAuthStoreException {
    try {
        DBCollection col = getConsentCollection();
        BasicDBObject db = new BasicDBObject(CLIENTID, clientId);
        db.put(USERNAME, username);
        db.put(PROVIDERID, providerId);
        db.put(RESOURCE, resource);
        col.remove(db);
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on delete for Consent for " + username, e);
    }
}

16 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void update(OAuthToken oauthToken) throws OAuthStoreException {
    try {
        DBCollection col = getTokenCollection();
        col.update(createTokenKeyHelper(oauthToken), createTokenDBObjectHelper(oauthToken), false, false);
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on update for OAuthToken for " + oauthToken.getClientId(), e);
    }
}

16 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void deleteConsents(String providerId, long timestamp) throws OAuthStoreException {
    try {
        DBCollection col = getConsentCollection();
        BasicDBObject query = new BasicDBObject();
        query.put(EXPIRES, new BasicDBObject("$lt", timestamp));
        query.put(PROVIDERID, providerId);
        col.remove(query);
    } catch (Exception e) {
        throw new OAuthStoreException("Failed on deleteConsents for time after " + timestamp, e);
    }
}

16 Source : CustomStoreSample.java
with Eclipse Public License 1.0
from OpenLiberty

@Override
public void create(OAuthConsent oauthConsent) throws OAuthStoreException {
    try {
        DBCollection col = getConsentCollection();
        col.insert(createConsentDBObjectHelper(oauthConsent));
    } catch (Exception e) {
        throw new OAuthStoreException("Failed to process create on OAuthConsent " + oauthConsent.getClientId(), e);
    }
}

See More Examples