0

I have following code

public class UserDAO {
    private final MongoCollection<Document> usersCollection;
    private Random random = new SecureRandom();

    public UserDAO(final MongoDatabase blogDatabase) {
        usersCollection = blogDatabase.getCollection("users");
    }

    public boolean addUser(String username, String password, String email) {

        String passwordHash = makePasswordHash(password, Integer.toString(random.nextInt()));    

        Document doc = new Document("_id", username).append("password", passwordHash);

        if (email != null && !email.equals("")) {

            doc = new Document("_id", username)
            .append("password", passwordHash)
            .append("email", email);
        }

        try {

            usersCollection.insertOne(doc);             
             return true;
        } catch (MongoWriteException e) {
            if (e.getError().getCategory().equals(ErrorCategory.DUPLICATE_KEY)) {
                System.out.println("Username already in use: " + username);
                return false;
            }
            throw e;
        }
    }

    public Document validateLogin(String username, String password) {
        Document user = null;   

        user = (Document) usersCollection.find(new BasicDBObject("_id", username));// at this line I'm getting error
        if (user == null) {
            System.out.println("User not in database");
            return null;
        }

        String hashedAndSalted = user.get("password").toString();

        String salt = hashedAndSalted.split(",")[1];

        if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
            System.out.println("Submitted password is not a match");
            return null;
        }

        return user;
    }    

}

I want to get one document/record but I'm getting error

java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be cast to org
.bson.Document
        at course.UserDAO.validateLogin(UserDAO.java:94)
        at course.BlogController$6.doHandle(BlogController.java:231)
        at course.BlogController$FreemarkerBasedRoute.handle(BlogController.java
:92)
        at spark.webserver.MatcherFilter.doFilter(MatcherFilter.java:139)
        at spark.webserver.JettyHandler.doHandle(JettyHandler.java:54)
        at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandle
r.java:179)
        at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.j
ava:136)
        at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper
.java:97)
        at org.eclipse.jetty.server.Server.handle(Server.java:451)
        at org.eclipse.jetty.server.HttpChannel.run(HttpChannel.java:252)
        at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.jav
a:266)
        at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConn
ection.java:240)
        at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPoo
l.java:596)
        at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool
.java:527)
        at java.lang.Thread.run(Thread.java:745)

are there any mistakes in my code, any solutions.

3
  • Where is the exception thrown. Commented Mar 27, 2016 at 12:08
  • at line user = (Document) usersCollection.find(new BasicDBObject("_id", username)); in code given above! Commented Mar 27, 2016 at 12:10
  • 2
    Possible duplicate of find in MongoCollection<Document> Commented Mar 27, 2016 at 12:13

3 Answers 3

1

You can do this also:

Document user = null;
user = usersCollection.find(eq("_id", username)).first();

use Filter.eq() to compare the equality of the username, If you have used import static com.mongodb.client.model.Filters.eq; then only use eq() method.
And use first() it returns the first Document from the collection.

Sign up to request clarification or add additional context in comments.

Comments

0

OK I've found this answer that is make some changes in validateLogin() as

public Document validateLogin(String username, String password) {
        FindIterable<Document> user = null; // Change to get the object of FindIterable<Document>

        user = usersCollection.find(new Document("_id", username) );// give Document as the find() argument
        if (user == null) {
            System.out.println("User not in database");
            return null;
        }

        String hashedAndSalted = user.first().get("password").toString();// get user.first()

        String salt = hashedAndSalted.split(",")[1];

        if (!hashedAndSalted.equals(makePasswordHash(password, salt))) {
            System.out.println("Submitted password is not a match");
            return null;
        }

        return user.first();//get user.first()
    }

hence the issue is resolved.

Comments

0

by just adding first() to your search query will save you all the trouble.

    Bson filter = new Document("_id",username);
    Document user = coll.find().filter(filter).first();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.