Search in sources :

Example 6 with BookDao

use of com.example.getstarted.daos.BookDao 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 7 with BookDao

use of com.example.getstarted.daos.BookDao 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 8 with BookDao

use of com.example.getstarted.daos.BookDao in project getting-started-java by GoogleCloudPlatform.

the class ListByUserServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    String startCursor = req.getParameter("cursor");
    List<Book> books = null;
    String endCursor = null;
    try {
        Result<Book> result = dao.listBooksByUser((String) req.getSession().getAttribute("userId"), startCursor);
        books = result.result;
        endCursor = result.cursor;
    } catch (Exception e) {
        throw new ServletException("Error listing books", e);
    }
    req.getSession().getServletContext().setAttribute("books", books);
    StringBuilder bookNames = new StringBuilder();
    for (Book book : books) {
        bookNames.append(book.getTitle() + " ");
    }
    logger.log(Level.INFO, "Loaded books: " + bookNames.toString() + " for user " + (String) req.getSession().getAttribute("userId"));
    req.getSession().setAttribute("cursor", endCursor);
    req.getSession().setAttribute("page", "list");
    req.getRequestDispatcher("/base.jsp").forward(req, resp);
}
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)

Example 9 with BookDao

use of com.example.getstarted.daos.BookDao in project getting-started-java by GoogleCloudPlatform.

the class ListBookServlet method init.

@Override
public void init() throws ServletException {
    BookDao dao = null;
    CloudStorageHelper storageHelper = new CloudStorageHelper();
    // Creates the DAO based on the Context Parameters
    String storageType = this.getServletContext().getInitParameter("bookshelf.storageType");
    switch(storageType) {
        case "datastore":
            dao = new DatastoreDao();
            break;
        case "cloudsql":
            try {
                // Use this url when using dev appserver, but connecting to Cloud SQL
                String connect = this.getServletContext().getInitParameter("sql.urlRemote");
                if (connect.contains("localhost")) {
                    // Use this url when using a local mysql server
                    connect = this.getServletContext().getInitParameter("sql.urlLocal");
                } else if (System.getProperty("com.google.appengine.runtime.version").startsWith("Google App Engine/")) {
                    // Use this url when on App Engine, connecting to Cloud SQL.
                    // Uses a special adapter because of the App Engine sandbox.
                    connect = this.getServletContext().getInitParameter("sql.urlRemoteGAE");
                }
                dao = new CloudSqlDao(connect);
            } catch (SQLException e) {
                throw new ServletException("SQL error", e);
            }
            break;
        default:
            throw new IllegalStateException("Invalid storage type. Check if bookshelf.storageType property is set.");
    }
    this.getServletContext().setAttribute("dao", dao);
    this.getServletContext().setAttribute("storageHelper", storageHelper);
    this.getServletContext().setAttribute(// Hide upload when Cloud Storage is not configured.
    "isCloudStorageConfigured", !Strings.isNullOrEmpty(getServletContext().getInitParameter("bookshelf.bucket")));
}
Also used : CloudStorageHelper(com.example.getstarted.util.CloudStorageHelper) ServletException(javax.servlet.ServletException) CloudSqlDao(com.example.getstarted.daos.CloudSqlDao) SQLException(java.sql.SQLException) BookDao(com.example.getstarted.daos.BookDao) DatastoreDao(com.example.getstarted.daos.DatastoreDao)

Aggregations

BookDao (com.example.getstarted.daos.BookDao)9 Book (com.example.getstarted.objects.Book)6 IOException (java.io.IOException)5 ServletException (javax.servlet.ServletException)5 CloudStorageHelper (com.example.getstarted.util.CloudStorageHelper)3 FileUploadException (org.apache.commons.fileupload.FileUploadException)3 HashMap (java.util.HashMap)2 FileItemIterator (org.apache.commons.fileupload.FileItemIterator)2 FileItemStream (org.apache.commons.fileupload.FileItemStream)2 ServletFileUpload (org.apache.commons.fileupload.servlet.ServletFileUpload)2 CloudSqlDao (com.example.getstarted.daos.CloudSqlDao)1 DatastoreDao (com.example.getstarted.daos.DatastoreDao)1 FirestoreDao (com.example.getstarted.daos.FirestoreDao)1 SQLException (java.sql.SQLException)1 HttpSession (javax.servlet.http.HttpSession)1