Search in sources :

Example 6 with Book

use of com.example.getstarted.objects.Book in project getting-started-java by GoogleCloudPlatform.

the class CreateBookServlet method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
    String newImageUrl = null;
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item, System.getenv("BOOKSHELF_BUCKET"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) {
        // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }
    Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString).createdById(createdByIdString).build();
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    String id = dao.createBook(book);
    logger.log(Level.INFO, "Created book {0}", book);
    resp.sendRedirect("/read?id=" + id);
}
Also used : CloudStorageHelper(com.example.getstarted.util.CloudStorageHelper) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) IOException(java.io.IOException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) Book(com.example.getstarted.objects.Book) BookDao(com.example.getstarted.daos.BookDao) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 7 with Book

use of com.example.getstarted.objects.Book in project getting-started-java by GoogleCloudPlatform.

the class UpdateBookServlet method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");
    String newImageUrl = null;
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item, getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }
    try {
        Book oldBook = dao.readBook(Long.decode(params.get("id")));
        Book book = new Book.Builder().author(params.get("author")).description(params.get("description")).publishedDate(params.get("publishedDate")).title(params.get("title")).imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).id(Long.decode(params.get("id"))).createdBy(oldBook.getCreatedBy()).createdById(oldBook.getCreatedById()).build();
        dao.updateBook(book);
        resp.sendRedirect("/read?id=" + params.get("id"));
    } catch (Exception e) {
        throw new ServletException("Error updating book", e);
    }
}
Also used : CloudStorageHelper(com.example.getstarted.util.CloudStorageHelper) HashMap(java.util.HashMap) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException) ServletException(javax.servlet.ServletException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) Book(com.example.getstarted.objects.Book) BookDao(com.example.getstarted.daos.BookDao) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 8 with Book

use of com.example.getstarted.objects.Book in project getting-started-java by GoogleCloudPlatform.

the class UpdateBookServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Book book = dao.readBook(Long.decode(req.getParameter("id")));
        req.setAttribute("book", book);
        req.setAttribute("action", "Edit");
        req.setAttribute("destination", "update");
        req.setAttribute("page", "form");
        req.getRequestDispatcher("/base.jsp").forward(req, resp);
    } catch (Exception e) {
        throw new ServletException("Error loading book for editing", e);
    }
}
Also used : ServletException(javax.servlet.ServletException) Book(com.example.getstarted.objects.Book) BookDao(com.example.getstarted.daos.BookDao) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 9 with Book

use of com.example.getstarted.objects.Book in project getting-started-java by GoogleCloudPlatform.

the class CloudSqlDao method listBooksByUser.

// [END listbooks]
// [START listbyuser]
@Override
public Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException {
    int offset = 0;
    if (startCursor != null && !startCursor.equals("")) {
        offset = Integer.parseInt(startCursor);
    }
    final String listBooksString = "SELECT SQL_CALC_FOUND_ROWS author, createdBy, createdById, " + "description, id, publishedDate, title, imageUrl FROM books WHERE createdById = ? " + "ORDER BY title ASC LIMIT 10 OFFSET ?";
    try (Connection conn = DriverManager.getConnection(sqlUrl);
        PreparedStatement listBooksStmt = conn.prepareStatement(listBooksString)) {
        listBooksStmt.setString(1, userId);
        listBooksStmt.setInt(2, offset);
        List<Book> resultBooks = new ArrayList<>();
        try (ResultSet rs = listBooksStmt.executeQuery()) {
            while (rs.next()) {
                Book book = new Book.Builder().author(rs.getString(Book.AUTHOR)).createdBy(rs.getString(Book.CREATED_BY)).createdById(rs.getString(Book.CREATED_BY_ID)).description(rs.getString(Book.DESCRIPTION)).id(rs.getLong(Book.ID)).publishedDate(rs.getString(Book.PUBLISHED_DATE)).title(rs.getString(Book.TITLE)).imageUrl(rs.getString(Book.IMAGE_URL)).build();
                resultBooks.add(book);
            }
        }
        try (ResultSet rs = conn.createStatement().executeQuery("SELECT FOUND_ROWS()")) {
            int totalNumRows = 0;
            if (rs.next()) {
                totalNumRows = rs.getInt(1);
            }
            if (totalNumRows > offset + 10) {
                return new Result<>(resultBooks, Integer.toString(offset + 10));
            } else {
                return new Result<>(resultBooks);
            }
        }
    }
}
Also used : Book(com.example.getstarted.objects.Book) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Result(com.example.getstarted.objects.Result)

Example 10 with Book

use of com.example.getstarted.objects.Book in project getting-started-java by GoogleCloudPlatform.

the class CloudSqlDao method listBooks.

// [END delete]
// [START listbooks]
@Override
public Result<Book> listBooks(String cursor) throws SQLException {
    int offset = 0;
    if (cursor != null && !cursor.equals("")) {
        offset = Integer.parseInt(cursor);
    }
    final String listBooksString = "SELECT SQL_CALC_FOUND_ROWS author, createdBy, createdById, " + "description, id, publishedDate, title, imageUrl FROM books5 ORDER BY title ASC " + "LIMIT 10 OFFSET ?";
    try (Connection conn = DriverManager.getConnection(sqlUrl);
        PreparedStatement listBooksStmt = conn.prepareStatement(listBooksString)) {
        listBooksStmt.setInt(1, offset);
        List<Book> resultBooks = new ArrayList<>();
        try (ResultSet rs = listBooksStmt.executeQuery()) {
            while (rs.next()) {
                Book book = new Book.Builder().author(rs.getString(Book.AUTHOR)).createdBy(rs.getString(Book.CREATED_BY)).createdById(rs.getString(Book.CREATED_BY_ID)).description(rs.getString(Book.DESCRIPTION)).id(rs.getLong(Book.ID)).publishedDate(rs.getString(Book.PUBLISHED_DATE)).title(rs.getString(Book.TITLE)).imageUrl(rs.getString(Book.IMAGE_URL)).build();
                resultBooks.add(book);
            }
        }
        try (ResultSet rs = conn.createStatement().executeQuery("SELECT FOUND_ROWS()")) {
            int totalNumRows = 0;
            if (rs.next()) {
                totalNumRows = rs.getInt(1);
            }
            if (totalNumRows > offset + 10) {
                return new Result<>(resultBooks, Integer.toString(offset + 10));
            } else {
                return new Result<>(resultBooks);
            }
        }
    }
}
Also used : Book(com.example.getstarted.objects.Book) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Result(com.example.getstarted.objects.Result)

Aggregations

Book (com.example.getstarted.objects.Book)12 BookDao (com.example.getstarted.daos.BookDao)6 Result (com.example.getstarted.objects.Result)6 IOException (java.io.IOException)5 ServletException (javax.servlet.ServletException)4 FileUploadException (org.apache.commons.fileupload.FileUploadException)3 CloudStorageHelper (com.example.getstarted.util.CloudStorageHelper)2 Cursor (com.google.appengine.api.datastore.Cursor)2 Entity (com.google.appengine.api.datastore.Entity)2 FetchOptions (com.google.appengine.api.datastore.FetchOptions)2 PreparedQuery (com.google.appengine.api.datastore.PreparedQuery)2 Query (com.google.appengine.api.datastore.Query)2 Query (com.google.cloud.firestore.Query)2 QuerySnapshot (com.google.cloud.firestore.QuerySnapshot)2 Connection (java.sql.Connection)2 PreparedStatement (java.sql.PreparedStatement)2 ResultSet (java.sql.ResultSet)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 ExecutionException (java.util.concurrent.ExecutionException)2