public void testSerializableToBlob() throws Exception {
   Book book = new Book();
   Editor editor = new Editor();
   editor.setName("O'Reilly");
   book.setEditor(editor);
   book.setCode2(new char[] {'r'});
   Session s;
   Transaction tx;
   s = openSession();
   tx = s.beginTransaction();
   s.persist(book);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   Book loadedBook = (Book) s.get(Book.class, book.getId());
   assertNotNull(loadedBook.getEditor());
   assertEquals(book.getEditor().getName(), loadedBook.getEditor().getName());
   loadedBook.setEditor(null);
   tx.commit();
   s.close();
   s = openSession();
   tx = s.beginTransaction();
   loadedBook = (Book) s.get(Book.class, book.getId());
   assertNull(loadedBook.getEditor());
   tx.commit();
   s.close();
 }
Ejemplo n.º 2
0
 public void setBookFavorite(Book book, boolean favorite) {
   if (favorite) {
     myDatabase.addToFavorites(book.getId());
   } else {
     myDatabase.removeFromFavorites(book.getId());
   }
   fireBookEvent(BookEvent.Updated, book);
 }
Ejemplo n.º 3
0
 @RequestMapping(value = "/book", method = RequestMethod.POST)
 public ResponseEntity create(@RequestBody Book book) {
   for (Book a : books) {
     if (a.getId() == book.getId())
       return new ResponseEntity<String>(null, new HttpHeaders(), HttpStatus.FOUND);
   }
   books.add(book);
   return new ResponseEntity<Book>(book, new HttpHeaders(), HttpStatus.OK);
 }
Ejemplo n.º 4
0
 @RequestMapping(value = "/book/{id}", method = RequestMethod.PUT)
 public ResponseEntity update(@RequestBody Book book) {
   for (Book b : this.books) {
     if (b.getId() == book.getId()) {
       b.setTitlu(book.getTitlu());
       b.setEditura(book.getEditura());
       return new ResponseEntity<Book>(b, new HttpHeaders(), HttpStatus.OK);
     }
   }
   return new ResponseEntity<String>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
 }
Ejemplo n.º 5
0
  public void removeBook(Book book, boolean deleteFromDisk) {
    synchronized (myBooksByFile) {
      myBooksByFile.remove(book.File);
      myBooksById.remove(book.getId());

      final List<Long> ids = myDatabase.loadRecentBookIds();
      if (ids.remove(book.getId())) {
        myDatabase.saveRecentBookIds(ids);
      }
      if (deleteFromDisk) {
        book.File.getPhysicalFile().delete();
      }
    }
    fireBookEvent(BookEvent.Removed, book);
  }
