Example usage for com.mongodb Block Block

List of usage examples for com.mongodb Block Block

Introduction

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

Prototype

Block

Source Link

Usage

From source file:com.DA.assignment1.Query.Question3.java

public void Answer() {

    //find MovieID
    FindIterable<Document> movieID = db.getCollection("movies")
            .find(eq("title", "2001: A Space Odyssey (1968)"));
    movieID.forEach(new Block<Document>() {
        @Override/*www .j a  va  2  s .  c om*/
        public void apply(final Document document) {
            // String Mytitle =document;
            //System.out.println("hah");
            String MymovieID = document.getString("movieID");

            findTag(MymovieID);

        }
    });

}

From source file:com.DA.assignment1.Query.Question3.java

public void findTag(String movieID) {

    //find tags/*from   ww w  . j  a v  a  2  s .c o m*/
    FindIterable<Document> userID = db.getCollection("tags")
            .find(and(eq("userID", "146"), eq("movieID", movieID)));
    userID.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            // String Mytitle =document;
            //System.out.println("hah");
            String tags = document.getString("tag");

            System.out.println(tags);

        }
    });

}

From source file:com.DA.assignment1.Query.Question4.java

public void Answer() {

    AggregateIterable<Document> iterable = db.getCollection("ratings")
            .aggregate(asList(//from   w  ww.j a  v  a 2 s  . co m
                    new Document("$group",
                            new Document("_id", "$movieID").append("AVR_Rating",
                                    new Document("$avg", "$rating"))),
                    new Document("$sort", new Document("AVR_Rating", -1))));

    iterable.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {
            String movie_id = document.getString("_id");
            double rating = document.getDouble("AVR_Rating");
            System.out.print("Movie_id: " + movie_id + "  Rating: " + rating + "  Title: ");
            findMovie(movie_id);
            //  System.out.println(document);
        }
    });
}

From source file:com.DA.assignment1.Query.Question4.java

public void findMovie(String MymovieID) {

    //String MyRating =document.getString("AVR_Rating");

    FindIterable<Document> userID = db.getCollection("movies").find(eq("movieID", MymovieID));
    userID.forEach(new Block<Document>() {
        @Override/*from  ww w  .  j ava2s  .  co m*/
        public void apply(final Document document) {
            // String Mytitle =document;
            //System.out.println("hah");
            String titles = document.getString("title");

            System.out.println(titles);

        }
    });

}

From source file:com.imos.sample.NewClass.java

