Make a serializable class Book
that holds the following information:
title
author
year
pages
The class BookStore
stores books in a hash table, identifying them by their names. The class should implement the following methods:
// Initialises the hash map with some predefined data.
void addSomeBooks();
// Loads the books from the given file.
// Returns whether the loading was successful.
boolean loadBooks(String fileName);
// Saves the books into the given file.
// Returns whether the saving was successful.
boolean saveBooks(String fileName);
Make a command line application that tests the above operations.
Make a simple client-server application, whose parts communicate using TCP/IP. Use the classes Book
and BookStore
from the previous exercise.
The server accepts clients one after the other. When a client connects, the server does the following.
BookStore
.addSomeBooks
true
to the client, then the book itself.false
to the client.The client connects to the server, and takes the appropriate steps, mirroring the server.
true
, reads the book and prints itfalse
, prints a message about the book missingMake a server that communicates using TCP that serves the clients using a separate thread for each client.
The server has to have an internal state, a data field of type java.util.HashMap<String, Integer>
.
Make a server that is accessible through RMI through the interface BookService
, which makes the following service available:
// Add a new book. If such a book is already present, return false, otherwise return true.
boolean add(Book newBook);
// If the book is present, return its title, otherwise, return null.
Book getByTitle(String title);
// Remove the book if present. Return whether the book was present.
boolean removeByTitle(String title);
Also make a client that accesses the server and tries its features.
You may use the following, simplified versions of Book
and BookStore
:
// Book.java ///////////////////////////////////////////////////////////////////
import java.io.Serializable;
public class Book implements Serializable {
public String title;
public String author;
public int year;
public int pages;
}
// BookStore.java //////////////////////////////////////////////////////////////
import java.util.HashMap;
public class BookStore {
public HashMap<String, Book> books = new HashMap<>();
public void BookStore() {
for (int i = 0; i < 10; ++i) {
Book book = new Book("Book #" + i, "Author #" + i, 2000 + i,
300 + 10 * i);
books.put(book.getTitle(), book);
}
}
}
startNetworkServer
.db/bin
directory within the JDK.ij
.ij
is short for i
nteractive J
DBC scripting tool.db/bin
directory within the JDK.CONNECT 'jdbc:derby://localhost:1527/books;create=true';
BOOK
that stores books.Book
.pages
should be optional.CREATE TABLE
SQL command.year
is reserved; we have to use quotes: "year"
, or choose another name.Use SHOW TABLES
and DESCRIBE BOOK
to get more information.
Use basic SQL operations (SELECT
, INSERT
, UPDATE
, DELETE
) to experiment with the database.
You can stop the server with the stopNetworkServer
command.
ij
with:CONNECT 'jdbc:derby:books;create=true';
Create an application that uses JDBC which persists the previous Book
entities in a Derby database.
Implement a new BookStore
class that uses the database:
// Constructor, connects to the database. In case of an error, prints an error message to the console.
BookStore(String host, int port);
// Adds a new book into the database. Returns true if there was no error, otherwise false.
boolean addBook(Book newBook);
// Deletes a book from the database. Returns true if there was no error, otherwise false.
boolean removeBookByTitle(String title);
// Gets all books from the database. In case of an error, returns the empty list.
java.util.List<Book> getAllBooks();
BookStore
class, and explore the created database using ij
.db/lib/derbyclient.jar
within the JDK.Make a Book
entity the following way:
id
: integer, primary key, automatically generatedtitle
: string, at most 255
characters long, must be presentauthor
: string, at most 255
characters long, must be presentpublishedAt
: date, optionalpages
: integer, optionalprice
: java.math.BigDecimal
with precision "10,2"
, optionalStockStatus
: values stored as strings
IN_STOCK
OUT_OF_STOCK
UNKNOWN
Store the books in the database table books
.
equals()
and hashCode()
so that they function based on the primary key.Make a class BookStore
that handles the above Book
entities via JPA. Implement the following operations:
// Constructor, gets the name of a persistence unit, and creates an appropriate `EntityManager` for it.
BookStore(String persistenceUnitName);
// Adds a new book into the database, and returns its identifier.
int addBook(Book newBook);
// Deletes the book with the given id (if it exists in the database).
void removeBookById(int bookId);
// Gets all books present in the database.
java.util.List<Book> getAllBooks();
Make a command line application that tests the BookStore
class.
db/lib/derbyclient.jar
within the JDK.make_and_run.sh
.Create an entity Author
that represents the author of a book:
id
: integer, primary key, automatically generatedname
: string, at most 255 characters long, compulsorybirthDate
: date - only year/month/day, optionalbooks
: list that consists of Book
entitiesCreate a Book
entity that contains the following data
id
: integer, primary key, automatically generatedtitle
: string, max. 255 karakter, compulsoryauthor
: an Author
entity
publishedAt
: date, optionalpages
: integer, optionalprice
: java.math.BigDecimal
with precision “10,2”, optionalStockStatus
: values stored as strings
IN_STOCK
OUT_OF_STOCK
UNKNOWN
equals()
and hashCode()
so that they function based on the primary key.Author
and Book
entities so that a book may have multiple authors.// Adds an author.
Author addAuthor(String name, Date birthDate /* can be null */);
// Removes an author.
void removeAuthor(Author author);
// Adds a book with one author. It will be UNKNOWN in stock.
Book addBook(String title, Author author);
// Associates a book with an author.
void assignAuthorToBook(Author author, Book book);
// Removes a book.
void removeBook(Book book);
books
.CascadeType
settings for the connections between the books and the authors.Make a web service that contains a servlet called ScopeTest
. From the service’s root, the servlet should be accessible under /test
.
The servlet has to do the following.
GET
requestsTry the application in various ways, and see what happens.
Dynamic Web Project
.Project Explorer
, and choose Java EE Tools>Generate Deployment Descriptor Stub
. This generates a web.xml
file in WebContent/WEB-INF
.GlassFish Console
: in your browser, go to the URL http://localhost:4848
.Create New JDBC Resource
, and create two resources for each of your persistence units: jdbc/YOURPERSISTENCEUNIT__pm
and jdbc/YOURPERSISTENCEUNIT__nontx
. (Note the double underscores.)META-INF/persistence.xml
.startNetworkServer
in the environment setup guide.Publishing to GlassFish ... has encountered a problem
with the details cannot Deploy your-application-name deploy is failing=Application with name [your-application-name] is not deployed
), you may have to explicitly remove it from GlassFish before you can attempt to deploy the application again. To do that, go to the Servers
tab in Eclipse, select the application, and press Del.@WebMethod
s etc.
$GLASSFISH/bin/asadmin start-domain
$GLASSFISH/bin/asadmin create-jdbc-resource --connectionpoolid=DerbyPool RESOURCENAME
RESOURCENAME
with jdbc/books__pm
and jdbc/books__nontx
(Note the double underscores.)jdbc/books
parts above with your JTA data source, which is located in your project: JPA Content>persistence.xml
, look inside the Source
tab, see the jta-data-source
elementCompanyServlet
that is available at /company-servlet
from the root./company-servlet/companies
, the servlet should return a page with a list of (built-in) company names./company-servlet/products
, the servlet should return a page with a list of (built-in) product names.company.jsp
which is used to store and display companies and their products.Map<String, List<String>>
to store the company names and their associated products.
CompanyServlet
to use JPA. Make two very simple entity types Company
and Product
; the servlet should provide functionalities to add a company and to add a product to a company. The servlet will always print the names of all companies with the names of their associated products.@Stateless
and @Remote
similar to the example.Deployment Assembly
, add both the interface project and the EJB project to it.Company
with the interface CompanyInterface
.hasProduct
that takes a String
and returns a boolean
.
CompanyProductsEn
, CompanyProductsHu
etc. contain the list of product names in the appropriate language. The local beans have a method getProductNames
that simply return the list.Company
will have a separate variable for each language, and the appropriate local EJB will be injected into it.hasProduct
now takes an additional parameter, a String
for the language. The method returns false if the language is not known, otherwise it takes the products from the local bean, and returns whether the product name is present in the list.@WebService
with a @WebMethod
named isBetween
that takes three parameters. Let it return true
iff param1
is between param2
and param3
.@WebMethod
s: setLowerBound
, setUpperBound
and isBetween
. The implementing class will store the bounds, and isBetween
only takes one number; it will check whether the parameter value is between the two stored values.All classes/objects mentioned in this section are POJOs (Plain old Java objects).
example.company
, create the classes Company
and Person
.
Person
s have a name
and a job
(strings), and an age
. They also have an employer
, a Company
.Company
objects have employees
(a list of them), and they have a ceo
(who is a Person
).toString
equals
and hashCode
Company.employees
, make and addEmployee
, hasEmployee
and removeEmployee
addEmployee
, removeEmployee
, setCompany
should change the other side too (if it is not set already)employees
and employer
CompanyTester
in the package example.company.test
. This class will contain the main
method. In main
, let us maintain a list of Company
objects.
makeDefaults
that will make some Company
and Person
objects, and associates them with each other.Company
and Person
classes Serializable
.main
, use makeDefaults
to get some companies (with some employees).ObjectOutputStream
. (Their employees will be saved, too.)ObjectInputStream
. (Their employees will be loaded, too.)example.company
, create the classes Product
. It will have an id
(an int), and knows its producingCompany
(a company) and buyer
(an Employee).
Company
will list its availableProducts
(a list).Company
will have a produce
method (no arguments) that creates a new product and adds it to the availableProducts
list.Company
will also have a sell
method that returns the first product of the availableProducts
list (and also removes it from the list). If there is no product, return null
. (Or, even better, return an Optional<Product>
).Person
will have a buy
method that takes a Company
. It will try to buy a product from the company; if successful, the Person
will store the product in his own boughtProducts
list.Set
instead of a List
to store the employees
of the company?File>New>JPA Entity
) called TestEntity
in the package test.entity
, which is a simple class annotated with @Entity
.
persistence.xml
(under JPA Content
in Project Explorer
) in the Managed classes
part. Also, have a look at the Source
tab.int
field called id
. It will be the entity’s primary key: annotate it with @Id
. Also, add @GeneratedValue
.MyEntity
instances: create some of them, persist them and query them.persistence.xml
settings, e.g. try to set eclipselink.ddl-generation
to drop-and-create-tables
instead of create-tables
.Company
, Person
and Product
classes from before to entities.
id
for each. Annotate them with @Id
.