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

Java tutorial

Introduction

Here is the source code for pt.ua.cbd.cbd_project.service.BookService.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.google.gson.Gson;
import java.io.IOException;
import static java.lang.Math.toIntExact;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.log4j.Logger;
import java.util.List;
import java.util.UUID;
import org.json.JSONException;
import org.json.JSONObject;
import pt.ua.cbd.cbd_project.database.JsonDatabaseConnector;
import pt.ua.cbd.cbd_project.model.Book;
import pt.ua.cbd.cbd_project.model.BookAuthors;

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

    final static Logger logger = Logger.getLogger(BookService.class);
    private JsonDatabaseConnector j = new JsonDatabaseConnector();
    private Gson gson = new Gson();

    public Book getBookById(int id) {
        String query = "SELECT \n" + "JSON_VALUE(f.doc, '$.id') as id,\n"
                + "JSON_VALUE(f.doc, '$.title') as title,\n" + "JSON_QUERY(f.doc, '$.authors') as authors,\n"
                + "JSON_VALUE(f.doc, '$.creationDate') as creationDate,\n"
                + "JSON_VALUE(f.doc, '$.isAvailable') as isAvailable,\n"
                + "JSON_VALUE(f.doc, '$.addToLibraryDate') as addToLibraryDate\n" + "FROM Book f "
                + "WHERE JSON_VALUE(f.doc, '$.id') = '" + id + "'";
        try {
            j.connect();
            ResultSet rs = j.viewTable(query);
            Book book = new Book();
            if (!rs.next()) {
                return null;
            }
            rs.previous();
            while (rs.next()) {

                book.setId(rs.getInt("id"));
                book.setTitle(rs.getString("title"));
                book.setCreationDate(rs.getString("creationDate"));
                book.setIsAvailable(rs.getString("isAvailable"));
                book.setAddToLibraryDate(rs.getString("addToLibraryDate"));

                String authors = rs.getString("authors");
                BookAuthors bookAuthors[] = gson.fromJson(authors, BookAuthors[].class);
                book.setAuthors(bookAuthors);
            }
            return book;
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            return null;
        } finally {
            j.connectionClose();
        }

    }

    public Book addNewBook(Book book) {
        JSONObject jsonObject = new JSONObject();
        PreparedStatement ps = null;

        try {

            j.connect();
            String query = "INSERT INTO book VALUES(?);";
            ps = j.insertOrUpdateTable(query);

            jsonObject.put("id", book.getId());
            jsonObject.put("title", book.getTitle());
            jsonObject.put("authors", book.getAuthorsArray());
            //jsonObject.put("creationDate", book.getCreationDate());
            //jsonObject.put("isAvailable", book.getIsAvailable());
            jsonObject.put("addToLibraryDate", book.getAddToLibraryDate());

            ps.setString(1, jsonObject.toString());
            ps.executeUpdate();
            logger.info("Insert book id:" + book.getId());

            return book;

        } catch (Exception e) {

            logger.error(e.getMessage());

        }

        j.connectionClose();

        return null;

    }

    public BookAuthors[] addBookAuthors(BookAuthors... authors) {

        BookAuthors[] bookAuthors = new BookAuthors[authors.length];
        for (int i = 0; i < authors.length; ++i) {
            bookAuthors[i] = authors[i];
        }
        return bookAuthors;

    }

    public Book editBook(Book book) {

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

    public boolean deleteBook(Book book) {
        try {
            PreparedStatement ps = null;
            j.connect();

            String query = "DELETE FROM book WHERE JSON_VALUE(doc, '$.id') = ?";
            ps = j.insertOrUpdateTable(query);
            ps.setString(1, Integer.toString(book.getId()));
            ps.executeUpdate();
            logger.info("Book id: " + Integer.toString(book.getId()) + " deleted");

            return true;

        } catch (Exception e) {

            logger.error(e.getMessage());

        } finally {
            j.connectionClose();
        }

        return false;

    }

    public List<Book> getBooks(String title) {
        String query = "SELECT \n" + "JSON_VALUE(f.doc, '$.id') as id,\n"
                + "JSON_VALUE(f.doc, '$.title') as title,\n" + "JSON_QUERY(f.doc, '$.authors') as authors,\n"
                + "JSON_VALUE(f.doc, '$.creationDate') as creationDate,\n"
                + "JSON_VALUE(f.doc, '$.isAvailable') as isAvailable,\n"
                + "JSON_VALUE(f.doc, '$.addToLibraryDate') as addToLibraryDate\n" + "FROM Book f\n"
                + "WHERE JSON_VALUE(f.doc ,'$.title') LIKE '%" + title + "%'";

        List<Book> bookList = new ArrayList<Book>();

        try {
            j.connect();

            ResultSet rs = j.viewTable(query);
            if (!rs.next()) {
                return null;
            }
            rs.previous();
            while (rs.next()) {
                Book book = new Book();
                //logger.info(rs.getString("title"));
                String authors = rs.getString("authors");
                BookAuthors bookAuthors[] = gson.fromJson(authors, BookAuthors[].class);
                book.setAuthors(bookAuthors);
                book.setId(rs.getInt("id"));
                book.setTitle(rs.getString("title"));
                //book.setCreationDate(rs.getString("creationDate"));
                // book.setIsAvailable(rs.getString("isAvailable"));
                book.setAddToLibraryDate(rs.getString("addToLibraryDate"));
                bookList.add(book);
            }
            return bookList;

        } catch (SQLException ex) {
            logger.error(ex.getMessage());
            return null;
        } finally {
            j.connectionClose();
        }

    }
}