public static void main(String[] args) {
    try {/*w ww.j a v  a 2  s. com*/
        MongoClient mongoClient = new MongoClient();
        MongoDatabase db = mongoClient.getDatabase("test");

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

        Document address = new Document().append("street", "2 Avenue").append("zipcode", "10075")
                .append("building", "1480").append("coord", asList(-73.9557413, 40.7720266));

        db.getCollection("restaurants")
                .insertOne(
                        new Document("address", address)
                                .append("borough",
                                        "Manhattan")
                                .append("cuisine",
                                        "Italian")
                                .append("grades", asList(
                                        new Document().append("date", format.parse("2014-10-01T00:00:00Z"))
                                                .append("grade", "A").append("score", 11),
                                        new Document().append("date", format.parse("2014-01-16T00:00:00Z"))
                                                .append("grade", "B").append("score", 17)))
                                .append("name", "Vella").append("restaurant_id", "41704620"));

        FindIterable<Document> iterable = db.getCollection("restaurants").find();

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });

        db.getCollection("restaurants").updateOne(address, new Document()
                //                    .append("street", "5th Avenue")
                .append("zipcode", "10075").append("building", "1480")
                .append("coord", asList(-73.9557413, 40.7720266)));

        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                System.out.println(document);
            }
        });

    } catch (ParseException ex) {
        Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.left8.evs.utilities.dsretriever.MongoHandler.java

License:Open Source License

/**
 * Retrieves all stored retrievedTweets in MongoDB Store.
 * @return A List containing all retrieved retrievedTweets
 *//*from w w  w  .j  a v a  2 s.c  o m*/
public final List<Tweet> retrieveAllTweetsFiltered() {
    List<Tweet> retrievedTweets = new ArrayList<>();
    if (langFilter.equals("no_filter")) {
        Utilities.printMessageln("No language filter was applied. Retrieving " + "all tweets, unfiltered.");
    }

    MongoCollection<Document> collection = db.getCollection(config.getRawTweetsCollectionName());

    try {
        FindIterable<Document> iterable = collection.find(); //Load all documents
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document tweetDoc) {
                if (langFilter.equals("no_filter")
                        || tweetDoc.getString(config.getLanguageFieldName()).equals(langFilter)) {
                    //Get tweet ID
                    long id = tweetDoc.getLong(config.getTweetIdFieldName());
                    Document user = tweetDoc.get(config.getUserDocumentFieldName(), Document.class); //Get the embedded document

                    //User details
                    String username = user.getString(config.getUsernameFieldName()); //Name
                    long userId; //User ID
                    try {
                        userId = user.getLong(config.getUserIdFieldName());
                    } catch (ClassCastException e) {
                        userId = user.getInteger(config.getUserIdFieldName());
                    }

                    //Tweet text, date and language
                    String text = tweetDoc.getString(config.getTextFieldName());
                    Date date = tweetDoc.getDate(config.getDateFieldName());
                    String language = tweetDoc.getString(config.getLanguageFieldName());

                    //Coordinates
                    Document coordinates = tweetDoc.get(config.getCoordinatesDocumentFieldName(),
                            Document.class);
                    double latitude = -1;
                    double longitude = -1;
                    if (coordinates != null) {
                        try {
                            List<Double> coords = coordinates.get(config.getCoordinatesDocumentFieldName(),
                                    ArrayList.class);
                            latitude = coords.get(0);
                            longitude = coords.get(1);
                        } catch (ClassCastException e) { //Case where data where incorrectly casted as integers
                            List<Integer> coords = coordinates.get(config.getCoordinatesDocumentFieldName(),
                                    ArrayList.class);
                            latitude = coords.get(0);
                            longitude = coords.get(1);
                        }
                    }

                    //Number of retweets and favorites
                    int numberOfRetweets = tweetDoc.getInteger(config.getRetweetsCountFieldName());
                    int numberOfFavorites = tweetDoc.getInteger(config.getFavoritesCountFieldName());
                    boolean isFavorited = tweetDoc.getBoolean(config.getFavoritedFieldName());
                    boolean isRetweeted = tweetDoc.getBoolean(config.getRetweetedFieldName());
                    long retweetId;

                    //Retweet status
                    boolean isRetweet;
                    try {
                        Document retweetStatus = tweetDoc.get(config.getRetweetedStatusDocumentFieldName(),
                                Document.class);
                        isRetweet = true;
                        try {
                            retweetId = retweetStatus.getLong(config.getRetweetIdFieldName());
                        } catch (ClassCastException e) {
                            retweetId = retweetStatus.getInteger(config.getRetweetIdFieldName());
                        }
                    } catch (NullPointerException e) {
                        isRetweet = false;
                        retweetId = -1;
                    }

                    int stanfordSentiment;
                    try {
                        stanfordSentiment = tweetDoc.getInteger(config.getStanfordSentimentName());
                    } catch (NullPointerException e) {
                        stanfordSentiment = -1;
                    }

                    int naiveBayesSentiment;
                    try {
                        naiveBayesSentiment = tweetDoc.getInteger(config.getNaiveBayesSentimentName());
                    } catch (NullPointerException e) {
                        naiveBayesSentiment = -10;
                    }

                    int bayesianNetSentiment;
                    try {
                        bayesianNetSentiment = tweetDoc.getInteger(config.getBayesianNetSentimentName());
                    } catch (NullPointerException e) {
                        bayesianNetSentiment = -10;
                    }

                    int posEmot, negEmot;
                    try {
                        posEmot = tweetDoc.getInteger(config.getPositiveEmoticonFieldName());
                        negEmot = tweetDoc.getInteger(config.getNegativeEmoticonFieldName());
                    } catch (NullPointerException e) {
                        posEmot = 0;
                        negEmot = 0;
                    }

                    Tweet tweet = new Tweet(id, username, userId, text, date, latitude, longitude,
                            numberOfRetweets, numberOfFavorites, isRetweet, isFavorited, isRetweeted, language,
                            retweetId, stanfordSentiment, posEmot, negEmot, naiveBayesSentiment,
                            bayesianNetSentiment);

                    retrievedTweets.add(tweet);
                }
            }
        });
        return retrievedTweets;
    } catch (MongoException e) {
        Utilities.printMessageln("Cannot find documents in MongoDB Store.");
        Logger.getLogger(MongoHandler.class.getName()).log(Level.SEVERE, null, e);
        return null;
    }
}