Ejemplo n.º 6
0
	public static String XMLContent(List<Book> books, Writer writer)
	{
		XmlSerializer serializer = Xml.newSerializer();
		try {
			serializer.setOutput(writer);
			serializer.startDocument("UTF-8", true);
			serializer.startTag("", "books");
			for (Book book : books) {
				serializer.startTag("", "book");
				serializer.attribute("", "id", String.valueOf(book.getId()));
				serializer.startTag("", "name");
				serializer.text(book.getName());
				serializer.endTag("", "name");
				serializer.startTag("", "price");
				serializer.text(String.valueOf(book.getPrice()));
				serializer.endTag("", "price");
				serializer.endTag("", "book");
			}
			serializer.endTag("", "books");
			serializer.endDocument();
			return writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
Ejemplo n.º 7
0
 public void remove() {
   System.out.println("elo");
   bookList.remove(1);
   for (Book book : bookList) {
     System.out.println(book.getId() + " " + book.getTitle() + " " + book.getPrice());
   }
 }
Ejemplo n.º 8
0
  @Test
  public void testPaging() {
    JPA.bootstrap(path());

    int total = 15;

    JPA.transaction(
        () -> {
          for (int i = 0; i < total; i++) {
            Book book = JPA.insert(new Book("b" + i));
            notNull(book.getId());
          }
        });

    JPA.transaction(
        () -> {
          eq(JPA.getAllEntities().size(), total);
          eq(JPA.count(Book.class), total);

          eq(JPA.of(Book.class).all().size(), total);

          List<Book> first3 = JPA.of(Book.class).page(0, 3);
          eq(first3.size(), 3);
          eq(Do.map(first3).to(Book::getTitle), U.list("b0", "b1", "b2"));

          List<Book> next5 = JPA.of(Book.class).page(3, 5);
          eq(Do.map(next5).to(Book::getTitle), U.list("b3", "b4", "b5", "b6", "b7"));

          List<Book> last2 = JPA.of(Book.class).page(13, 2);
          eq(Do.map(last2).to(Book::getTitle), U.list("b13", "b14"));
        });
  }
Ejemplo n.º 9
0
  private void addBook(Book book, boolean force) {
    if (book == null || book.getId() == -1) {
      return;
    }

    synchronized (myBooksByFile) {
      final Book existing = myBooksByFile.get(book.File);
      if (existing == null) {
        myBooksByFile.put(book.File, book);
        myBooksById.put(book.getId(), book);
        fireBookEvent(BookEvent.Added, book);
      } else if (force) {
        existing.updateFrom(book);
        fireBookEvent(BookEvent.Updated, existing);
      }
    }
  }
Ejemplo n.º 10
0
 @RequestMapping(value = "/book/{id}", method = RequestMethod.GET)
 public ResponseEntity show(@PathVariable("id") int id) {
   for (Book b : this.books) {
     if (b.getId() == id) {
       return new ResponseEntity<Book>(b, new HttpHeaders(), HttpStatus.OK);
     }
   }
   return new ResponseEntity<String>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
 }
Ejemplo n.º 11
0
 public void removeItem(int id) {
   Iterator<Book> it = booksOrdered.iterator();
   while (it.hasNext()) {
     Book next = it.next();
     if (next.getId() == id) {
       it.remove();
     }
   }
 }
Ejemplo n.º 12
0
 public static Integer create(Book b) {
   Session session = getSessionFactory().openSession();
   session.beginTransaction();
   session.save(b);
   session.getTransaction().commit();
   session.close();
   System.out.println("Successfully created " + b.toString());
   return b.getId();
 }
Ejemplo n.º 13
0
 @RequestMapping(value = "/book/{id}", method = RequestMethod.DELETE)
 public ResponseEntity remove(@PathVariable("id") int id) {
   for (Book b : this.books) {
     if (b.getId() == id) {
       this.books.remove(b);
       return new ResponseEntity<String>(null, new HttpHeaders(), HttpStatus.NO_CONTENT);
     }
   }
   return new ResponseEntity<String>(null, new HttpHeaders(), HttpStatus.NOT_FOUND);
 }
Ejemplo n.º 14
0
 public void addBookToRecentList(Book book) {
   final List<Long> ids = myDatabase.loadRecentBookIds();
   final Long bookId = book.getId();
   ids.remove(bookId);
   ids.add(0, bookId);
   if (ids.size() > 12) {
     ids.remove(12);
   }
   myDatabase.saveRecentBookIds(ids);
 }
Ejemplo n.º 15
0
 public Hold(Context context, Book book, Member member, int numberOfDays) {
   this.mBookId = book.getId();
   this.mMemberId = member.getId();
   int tempNumberOfDays = numberOfDays;
   if (tempNumberOfDays > Library.MAX_HOLD_DAYS) tempNumberOfDays = Library.MAX_HOLD_DAYS;
   else {
     if (tempNumberOfDays < 0) tempNumberOfDays = 0;
   }
   mEndDate = Calendar.getInstance();
   mEndDate.add(Calendar.DAY_OF_MONTH, tempNumberOfDays);
   sAppContext = context;
 }
Ejemplo n.º 16
0
 public static void shouldGetUserInput() throws ParseException {
   // this method also tests dateToString()
   // needed input: 1, Title, Author, 01.01.2011
   _testBook.input();
   int id = _testBook.getId();
   String title = _testBook.getTitle();
   String author = _testBook.getAuthor();
   Date date = _testBook.getDateOfPublication();
   if (id != 1
       || !title.equals("Title")
       || !author.equals("Author")
       || !_testBook.dateToString(date).equals("01.01.2011")) {
     _allTestsPassed = false;
   }
 }
Ejemplo n.º 17
0
 public OwnedBook(Book book) {
   super(
       book.getId(),
       book.getGoodreadsId(),
       book.getAuthorName(),
       book.getGoodreadsAuthorId(),
       book.getName(),
       book.getIsbn(),
       book.getIsbn13(),
       book.getPublishedYear(),
       book.getDescription(),
       book.getPublisher(),
       book.getNumberOfPages(),
       book.getImageUrl());
   setBookType(book.getBookType());
 }
Ejemplo n.º 18
0
 public synchronized boolean equals(java.lang.Object obj) {
   if (!(obj instanceof Book)) return false;
   Book other = (Book) obj;
   if (obj == null) return false;
   if (this == obj) return true;
   if (__equalsCalc != null) {
     return (__equalsCalc == obj);
   }
   __equalsCalc = obj;
   boolean _equals;
   _equals =
       true
           && this.id == other.getId()
           && ((this.name == null && other.getName() == null)
               || (this.name != null && this.name.equals(other.getName())));
   __equalsCalc = null;
   return _equals;
 }
Ejemplo n.º 19
0
 private void createItem() {
   try {
     if (!totalItemsLocked) {
       totalItems = Integer.parseInt(text_totalItems.getText());
       totalItemsLocked = true;
     }
     String bookQuery = text_bookID.getText();
     boolean found = false;
     for (Book book : inventory)
       if (book.getId().equals(bookQuery)) {
         this.item = new Item(book, Integer.parseInt(text_quantity.getText()));
         found = true;
       }
     if (!found) bookNotFoundAlert(bookQuery);
   } catch (Exception e) {
     System.out.println("DEBUG: -----Start-----\n" + e + "DEBUG: ------End------\n");
   }
 }
Ejemplo n.º 20
0
  private void processFilesQueue() {
    synchronized (myFilesToRescan) {
      if (!myStatus.IsCompleted) {
        return;
      }

      final Set<ZLFile> filesToRemove = new HashSet<ZLFile>();
      for (String path : myFilesToRescan) {
        path = new ZLPhysicalFile(new File(path)).getPath();
        synchronized (myBooksByFile) {
          for (ZLFile f : myBooksByFile.keySet()) {
            if (f.getPath().startsWith(path)) {
              filesToRemove.add(f);
            }
          }
        }
      }

      for (ZLFile file : collectPhysicalFiles(myFilesToRescan)) {
        // TODO:
        // collect books from archives
        // rescan files and check book id
        filesToRemove.remove(file);
        final Book book = getBookByFile(file);
        if (book != null) {
          saveBook(book, false);
        }
      }

      for (ZLFile f : filesToRemove) {
        synchronized (myBooksByFile) {
          final Book book = myBooksByFile.remove(f);
          if (book != null) {
            myBooksById.remove(book.getId());
            fireBookEvent(BookEvent.Removed, book);
          }
        }
      }

      myFilesToRescan.clear();
    }
  }
Ejemplo n.º 21
0
  private Entry createBookEntry(int id, String name) throws Exception {

    Book b = new Book();
    b.setId(id);
    b.setName(name);

    Factory factory = Abdera.getNewFactory();
    JAXBContext jc = JAXBContext.newInstance(Book.class);

    Entry e = factory.getAbdera().newEntry();
    e.setTitle(b.getName());
    e.setId(Long.toString(b.getId()));

    StringWriter writer = new StringWriter();
    jc.createMarshaller().marshal(b, writer);

    Content ct = factory.newContent(Content.Type.XML);
    ct.setValue(writer.toString());
    e.setContentElement(ct);
    return e;
  }
  public void testClob() throws Exception {
    Session s;
    Transaction tx;
    s = openSession();
    tx = s.beginTransaction();
    Book b = new Book();
    b.setShortDescription("Hibernate Bible");
    b.setFullText("Hibernate in Action aims to...");
    b.setCode(new Character[] {'a', 'b', 'c'});
    b.setCode2(new char[] {'a', 'b', 'c'});
    s.persist(b);
    tx.commit();
    s.close();

    s = openSession();
    tx = s.beginTransaction();
    Book b2 = (Book) s.get(Book.class, b.getId());
    assertNotNull(b2);
    assertEquals(b2.getFullText(), b.getFullText());
    assertEquals(b2.getCode()[1].charValue(), b.getCode()[1].charValue());
    assertEquals(b2.getCode2()[2], b.getCode2()[2]);
    tx.commit();
    s.close();
  }
Ejemplo n.º 23
0
 public static void shouldSetId() {
   _testBook.setId(500);
   int newid = _testBook.getId();
   if (newid != 500) _allTestsPassed = false;
 }
Ejemplo n.º 24
0
  private void build() {
    // Step 0: get database books marked as "existing"
    final FileInfoSet fileInfos = new FileInfoSet(myDatabase);
    final Map<Long, Book> savedBooksByFileId = myDatabase.loadBooks(fileInfos, true);
    final Map<Long, Book> savedBooksByBookId = new HashMap<Long, Book>();
    for (Book b : savedBooksByFileId.values()) {
      savedBooksByBookId.put(b.getId(), b);
    }

    // Step 1: check if files corresponding to "existing" books really exists;
    //         add books to library if yes (and reload book info if needed);
    //         remove from recent/favorites list if no;
    //         collect newly "orphaned" books
    final Set<Book> orphanedBooks = new HashSet<Book>();
    final Set<ZLPhysicalFile> physicalFiles = new HashSet<ZLPhysicalFile>();
    int count = 0;
    for (Book book : savedBooksByFileId.values()) {
      final ZLPhysicalFile file = book.File.getPhysicalFile();
      if (file != null) {
        physicalFiles.add(file);
      }
      if (file != book.File && file != null && file.getPath().endsWith(".epub")) {
        continue;
      }
      if (book.File.exists()) {
        boolean doAdd = true;
        if (file == null) {
          continue;
        }
        if (!fileInfos.check(file, true)) {
          try {
            book.readMetaInfo();
            saveBook(book, false);
          } catch (BookReadingException e) {
            doAdd = false;
          }
          file.setCached(false);
        }
        if (doAdd) {
          // loaded from db
          addBook(book, false);
        }
      } else {
        orphanedBooks.add(book);
      }
    }
    myDatabase.setExistingFlag(orphanedBooks, false);

    // Step 2: collect books from physical files; add new, update already added,
    //         unmark orphaned as existing again, collect newly added
    final Map<Long, Book> orphanedBooksByFileId = myDatabase.loadBooks(fileInfos, false);
    final Set<Book> newBooks = new HashSet<Book>();

    final List<ZLPhysicalFile> physicalFilesList = collectPhysicalFiles(BookDirectories);
    for (ZLPhysicalFile file : physicalFilesList) {
      if (physicalFiles.contains(file)) {
        continue;
      }
      collectBooks(
          file,
          fileInfos,
          savedBooksByFileId,
          orphanedBooksByFileId,
          newBooks,
          !fileInfos.check(file, true));
      file.setCached(false);
    }

    // Step 3: add help file
    try {
      final ZLFile helpFile = BookUtil.getHelpFile();
      Book helpBook = savedBooksByFileId.get(fileInfos.getId(helpFile));
      if (helpBook == null) {
        helpBook = new Book(helpFile);
      }
      saveBook(helpBook, false);
      // saved
      addBook(helpBook, false);
    } catch (BookReadingException e) {
      // that's impossible
      e.printStackTrace();
    }

    // Step 4: save changes into database
    fileInfos.save();

    myDatabase.executeAsTransaction(
        new Runnable() {
          public void run() {
            for (Book book : newBooks) {
              saveBook(book, false);
            }
          }
        });
    myDatabase.setExistingFlag(newBooks, true);
  }
Ejemplo n.º 25
0
 public List<Bookmark> invisibleBookmarks(Book book) {
   final List<Bookmark> list = myDatabase.loadBookmarks(book.getId(), false);
   Collections.sort(list, new Bookmark.ByTimeComparator());
   return list;
 }
Ejemplo n.º 26
0
 public static void shouldReturnId() {
   int id = _testBook.getId();
   if (id != 3) _allTestsPassed = false;
 }
Ejemplo n.º 27
0
 public Book addBook(Book book) {
   books.put(book.getId(), book);
   return books.get(book.getId());
 }
Ejemplo n.º 28
0
 private void init() {
   Book book = new Book();
   book.setId(123);
   book.setName("CXF in Action");
   books.put(book.getId(), book);
 }
Ejemplo n.º 29
0
  public static void main(String[] args) {
    //  staticFileLocation("/public");
    String layout = "templates/layout.vtl";

    get(
        "/",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          model.put("template", "templates/index.vtl");

          model.put("books", Author.all());
          model.put("authors", Author.all());
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    get(
        "/books",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          model.put("books", Book.all());
          model.put("template", "templates/books.vtl");
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    post(
        "/books",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          String title = request.queryParams("title");
          Book newBook = new Book(title);
          newBook.save();
          Copy copy = new Copy(newBook.getCopiesOfBook().size() + 1, newBook.getId());
          copy.save();
          model.put("books", Book.all());
          model.put("template", "templates/books.vtl");
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    get(
        "/authors",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          model.put("template", "templates/authors.vtl");
          model.put("authors", Author.all());
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    post(
        "/authors",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          String name = request.queryParams("name");
          Author newAuthor = new Author(name);
          newAuthor.save();
          model.put("authors", Author.all());
          model.put("template", "templates/authors.vtl");
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    get(
        "/books/:id",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          int bookId = Integer.parseInt(request.params("id"));
          Book book = Book.find(bookId);
          ArrayList<Author> authorList = book.getAuthors();
          int numCopies = book.getCopiesOfBook().size();
          model.put("numCopies", numCopies);
          model.put("book", book);
          model.put("template", "templates/book.vtl");
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    post(
        "/books/:id/addCopy",
        (request, response) -> {
          int bookId = Integer.parseInt(request.queryParams("bookToCopy"));
          Book bookToCopy = Book.find(bookId);
          bookToCopy.addCopy();
          String bookCopyPath = String.format("/books/%d", bookId);
          response.redirect(bookCopyPath);
          return null;
        });

    post(
        "/books/:id/addAuthor",
        (request, response) -> {
          int bookId = Integer.parseInt(request.queryParams("book_id"));
          Book book = Book.find(bookId);
          String newAuthorName = request.queryParams("authorName");
          Author newAuthor = new Author(newAuthorName);
          newAuthor.save();
          newAuthor.addBook(book);
          String bookIdPath = String.format("/books/%d", bookId);
          response.redirect(bookIdPath);
          return null;
        });

    post(
        "/books/:book_id/deleteAuthor/:author_id",
        (request, response) -> {
          int bookId = Integer.parseInt(request.params("book_id"));
          int deadAuthorId = Integer.parseInt(request.queryParams("deleteAuthor"));
          Author deadAuthor = Author.find(deadAuthorId);
          deadAuthor.delete();
          String deleteAuthPath = String.format("/books/%d", bookId);
          response.redirect(deleteAuthPath);
          return null;
        });

    get(
        "/authors/:id",
        (request, response) -> {
          Map<String, Object> model = new HashMap<String, Object>();
          int authorId = Integer.parseInt(request.params("id"));
          Author author = Author.find(authorId);
          // ArrayList<Book> bookList = author.getBooks();
          model.put("author", author);
          model.put("template", "templates/author.vtl");
          return new ModelAndView(model, layout);
        },
        new VelocityTemplateEngine());

    post(
        "/authors/:id/addBook",
        (request, response) -> {
          int authorId = Integer.parseInt(request.queryParams("authorId"));
          Author author = Author.find(authorId);
          String newBookTitle = request.queryParams("bookTitle");
          Book newBook = new Book(newBookTitle);
          newBook.save();
          newBook.addAuthor(author);
          String authIdPath = String.format("/authors/%d", authorId);
          response.redirect(authIdPath);
          return null;
        });

    post(
        "/authors/:author_id/deleteBook/:book_id",
        (request, response) -> {
          int authId = Integer.parseInt(request.params("author_id"));
          int deadBookId = Integer.parseInt(request.queryParams("deleteBook"));
          Book deadBook = Book.find(deadBookId);
          deadBook.delete();
          String deleteBookPath = String.format("/authors/%d", authId);
          response.redirect(deleteBookPath);
          return null;
        });
  }
Ejemplo n.º 30
0
 final void init() {
   Book book = new Book();
   book.setId(mainId);
   book.setName("CXF in Action");
   books.put(book.getId(), book);
 }