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.

Arshad Ali
  • 3,082
  • 12
  • 56
  • 99

3 Answers3

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.

Shaggy
  • 596
  • 1
  • 6
  • 15
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.

Arshad Ali
  • 3,082
  • 12
  • 56
  • 99
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();