From source file:com.mlveda.dori.AddPageWebhook.java

private PageArray getPagesData(PageArray pages, String shopName) {

    MongoDatabase db = MongoProvider.getInstance();

    FindIterable<Document> collection = db.getCollection("facebook_pages").find(eq("shop_name", shopName));
    final ArrayList<PagesInsertData> pageList = new ArrayList<>();

    System.out.println();//  w  w  w  .  j  ava  2 s . co  m
    System.out.println();

    //        System.out.println("document: " + document);
    collection.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {

            pageList.add(gson.fromJson(gson.toJson(document), PagesInsertData.class));

        }
    });
    //        BasicDBObject document = new BasicDBObject();
    //        QueryBuilder qb = new QueryBuilder().put("shop_name").is(shopName);
    ////        qb.or(new QueryBuilder().put("shop_name").is(shopName).get(), new QueryBuilder().put("published_at").notEquals(null).get());
    //        document.putAll(qb.get());

    // convert JSON to DBObject directly
    //            Document document = new Document("array", JSON.parse(gson.toJson(pages.getData())), new JSONCallback());
    DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);

    ArrayList<PagesInsertData> responseObject = new ArrayList<>();

    if (pages.getData().isEmpty()) {
        return new PageArray(responseObject, false);
    }

    for (PagesInsertData page : pages.getData()) {
        boolean found = false;

        page.setCreatedAt(format.format(Calendar.getInstance().getTime()));
        page.setUpdatedAt(format.format(Calendar.getInstance().getTime()));
        page.setShopName(shopName);

        Document document = Document.parse(gson.toJson(page));

        for (PagesInsertData facebookPage : pageList) {

            System.out.println("facebook id: " + facebookPage.getId() + " page id: " + page.getId());
            if (facebookPage.getId().equalsIgnoreCase(page.getId())) {
                System.out.println("facebook id: " + facebookPage.getId() + " page id: " + page.getId());
                page.setInstalled(facebookPage.isInstalled());
                page.setCreatedAt(facebookPage.getCreatedAt());

                document = Document.parse(gson.toJson(page));
                found = true;
                //                    break;
            }

        }

        if (found) {
            found = false;
            db.getCollection("facebook_pages").updateOne(new Document("id", page.getId()),
                    new Document("$set", document));
        } else {
            db.getCollection("facebook_pages").insertOne(document);
        }

        responseObject.add(page);

        //            collection.insertOne(document);
    }

    return new PageArray(responseObject, true);

}

From source file:com.mlveda.dori.Webhook.java

