Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit



CSE3OAD – Object-oriented Application Development

Question 1 (25 marks)
Consider the following JavaFX program:
import javafx.application.*;
import javafx.stage.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.text.*;
public class SampleFX extends Application
{
private int count = 0;
public void start(Stage stage)
{
build(stage);
stage.setTitle(getClass().getName());
stage.show();
}
private void build(Stage stage)
{
// Define controls and layout
Label msgLB = new Label(count + "");
VBox root = new VBox();
root.getChildren().add(msgLB);
//
Define the scene and set the stage
Scene scene = new Scene(root, 400, 300);
stage.setScene(scene);
}
}
(a)
Describe what will be shown on the screen when the above program is executed.
Sketch a diagram to illustrate your answer.
[5 marks]
(b)
Modify the build method to display a button, labelled “Click Me”, on the window;
and when we click on the button, the attribute count is increased by 1 and the word “Hello
World” following by the updated value of count is shown on the window.
[10 marks]
(c)
Answer the following:
I.
What are the two important parts of a lambda expression?
II.
What kind of interfaces can be implemented using a lambda expression?
III.
What is the most common use of lambda expression in JavaFX?
[3 + 3 + 4 = 10 marks]Question 2 (10 marks)
A typical OO Java class will have the following items. Describe each one in
concise terms:
(a) Constructor.
(b) getter().
(c) setter().
(d) toString()
After careful examination of the code fragment below, answer the questions
that follow:
1
2 Group g = new Group();
3 for (int i = 0; i < 5; i++) {
4 Rectangle r = new Rectangle();
5 r.setWidth(100*i);
6 r.setHeight(10);
7 r.setFill(Color.RED);
8 g.getChildren().add(r);
9 }
10 return g;
(e ) How many Objects are instantiated in the above code?
(f ) Describe three methods that a Rectangle object is able to call?
(g ) Describe two methods that a Group object is able to call?
(h ) Identify one static class variable call
(i ) What type of object will the "getChildren()" method call on line 8 return?
(j ) On line 10 what is the type of the object is returned by the method?
[(1 + 1 + 1 + 1 + 1 + 1 + 1 +1 + 1 + 1) = 10 Marks]
Question 3 (30 marks)
Consider an application that maintains a collection of books. Each book has a unique id
(a String), a title (a String), authors (a String), and an attribute to show if it is a book for
kid or not (a Boolean).
Two classes have been completed: The Book class (representing a book), and the BookDSC
class, which provides the usual methods to manipulate a collection of books.
In addition, suppose we also have the following partially complete program:
// import statements
public class BookGUI extends Application
{
BookDSC bookDSC = new BookDSC();
public void start(Stage stage) throws Exception
{
build(stage);
stage.setTitle(getClass().getName());
stage.show();
}
public void build(Stage stage) throws Exception
{
// Define table view and table columns
TableView tableView = new TableView();
TableColumn idColumn =
new TableColumn("Id");
idColumn.setCellValueFactory(
new PropertyValueFactory("Id"));
tableView.getColumns().add(idColumn);
TableColumn titleColumn =
new TableColumn("Title");
titleColumn.setCellValueFactory(
new PropertyValueFactory("Title"));
tableView.getColumns().add(titleColumn);
TableColumn authorsColumn =
new TableColumn("Authors");
authorsColumn.setCellValueFactory(
new PropertyValueFactory("Authors"));
tableView.getColumns().add(authorsColumn);
TableColumn forKidsColumn =
new TableColumn("For Kids");
forKidsColumn.setCellValueFactory(
new PropertyValueFactory("isForKids"));
tableView.getColumns().add(authorsColumn);
// Prepare data and set the data to the table view
List list = bookDSC.getAll();
ObservableList tableData= FXCollections.observableArrayList(list);
tableView.setItems(tableData);
// Add table view to root element of the scene
VBox root = new VBox();
root.getChildren().add(tableView);
// To do Part (a)
// To do Part (b)
// Set scene and stage
Scene scene = new Scene(root);
stage.setScene(scene);
}
}
(a)
Add to the above program the necessary code, to be inserted after ‘// To do - Part
(a)’, to create four text fields and a button so that when we select a row in the table view
and click on the button, the details of the selected row are copied to the text fields.5
Note: You do not need to provide a nice layout for the interface. You just need to fulfil the
functional requirement. You may want to refer to the Syntax reference (Appendix A) for
the correct syntax.
[15 marks]
(b)
The following code segment is written and inserted after ‘To do Part (b)’:
1 FilteredList filteredList =
2
new FilteredList<>(tableData, p -> true);
3
4 SortedList sortedList = new SortedList<>(filteredList);
5 tableView.setItems(sortedList);
6
7 sortedList.comparatorProperty().bind(tableView.comparatorProperty());
8
9 TextField filterTF = new TextField();
10 root.getChildren().addAll(filterTF);
11 filterTF.textProperty().addListener((observable, oldValue, newValue) ->
12
{
13
filteredList.setPredicate(book ->
14
{
15
if (newValue == null || newValue.isEmpty())
16
return true;
17
18
if (book.getAuthors().toUpperCase().contains(newValue.toUpperCase()))
19
return true;
20
else
21
return false;
22
});
23
});
Answer the following questions:
I.
What is the purpose of the code segment?
II.
What is the meaning of the expression p -> true on line 2? What happens if we
replace it by p -> false?
III.
What will happen if we omit the statement on line 7?
[10 marks]
(c)
When completing all the code, we compile and run the program BookGUI. It works
well, but only the column “For Kids” does not show the data. What is the reason for that?
How would you fix it to show the data on the column?
[5 marks]6
Question 4 (20 marks)
A database contains the following table
Customer(id, name, phone, creditRating)
Where id, name, and phone are of type varchar and creditRating is of type integer. In
addition, id is declared to be the primary key of the table.
Assume that you already have the Customer class, which has a constructor that takes four
parameters for id, name, phone number and credit rating.
You are about to write a number of methods for the data source controller, called
CustomerDSC.
Assume that the CustomerDSC class already has methods connect() and disconnect() to
connect to the database and to disconnect from it. In addition,
• An attribute named statement of type Statement has been declared and
instantiated
• An attribute named preparedStatement of type PreparedStatement has been
declared (but not instantiated)
(a)
Write a method to find a customer by the customer's id. Return a Customer instance
if the customer is found. Otherwise, return null.
[8 marks]
(b)
Write a method to add a new customer (the parameters are: id, name, phone
number and credit rating). Based on your implementation, what would happen if the id is
not new?
[7 marks]
(c)
Write a method to change the phone of an existing customer (think of which
parameters that the method needs). Provide appropriate messages in cases of successful
and unsuccessful operations.
[5 marks]7
Question 5 (30 marks)
Provide answers for the following short answer questions. You should aim for a
paragraph for each question.
a) Why are Design Patterns considered useful in developing software applications?
[3 marks]
b) Draw a diagram that shows the relationship of Model, View and Controller
components of the MVC design pattern to each other and briefly explain how the MVC
design pattern works.
[3 marks]
c) What are Annotations? What are their typical usages?
[3 marks]
d) Describe the process of using Annotations and Reflection to implement a Validation
framework
[3 marks]
e) The following annotations are part of the JDK. Describe in short, what each of them
does.
i. @Override
ii. @SupressWarnings
iii. @Deprecated
[3 marks]
(f)
Java Reflection API supports introspection and lets you query an object for its
class. Describe how an object of type Class can be used to break encapsulation.
[5 marks]
(g)
The following code segment defines the annotation Range:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Range
{
public int minValue() default 0;
public int maxValue() default 100;
}
Answer the following questions:
I.
What does the line of code @Retention(RetentionPolicy.RUNTIME) mean?
II.
What does the line of code @Target(ElementType.FIELD) mean?
III.
Describe what the default keyword does for the parameters minValue and
maxValue? 8
IV.
With the retention policy set to RUNTIME, how can the annotation data be
retrieved when the annotation is used in a Java program?
[2+2+2+4= 10 marks]
Question 6 (11 marks)
Suppose we have a Java class called Person.java
1 public class Person
2 {
3
private String name;
4
private int age;
5
public Person(String name, int age)
6
{
7
this.name = name;
8
this.age = age;
9
}
10
public String getName(){return name;}
11
public int getAge(){return age;}
12 }
(a) In the following main method which lines contain reflection calls?
1 import java.lang.reflect.Field;
2 public class TestPerson
3 {
4
public static void main(String args[]) throws Exception
5
{
6
Person person = new Person("Peter", 20);
7
Field field = person.getClass().getDeclaredField("name");
8
field.setAccessible(true);
9
field.set(person, "Paul");
10
}
11 }
[3 marks]
(b) Describe what the reflection commands in (a) above do and why it might be a concern
to object-oriented programming purists.
[4 marks]
(c) What reflection code would you add to find the methods that the person class has
WITHOUT instantiating Person
[4 marks]9
Question 7 (24 marks)
Consider the scenario described below, which involves the application of RESTful web
services:
We maintain information about a collection of books on a server and make the related
resources available to clients over the Web. Each book has an id, the title, authors, price
and the review rating.
And a client program may want to perform the following operations:
• Add a book
• Edit the price or the rating or both of a book
• Delete a book
• Get the details of a book with a specified id
• Get the details of all the books
• Get the details of the books whose title contains a search string
Assume that we have developed the following classes:
• Class Book, which has attributes: id (a string), title (a string), authors (a string),
price (a double), and rating (an int).
• Class BookDSC, a data source controller, whose methods include the following:
o add(Book book) to add a book
o edit(Book book) to edit an existing book
o delete(String id) to delete a book
o get(String id) which returns a Book, and
o getAll() which returns a List
o getByTitle(String searchString) which returns a List, the list of
books whose title attribute contains the searchString
(a)
With respect to the scenario given above, describe the anatomies of the REST
requests and the REST responses. The anatomies must be provided in a table, not
continuous prose. (HINT: In order to differentiate several GET requests, the anatomy
table should have a column to specify the query strings (i.e. parameter names and values)
instead of just the parameters.)
[12 marks]
(b)
Using a servlet, implement the following 2 web services:
I.
To get a book with a specified id
II.
To get all books whose title contains a specified search string
Note: If any part of your servlet code throws an Exception, you should catch them
accordingly and return necessary response back to the client.
[12 marks]
END OF EXAM PAPERAppendix A: Syntax Reference
1. JavaFX
Sample program skeleton >>
// import statements
public class SampleFX extends Application{
public void start(Stage stage){
addContents(stage);
stage.setTitle(getClass().getName());
stage.show();
}
private void addContents(Stage stage){
...
root.getChildren().addAll(...); // not for BorderPane
Scene scene = new Scene(root, 400, 300);
stage.setScene(scene);
}
}
Label >>
Label(String text)
setText(String text)
String getText()
Button >>
Button(String text)
setOnAction(EventHandler handler)
EventHandler (an interface) >> handle(T event)
TextField >>
TextField()
setText(String text)
String getText()
TextArea >>
TextArea()
String getText()
setText(String text)
append(String text)
2. TableView – Sample code segments
Create table view >>
TableView tableView = new TableView();
Define columns >>
TableColumn idColumn = new TableColumn("Id");
idColumn.setCellValueFactory(new PropertyValueFactory("Id"));
tableView.getColumns().add(idColumn);
10Set data items >>
List list = new ArrayList();
list.add(new Product("p40", "lights", 40.0, true));
ObservableList tableData= FXCollections.observableArrayList(list);
tableView.setItems(tableData);
Define filter >>
// Define filtered list and sorted list
FilteredList filteredList = new FilteredList<>(tableData,p -> true);
SortedList sortedList = new SortedList<>(filteredList);
tableView.setItems(sortedList);
//bind the comparator properties
sortedList.comparatorProperty().bind(tableView.comparatorProperty());
// Define a text field and listener to set filtered list’s predicate
TextField filterTF = new TextField();
filterTF.textProperty().addListener((observable, oldValue, newValue) -> {
filteredList.setPredicate(product -> {
if (newValue == null || newValue.isEmpty())
return true;
if (product.getName().contains(newValue))
return true;
else
return false;
});
});
Access selected rows >>
Product product = tableView.getSelectionModel().getSelectedItem();
// To refresh the table view, if necessary
tableView.getColumns().get(0).setVisible(false);
tableView.getColumns().get(0).setVisible(true);
3. JDBC
Sample program skeleton >>
import java.io.*;
import java.sql.*;
public class JDBCSyntaxDemo
{
public static void main(String [] args) throws Exception
{
// prepare to connect to MySQL database (on the local server)
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){e.printStackTrace();}
11String databaseURL = "jdbc:mysql://localhost:3306/CatalogDB";
String username = "";
String password = "";
Connection connection = null;
PreparedStatement preparedStatement = null;
// connect to the database
connection = DriverManager.getConnection(databaseURL,username,
password );
// perform a query
String query = "select * from product where price >= ?";
preparedStatement = connection.prepareStatement(query);
preparedStatement.setDouble(1, 19.99);
ResultSet rs = preparedStatement.executeQuery();
// process the query result
while (rs.next()) {
String id = rs.getString(1);
...
System.out.println(...);
}
//disconnect from the database
preparedStatement.close();
connection.close();
}
}
Basic syntax of SQL Statements >>
INSERT INTO table VALUES (value1, value2, ...)
UPDATE table SET column1 = value1, column2 = value2, ... [WHERE condition]
SELECT [* | columns] FROM tables [WHERE condition] [ORDER BY columns]
4. Web Services
Sample method to provide a web service >>
import ...
public class CatalogWS extends HttpServlet {
...
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
try {
// Get data sent with the request
BufferedReader in = request.getReader();
String data = new String();
String line = in.readLine();
...
// Send back the representation of the product in JSON
response.setContentType("application/json");
PrintWriter out = response.getWriter(); out.print(data);
}
catch(Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
Sample request method of a web service client class >>
import …
public class CatalogWSClient {
...
// Request to add a product
public void add(String id, String name, double price, boolean onSale)
throws Exception {
// Construct the Product object
// and convert it to a JSON string (called sentData)
...
// Make the REST request (BASE_URL is the URL to access the servlet)
// (Assume this and other helper methods are availabe)
HttpURLConnection connection = makeRESTRequest(BASE_URL,"POST",
sentData);
// Process response code. Throw exception if encounter error
processResponseCode(connection);
// IF reach this point, request is successful
// Extract received data in JSON
String receivedData = getReceivedData(connection);
// Convert JSON string to Product instance, if necessary
...
}
}
Conversions between JSON String and Objects (using Gson) >>
// Making an instance of Gson
Gson gson = new Gson();
// Convert object to JSON string
String data = gson.toJson(product);
// Convert JSON string to object
Product product = gson.fromJson(data, Product.class);
// Convert list of simple objects to JSON string
String data = gson.toJson(product);
Some useful HTTP codes
HTTP Code
Description
HTTP Code
Description
200
OK
401
Unauthorized
201
Created
403
Forbidden
204
No Content
404
Not Found
304
Not Modified
409
Conflict
400
Bad Request
500
Internal Server Error
Note: • 2xx HTTP Codes represents SUCCESS of requested action
• 3xx HTTP Codes represents REDIRECTION of requested action
• 4xx HTTP Codes represents Client Error of requested action
• 5xx HTTP Codes represents Server Error or requested action