pt.ua.cbd.cbd_project.service.BookServiceMongo.java Source code

Java tutorial

Introduction

Here is the source code for pt.ua.cbd.cbd_project.service.BookServiceMongo.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.ua.cbd.cbd_project.service;

import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoDatabase;
import org.json.JSONObject;
import pt.ua.cbd.cbd_project.database.MongoDatabaseConnector;
import pt.ua.cbd.cbd_project.model.Book;
import pt.ua.cbd.cbd_project.model.BookAuthors;
import org.bson.Document;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;

import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.bson.conversions.Bson;

/**
 *
 * @author Maciek
 */
public class BookServiceMongo {

    private final MongoDatabaseConnector mdbc = new MongoDatabaseConnector();
    private MongoDatabase db = mdbc.connect();
    final static Logger logger = Logger.getLogger(BookServiceMongo.class);

    public Book getBookById(int id) {
        BasicDBObject bookId = new BasicDBObject();
        bookId.put("id", id);

        try {
            Document d = this.db.getCollection("book").find(bookId).first();
            Book book = new Book();

            //get authors list
            int index = 0;
            ArrayList<Document> bookAuthors = (ArrayList) d.get("authors"); //get all authors for this.book
            BookAuthors ba[] = new BookAuthors[bookAuthors.size()];
            for (Document doc : bookAuthors) {
                BookAuthors singleAuthor = new BookAuthors();
                singleAuthor.setName(doc.getString("name"));
                singleAuthor.setSurname(doc.getString("surname"));
                ba[index] = singleAuthor;
                index++;
            }

            book.setAuthors(ba);
            book.setId(d.getInteger("id"));
            book.setTitle(d.getString("title"));
            book.setAddToLibraryDate(d.getString("addToLibraryDate"));

            return book;
        } catch (Exception e) {
            return null;
        }

    }

    public List<Book> getBooks(String title) {
        List<Book> bookList = new ArrayList<Book>();
        BasicDBObject likeTitle = new BasicDBObject();
        likeTitle.put("title", Pattern.compile(title, Pattern.CASE_INSENSITIVE));

        FindIterable<Document> iterable = this.db.getCollection("book").find(likeTitle).limit(30);
        iterable.forEach(new Block<Document>() {
            @Override
            public void apply(final Document document) {
                Book book = new Book();

                //get authors list
                ArrayList<BookAuthors> bookAuthorsList = new ArrayList<>();
                ArrayList<Document> singleBookAuthorsList = new ArrayList<>();
                singleBookAuthorsList = (ArrayList) document.get("authors"); //get all authors for this.book
                singleBookAuthorsList.stream().forEach((Document d) -> {
                    BookAuthors ba = new BookAuthors();
                    ba.setName(d.getString("name"));
                    ba.setSurname(d.getString("surname"));
                    bookAuthorsList.add(ba);
                });
                BookAuthors bookAuthors[] = bookAuthorsList.toArray(new BookAuthors[bookAuthorsList.size()]);
                book.setAuthors(bookAuthors);
                book.setId(document.getInteger("id"));
                book.setTitle(document.getString("title"));
                book.setAddToLibraryDate(document.getString("addToLibraryDate"));
                bookList.add(book);
            }
        });
        return bookList;
    }

    public Book addNewBook(Book book) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("authors", book.getAuthorsArray());
        jsonObject.put("id", book.getId());
        jsonObject.put("title", book.getTitle());
        jsonObject.put("addToLibraryDate", book.getAddToLibraryDate());

        String jsonFormattedString = jsonObject.toString().replaceAll("\\\\", "");
        BasicDBObject dbObject = (BasicDBObject.parse(jsonFormattedString));
        MongoCollection<BasicDBObject> coll = db.getCollection("book", BasicDBObject.class);
        coll.insertOne(dbObject);
        return book;
    }

    public boolean deleteBook(Book book) {
        BasicDBObject bookId = new BasicDBObject();
        bookId.put("id", book.getId()); //to be sure that books exists
        this.db.getCollection("book").findOneAndDelete(bookId);
        return true;
    }

    public Book editBook(Book book) {

        deleteBook(book);
        return addNewBook(book);
    }

}