public ArrayList<Collection> getCollectionList() {

    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    BasicDBObject document = new BasicDBObject();
    QueryBuilder qb = new QueryBuilder();
    qb.or(new QueryBuilder().put("handle").notEquals("frontpage").get(),
            new QueryBuilder().put("published_at").notEquals(null).get());
    document.putAll(qb.get());/*from   w  w w  .ja  v  a 2 s.  c  o  m*/

    FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collections")
            .find(and(ne("title", "Frontpage"), ne("published_at", null)));
    //        FindIterable<Document> coll = db.getCollection("disneytoys.myshopify.com_collection").find(document);

    //        FindIterable<Document> foundDocument = coll.find(and(ne("title", "Frontpage"), ne("published_at", null)));
    final Type collectionType = new TypeToken<ArrayList<Collection>>() {
    }.getType();

    final ArrayList<Collection> collection = new ArrayList<>();

    System.out.println();
    System.out.println();

    System.out.println("document: " + document);
    coll.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {

            collection.add(gson.fromJson(gson.toJson(document), Collection.class));

            //                System.out.println("document: " + document);
            //                ArrayList<Collection> c = gson.fromJson(gson.toJson(document.get("collections")), collectionType);
            //                System.out.println("collection: " + c);
            //                if (!c.isEmpty()) {
            //                    collection.addAll(c);
            //                }
            //                collection.add(t);
        }
    });
    System.out.println("Collection: " + gson.toJson(collection));
    System.out.println();
    System.out.println();

    return collection;
}

From source file:com.mlveda.dori.Webhook.java

private ArrayList<Product> getProducts(long collectionID) {
    MongoDatabase db = MongoProvider.getInstance();

    //        MongoCollection<Product> products = db.getCollection("disneytoys.myshopify.com_products", Product.class);
    System.out.println("collectionID: " + collectionID);

    FindIterable<Document> coll = db.getCollection("dakshal.myshopify.com_collects")
            .find(eq("collection_id", collectionID));

    final Type collectionType = new TypeToken<ArrayList<ProductCollectionMapping>>() {
    }.getType();/*from   w w  w. ja  v a 2  s .  com*/
    final Type productType = new TypeToken<ArrayList<Product>>() {
    }.getType();

    final ArrayList<ProductCollectionMapping> map = new ArrayList<>();
    final ArrayList<Product> products = new ArrayList<>();

    System.out.println();
    System.out.println("coll: " + coll.first());
    System.out.println();

    coll.forEach(new Block<Document>() {
        @Override
        public void apply(Document document) {
            map.add(gson.fromJson(gson.toJson(document), ProductCollectionMapping.class));
            //                System.out.println("document is: " + gson.toJson(document));
            //                ArrayList<ProductCollectionMapping> c = gson.fromJson(gson.toJson(document.get("collects")), collectionType);
            //                System.out.println(c);
            //                map.addAll(c);
            //                collection.add(t);
        }
    });

    System.out.println();
    System.out.println("map: " + map.size());
    System.out.println();

    for (ProductCollectionMapping pcm : map) {
        System.out.println("productID: " + pcm.getProductId());
        FindIterable<Document> prod = db.getCollection("dakshal.myshopify.com_products")
                .find(eq("id", pcm.getProductId()));
        System.out.println();
        System.out.println("prod: " + prod.toString());
        System.out.println();
        prod.forEach(new Block<Document>() {
            @Override
            public void apply(Document document) {
                Product prod = gson.fromJson(gson.toJson(document), Product.class);
                if (!products.contains(prod)) {
                    products.add(prod);
                }
                //                    System.out.println(gson.toJson(document));
                //                    ArrayList<Product> c = gson.fromJson(gson.toJson(document.get("collects")), productType);
                //                    System.out.println(c);
                //                    products.addAll(c);
                //                collection.add(t);
            }
        });
    }

    System.out.println();
    System.out.println();

    System.out.println("productlist: " + gson.toJson(products));

    return products;
}

From source file:com.mycompany.mongodb.tweet.SimpleClient.java

public boolean handleCommand(String command) {
    boolean exit = false;
    String split[] = command.split(" ", 2);

    if (split[0].equals("register") && split.length == 2) {
        String s[] = split[1].split(" ");
        if (s.length == 2) {
            String username = split[1].split(" ")[0];
            String password = split[1].split(" ")[1];
            FindIterable<Document> iterable = db.getCollection("users").find(eq("username", username));
            Document doc = iterable.first();
            if (doc == null) {
                db.getCollection("users")
                        .insertOne(new Document().append("username", username).append("password", password));
                System.out.println(username + " successfully registered");
            } else {
                System.out.println("Username already exist");
            }/*w w w  . j  ava 2  s. c om*/
        } else {
            System.out.println("Usage : register <username> <password>");
        }
    } else if (split[0].equals("login") && split.length == 2) {
        String s[] = split[1].split(" ");
        if (s.length == 2) {
            String username = split[1].split(" ")[0];
            String password = split[1].split(" ")[1];
            FindIterable<Document> iterable = db.getCollection("users")
                    .find(and(eq("username", username), eq("password", password)));
            Document doc = iterable.first();
            if (doc != null) {
                user = username;
                System.out.println("Hello, " + user + " !");
            } else {
                System.out.println("Wrong password");
            }
        } else {
            System.out.println("Usage : login <username> <password>");
        }
    } else if (split[0].equals("follow") && split.length == 2) {
        if (user != null) {
            String tofollow = split[1];

            FindIterable<Document> iterable = db.getCollection("users").find(eq("username", tofollow));
            Document doc = iterable.first();
            if (doc != null) {
                db.getCollection("users").updateOne(new Document("username", user),
                        new Document("$addToSet", new Document("friends", tofollow)));
                db.getCollection("users").updateOne(new Document("username", tofollow),
                        new Document("$addToSet", new Document("followers", user)));
                System.out.println("Successfully follow " + tofollow);
            } else {
                System.out.println("No user with username " + tofollow);
            }
        } else {
            System.out.println("Please login first");
        }
    } else if (split[0].equals("tweet") && split.length == 2) {
        if (user != null) {
            final String tweetBody = split[1];
            final Date date = new Date();
            db.getCollection("users").updateOne(new Document("username", user),
                    new Document("$push", new Document("tweets",
                            new Document().append("body", tweetBody).append("timestamp", date.toString()))));
            db.getCollection("users").updateOne(new Document("username", user),
                    new Document("$push", new Document("timeline", new Document("username", user)
                            .append("body", tweetBody).append("timestamp", date.toString()))));
            FindIterable<Document> iterables = db.getCollection("users").find(eq("username", user));
            iterables.forEach(new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    final ArrayList<String> followers = (ArrayList<String>) document.get("followers");
                    if (followers != null)
                        for (String follower : followers) {
                            db.getCollection("users").updateOne(new Document("username", follower),
                                    new Document("$push",
                                            new Document("timeline",
                                                    new Document("username", user).append("body", tweetBody)
                                                            .append("timestamp", date.toString()))));
                        }
                }
            });
        } else {
            System.out.println("Please login first");
        }
    } else if (split[0].equals("showuserline") && split.length == 2) {
        if (user != null) {
            final String toView = split[1];
            FindIterable<Document> iterable = db.getCollection("users").find(eq("username", toView));
            iterable.forEach(new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    final ArrayList<Document> documents = (ArrayList<Document>) document.get("tweets");
                    if (documents != null)
                        for (int i = documents.size() - 1; i >= 0; i--) {
                            Document d = documents.get(i);
                            System.out.println(toView + " : " + d.getString("body"));
                        }
                }
            });
        } else {
            System.out.println("Please login first");
        }
    } else if (split[0].equals("showtimeline")) {
        if (user != null) {
            FindIterable<Document> iterable = db.getCollection("users").find(eq("username", user));
            iterable.forEach(new Block<Document>() {
                @Override
                public void apply(final Document document) {
                    final ArrayList<Document> documents = (ArrayList<Document>) document.get("timeline");
                    if (documents != null)
                        for (int i = documents.size() - 1; i >= 0; i--) {
                            Document d = documents.get(i);
                            System.out.println(d.getString("username") + " : " + d.getString("body"));
                        }
                }
            });
        } else {
            System.out.println("Please login first");
        }
    } else if (split[0].equalsIgnoreCase("exit")) {
        exit = true;
    } else {
        printUsage();
    }
    return exit;
}