Lecture notes 7

Download Report

Transcript Lecture notes 7

CE203 - Application Programming
Part 5
Autumn 2016
CE203 Part 6
1
Reminder
• Assignment 2 is due 12th December at 11:59:59
– Demos in your regular lab slot next week!
– (more details soon)
Autumn 2016
CE203 Part 6
2
Learning objectives
•
•
•
•
•
•
JDBC refresh
Inner classes
Anonymous inner classes
Java security manager
Graphics methods
Using Frames (more details)
Autumn 2016
CE203 Part 6
3
Using JDBC
JDBC (Java Database Connectivity) allows Java to access
and manipulate relational SQL databases.
Communication to databases: by Strings containing SQL.
Communication from databases: in rows of a ResultSet.
String
e.g.
“SELECT …”
Database
ResultSet
Result table.
Autumn 2016
CE203 Part 6
4
JDBC – General Idea
http://ramj2ee.blogspot.co.uk/2014/07/jdbc-architecture.html#.VjJE425kpoy
Autumn 2016
CE203 Part 6
5
Connect
• Assuming the JDBC driver is setup steps to connect ...
1)
Load driver
Class.forName( "com.mysql.jdbc.Driver“ );
2)
Get connection
connection = DriverManager.getConnection(
"jdbc:mysql://localhost/mydb");
3)
Create statement object
statement = connection.createStatement();
Autumn 2016
CE203 Part 6
6
Executing Queries 1
Statement can be used as many times as required to perform
SQL queries and updates.
Queries performed using executeQuery()
ResultSet res = statement.executeQuery(
"SELECT name FROM employees");
res.next()
res
Autumn 2016
CE203 Part 6
Name
Salary
James
35k
Tom
23k
7
Using Metadata 1
getMetaData() obtains information about resultSet,
e.g. number of columns, names and types of objects.
The method returns an object of type ResultSetMetaData to
which we can apply methods
e.g. getColumnCount() and getColumnName().
Autumn 2016
CE203 Part 6
8
Executing Updates
To update a table use INSERT, UPDATE or DELETE
statements…
…apply executeUpdate() to a Statement object.
This method returns an int, indicating number of rows in the
table after update:
int i = statement.executeUpdate(
"DELETE FROM employees WHERE salary<1000");
System.out.println(
"Employees table now has " + i + " rows");
Autumn 2016
CE203 Part 6
Name
Name
Bob
Bob
John
Tim
Tim
Salary
Salary
1400
1400
950
2000
2000
Age
Age
23
23
21
34
34
9
Closing Connections
close() = close connections and release resources
Should be applied to any Statement objects created and then to
the Connection object (unless you use try-with-resources):
try
{
statement.close();
connection.close();
}
catch (SQLException e)
{
System.out.println(
"problems closing database");
}
Autumn 2016
CE203 Part 6
10
Prepared Statements 1
Parameterised Statements (or Stored Procedures).
Allow you to write a SQL statement with question marks
as placeholders. e.g.:
String updateString = "update COFFEES " +
"set SALES = ? "
"where COF_NAME like ?";
has two placeholders.
Autumn 2016
CE203 Part 6
11
Transactions 1
Allow batch processing of statements.
CAP = Consistent, Available, Partition Tolerant
A group of statements = a transaction.
auto-commit mode: an individual statement is treated as a
transaction (normal operation).
To disable auto-commit mode for a Connection con, write:
con.autoCommit(false);
Autumn 2016
CE203 Part 6
12
Questions?
Autumn 2016
CE203 Part 6
13
Learning objectives
•
•
•
•
•
•
JDBC refresh
Inner classes
Anonymous inner classes
Java security manager
Graphics methods
Using Frames (more details)
Autumn 2016
CE203 Part 6
14
Inner Classes 1
In Java a class may be declared within another class; such a
class is called an inner class.
Methods of inner class may access private instance variables
and methods of enclosing class.
Inner class
Conventional
arrangement
Frame
Frame
Autumn 2016
handleButton
handleButton
CE203 Part 6
15
Inner Classes 2
Inner classes frequently used for the event-handlers in GUI
programs.
On the following slides we write a square-calculating
application using this approach.
Since the inner class may access the members of the
FilledFrame class it is no longer necessary to store a
reference to the frame in the TextHandler object; hence no
constructor is needed.
Autumn 2016
CE203 Part 6
16
Inner Classes 3
// usual imports needed
public class FilledFrame extends JFrame
{
private JTextField input, result;
public FilledFrame()
{
JLabel prompt = new JLabel(
"Type a number and press return");
input = new JTextField(5);
result = new JTextField(25);
result.setEditable(false);
}
Autumn 2016
setLayout(new FlowLayout());
add(prompt); add(input);
add(result);
input.addActionListener(new TextHandler());
CE203 Part 6
17
Inner Classes 4
// class Arith2 continued
private class TextHandler implements ActionListener
{
}
public void actionPerformed(ActionEvent e)
{
String txt = e.getActionCommand();
input.setText("");
String answer = null;
try
{
int n = Integer.parseInt(txt.trim());
answer = "The square is " + n*n;
}
catch(Exception ex)
{
answer = "Invalid input“;
}
result.setText(answer);
}
} // end of inner class
// end of Arith class
Autumn 2016
CE203 Part 6
18
Inner Classes 5
Autumn 2016
CE203 Part 6
19
Inner Classes 6
Note, although the inner class was declared as private, its
actionPerformed method had to be public.
The class must correctly implement the ActionListener
interface;
this interface requires the actionPerformed method to
be public.
Unless an inner class is declared as static, objects of the class
must belong to objects of an outer class.
Therefore, an inner class object can be created only in the
non-static methods of the enclosing class.
Autumn 2016
CE203 Part 6
20
Inner Classes 7
If an inner class is public we can refer to objects of that class outside the
enclosing class.
The following slides present a student class, which contains a public inner class
to hold details of all of the student’s examination marks.
(The bodies for some of the inner class methods are omitted.)
Methods of enclosing class can
refer to objects of inner class.
Enclosing class
int method_1(){ …}
Public Inner class
Public inner class
Integer varA;
To refer to inner class (Marks) outside the Student class we use:
Student.Marks.
(We have already encountered this notation – Entry is an inner interface of Map.)
Autumn 2016
CE203 Part 6
21
Inner Classes 8
public class Student extends Person
{
private int regno;
private Marks marks;
public Student(String name, Date dob,
int regnum)
{
super(name, dob);
regno = regnum;
marks = new Marks();
}
public int regNumber()
{
return regNo;
}
// will inherit methods to get name and dob
Autumn 2016
CE203 Part 6
22
Inner Classes 9
// class Student continued
public void addMark(String module,
float mark)
{
marks.add(module, mark);
}
public Marks getMarks()
{
return marks;
}
public String toString()
{
// body omitted
}
Autumn 2016
CE203 Part 6
23
Inner Classes 10
// class Student continued
public class Marks {
private HashMap<String, Float> map;
public Marks() {
map = new HashMap<String, Float>();
}
public void add(String module, float mark) {
map.add(module, mark);
}
public float get(String module) {
return map.get(module).floatValue();
}
public float getAverage() { …… }
public String toString() { …… }
}
}
Autumn 2016
CE203 Part 6
24
Inner Classes 11
Assuming that variable lisa refers to a Student object
holding details about a student called Lisa, we retrieve and
print her marks for CE203 and CE204 using...
Student.Marks m = lisa.getMarks();
System.out.println("CE203: " +
m.get("CE203") +
"CE204: " +
m.get(CE204"));
Autumn 2016
CE203 Part 6
25
Take away message
• Inner classes provide a method for nesting classes within
one another.
• Members of the inner class are accessible to the enclosing
class
• Inner class object cannot be instantiated in static methods
of the enclosing class.
Autumn 2016
CE203 Part 6
26
Anonymous Inner Classes 1
When writing GUIs, an inner class that implements the ActionListener
interface often has just a single object, created and passed as an argument to
addActionListener().
class eventHandler implements ActionListener{…}
Button.addActionListener(new eventHandler() );
The object is effectively anonymous – no variable refers to it.
We can take this one step further by using an anonymous inner class.
Button.addActionListener(new actionListener(){…} );
An anonymous inner class must either implement an interface or extend an
existing class.
Autumn 2016
CE203 Part 6
27
Anonymous Inner Classes 2
Following slides demo how to use an anonymous inner class.
We replace
TextHandler constructor call
With
new ActionListener(){……}
(with the body of the text-handling class in the braces)
This call is an argument to a method
Therefore, don’t forget to place a closing parenthesis and
semicolon after the brace.
Note, despite the syntax, this code does not make a call to an
ActionListener constructor (an interface does not have a
constructor);
Instead the default constructor of the anonymous class is called.
Autumn 2016
CE203 Part 6
28
Anonymous Inner Classes 3
// usual imports needed
public class FilledFrame extends JFrame
{
private JTextField input, result;
public void FilledFrame()
{
JLabel prompt = new JLabel(
"Type a number and press return");
input = new JTextField(5);
result = new JTextField(25);
result.setEditable(false);
setLayout(new FlowLayout());
add(prompt);
add(input);
add(result);
Autumn 2016
CE203 Part 6
29
Anonymous Inner Classes 4
// FilledFrame constructor continued
input.addActionListener(
new ActionListener()
{
public void actionPerformed(
ActionEvent e)
{
// method body
}
}
);
}
}
Autumn 2016
CE203 Part 6
30
Anonymous Inner Classes 5
Anonymous inner classes can’t have constructors
-a constructor must have the same name as the class and an
anonymous inner class has no name.
Compiler generates a default constructor, which will call the noargument constructors for any object instance variables.
-if an anonymous class has object instance variables they
must be of classes that have no-argument constructors.
Additionally, if the anonymous class extends another class…
-constructor will call the no-argument constructor for
the superclass
-cannot use anonymous inner classes to extend classes that
have no such constructor.
Autumn 2016
CE203 Part 6
31
Anonymous Inner Classes 6
Uses of anonymous inner classes:
-extend an existing class
-replace inherited default methods.
On the following slides we write a program, Greeting, using
an anonymous inner class that extends an existing class.
Autumn 2016
CE203 Part 6
32
Anonymous Inner Classes 7
import javax.swing.*;
import java.awt.*;
public class Greeting
{
public static void main( String[] args )
{
Jframe frame = new Jframe();
frame.setSize( 500, 500 );
frame.setVisible( true );
add(new JLabel("Hello"), BorderLayout.NORTH);
frame.add( new Jlabel( “Hello”), BorderLayout.NORTH );
// main method continued on next slide
// previous version had
//
add(new GreetingPanel(),
//
BorderLayout.CENTER);
Autumn 2016
CE203 Part 6
33
Anonymous Inner Classes 8
// Greeting4 main method continued
frame.add(new JPanel()
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.blue);
g.drawRect(50, 100, 40, 30);
g.fillRect(120, 100, 30, 40);
}
},
BorderLayout.CENTER);
}
}
Autumn 2016
CE203 Part 6
34
Anonymous Inner Classes 9
Autumn 2016
CE203 Part 6
35
Take away messages
• Anonymous inner classes are created without an
associated name.
• Anonymous inner classes must either implement an
interface or extend an existing class.
• Anonymous inner classes don’t have constructors
– Instead an anonymous constructor is created that calls
no-argument constructors for all object instance
variables.
Autumn 2016
CE203 Part 6
36
Quiz and Break
• Quiz
kahoot.it
• Followed by: Break
5 minutes
Autumn 2016
CE203 Part 6
37
Learning objectives
•
•
•
•
•
•
JDBC refresh
Inner classes
Anonymous inner classes
Java security manager
Graphics methods
Using Frames (more details)
Autumn 2016
CE203 Part 6
38
Java Security Manager 1
• Java designed to work in a distributed
environment
• Code can be downloaded dynamically from a
variety of (un-trusted) sources
• Running such code alongside applications that
contain confidential information poses a risk.
• Security built into Java via access control
Autumn 2016
CE203 Part 6
39
Java Security Manager 2
• All access control decisions are done by a security
manager: java.lang.SecurityManager.
• A security manager must be installed into the Java runtime
to activate the access control checks.
• Applets are run with a security manager by default.
• Applications have no security manager by default.
Autumn 2016
CE203 Part 6
40
Java Security Manager 3
Two options to use a security manager:
• Set one via the setSecurityManager method in the
java.lang.System class, i.e..:
System.setSecurityManager(new SecurityManager());
• Call Java using appropriate command line arguments, e.g.:
javac -Djava.security.manager ...
Autumn 2016
CE203 Part 6
41
Java Security Manager 4
• A small set of default permissions are granted to code by class
loaders.
• Administrators can then flexibly manage additional code
permissions via a security policy.
• This is done via the java.security.Policy class. There is
only one Policy object installed into the Java runtime at any
given time.
• Policy files tell the security manager what is allowed by whom
(and what is not).
• Policies are defined declaratively in text files (usually created
via a policy tool utility)
Autumn 2016
CE203 Part 6
42
Java Security Manager 5
In Java 1.1 code was either…
Remote code
trusted
Local code
or
trusted
untrusted.
Untrusted code was run in a
“sandbox” and given only limited
access to vital resources e.g.
files.
JVM
Sandbox
Valuable resources (files etc.)
JDK 1.1 Security model
Local code was considered “safe”
remote code (e.g. applets) was
considered “unsafe”.
Autumn 2016
CE203 Part 6
43
Java Security Manager 6
In Java 2 onwards…
No built in concept that local code is
“trusted” and remote code
“untrusted”.
All code is checked against a
security policy when loaded.
Depending on policy the code is
then either allowed access to
resources or run in a sandbox.
Autumn 2016
CE203 Part 6
Local or Remote code
Security policy
Class loader
JVM
Sandbox
Valuable resources (files etc.)
JDK 2 Platform Security model
Code runs with different
permissions according to
security policy. Not built-in notion
of “trusted” code.
44
Java Security Manager 7
• System security is ensured by the use of protection domains.
• Domain: a set of objects that are directly accessible by the principle
• Principle: the entity in the system to which permissions are granted
(or denied).
• For example, a principle may be a class (or set of classes).
Domain
Files
Memory
Sockets
Autumn 2016
Keyboard
Suspicious looking
class
deleteFiles();
accessBankAccount();
stealMoney();
CE203 Part 6
Principle
45
Java Security Manager 8
• Domain categories
– System domain (access to files, sockets etc.)
– Application domain (access to memory, CPU etc.)
– etc.
• Domain:
– Encompasses set of classes with the same permissions.
– Determined by policy
• Java application environment manages mapping from code (classes and instances)
to protection domains and associated permissions
classA
classB
classC
Domain A
->
Permissions
Domain B
->
Permissions
Security policy
Classes in Java runtime
Autumn 2016
CE203 Part 6
46
Java Security Manager 9
• Example…
• Applets are not allowed to exit the virtual machine.
• Therefore, the exit() method of the RunTime class calls the checkExit() function in
the security manager.
• Security manager checks origin of exit request and throws exception if its invalid.
Public void exit( int status ) {
SecurityManager sm = System.getSecurityManager();
if (sm != null)
sm.checkExit( status );
exitInternal(status);
}
Autumn 2016
CE203 Part 6
47
Java Security Manager 10
Sample code snippet:
…
Permission perm = new
java.io.FilePermission("/tmp/abc", "read");
SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
sm.checkPermission(perm);
}
...
Autumn 2016
CE203 Part 6
48
Java Security Manager 10
http://docs.oracle.com/javase/8/docs/technotes/guides/security/overview/jsoverview.html
Autumn 2016
CE203 Part 6
49
Java Security Manager (Example)
//file: EvilEmpire.java
import java.net.*;
public class EvilEmpire
{
public static void main(String[] args) throws Exception
{
try
{
Socket s = new Socket("www.essex.ac.uk", 80);
System.out.println("Connected!");
}
catch (SecurityException e)
{
System.out.println("SecurityException:
could not connect.");
}
}
}
(see Niemeyer and Knudsen, 2005)
Autumn 2016
CE203 Part 6
50
Java Security Manager (Example) 2
Run this code without any parameters:
C:\> java EvilEmpire
Connected!
… and with security manager:
C:\> java –Djava.security.manager EvilEmpire
SecurityException: could not connect.
… and perhaps use your own policy file:
C:\> java –Djava.security.manager
-Djava.security.policy=EvilEmpire.policy
EvilEmpire
(you can of course also use IntelliJ to do this)
Autumn 2016
CE203 Part 6
51
Take away messages
• The security manager allows you to control which parts of
your code can access which resources.
• This allows you control access to sensitive resources.
• By default a security manager is loaded with applets but
not with desktop applications.
Autumn 2016
CE203 Part 6
52
Java Security Manager
• This has just been a quick overview.
• Check the Java homepage for more details, e.g.
http://docs.oracle.com/javase/8/docs/technotes/guides/
security/overview/jsoverview.html
Autumn 2016
CE203 Part 6
53
Learning objectives
•
•
•
•
•
•
JDBC refresh
Inner classes
Anonymous inner classes
Java security manager
Graphics methods
Using Frames (more details)
Autumn 2016
CE203 Part 6
54
Graphics Methods 1
We already encountered the drawString, setColor,
drawRect and fillRect methods from the Graphics
class;
these are normally used in paint and
paintComponent methods, which take an argument
of type Graphics.
drawLine() can be used to draw a line;
this method has four arguments, the x and y
coordinates of each end of the line, so, for example,
g.drawLine(0,10,30,40);
(0,10)
(30,40)
will draw a line from (0,10) to (30,40).
Autumn 2016
CE203 Part 6
55
Graphics Methods 2
clearRect(): similar to fillRect but draws the rectangle
in the background colour (effectively erasing anything that
was displayed in the area specified by the arguments).
drawOval() and fillOval() produce an oval instead of a
rectangle.
These methods take the same four arguments as drawRect()
x- and y-coordinates of the top-left corner
width and height
They draw an oval enclosed by the rectangle specified by the
arguments, touching the rectangle at the centre of each side.
If the rectangle is a square, the oval will of course be a circle.
Autumn 2016
CE203 Part 6
56
Graphics Methods 3
To draw a circle with centre coordinates (x,y) and radius r…
-top left-hand corner of the enclosing rectangle will be
(x-r,y-r)
-width and height of the rectangle will be the
diameter of the circle (i.e. twice the radius).
x-r,y-r
Hence we would use
r
g.drawOval(x-r,y-r,2*r,2*r);
Autumn 2016
CE203 Part 6
x,y
57
Graphics Methods 4
drawRoundRect()
and
fillRoundRect()
produce
rectangles with rounded corners;
they have six arguments:
-the first four are the same as the arguments of
drawRect(),
-the last two indicate the width and height of the
imaginary oval produced by combining the four arcs at
the corners.
Autumn 2016
CE203 Part 6
58
Graphics Methods 5
drawArc() and fillArc() produce a portion of an oval (an
outline or a segment);
they also have six arguments:
the first four are the same as drawOval(),
the fifth indicates the starting position of the arc by
specifying the angle in degrees (see the diagram on the next
slide),
the sixth indicates the number of degrees through
which the arc extends (positive numbers indicating
anticlockwise and negative numbers indicating clockwise).
Autumn 2016
CE203 Part 6
59
Graphics Methods 6
The segment shown below would be produced by
g.fillArc(10,10,300,200,10,40);
->
(10,10)
40⁰
<-
200
10⁰
<Autumn 2016
300
->
CE203 Part 6
60
Graphics Methods 7
drawPolygon() and fillPolygon() can produce polygons:
each takes three arguments:
two int arrays containing the x- and y-coordinates
respectively of the corners
an int indicating the number of corners.
For example we could use the following program fragment to
draw a solid triangle with corners at (10,10), (90,70) and (30,110).
(10,10)
int[] xCoords = { 10, 90, 30 };
int[] yCoords = { 10, 70, 110 };
g.fillPolygon(xCoords, yCoords, 3);
(90,70)
(30,110)
Autumn 2016
CE203 Part 6
61
Graphics Methods 8
If the third argument to drawPolygon() or fillPolygon()
is smaller than the size of the arrays only part of each array
will be used.
Thus, the same arrays can be reused to draw polygons with
different numbers of sides.
If the size of either of the arrays is smaller than the third
argument an exception will be thrown.
See also, drawPolyline() which does not connect the last
co-ordinate pair from the arrays with the first pair (i.e. it
draws an incomplete polygon).
Autumn 2016
CE203 Part 6
62
Graphics Methods 9
drawPolygon() and fillPolygon() can also be used with an
argument of type Polygon;
useful if we wish to store information about polygons
before they are drawn.
The Polygon class has a constructor that takes three arguments
similar to those of drawPolygon.
There is also a no-argument constructor that allows us to add
coordinates to a polygon one at a time using the addPoint
method:
Polygon p = new Polygon();
p.addPoint(10, 10);
p.addPoint(90, 70);
p.addPoint(30, 110);
g.drawPolygon(p);
Autumn 2016
CE203 Part 6
63
Learning objectives
•
•
•
•
•
•
JDBC refresh
Inner classes
Anonymous inner classes
Java security manager
Graphics methods
Using Frames (more details)
Autumn 2016
CE203 Part 6
64
Using Frames 1
We have seen GUI examples that extend the
JFrame class. We shall now explore the JFrame
class in more detail.
We start with a simple frame-based application…
Autumn 2016
CE203 Part 6
65
Using Frames 2
public class Greeting extends JFrame
{
public Greeting()
{
super("Greeting example");
setSize(300, 200);
setVisible(true);
}
}
Autumn 2016
public void paint(Graphics g)
{
super.paint(g);
g.drawString("Hello!", 20, 20);
g.setColor(Color.blue);
g.drawRect(50, 100, 40, 30);
g.fillRect(120, 100, 30, 40);
}
CE203 Part 6
66
Using Frames 3
The JFrame class has a constructor that takes a string
argument to specify the contents of the title bar of the
window.
We invoked this in our constructor using super.
We also used the constructor to specify the size of the
frame.
A frame is not displayed until it is explicitly made visible
so we need to make a call to the setVisible method; this
could be done elsewhere (e.g. in a main method that
creates a frame object) if we did not write a constructor.
Autumn 2016
CE203 Part 6
67
Using Frames 4
Reminder: we need a main method to create a Greeting object; this
could be placed in a separate class in a separate file, e.g.
public class Greet
{
public static void main(String args[])
{
JFrame myFrame = new Greeting();
myFrame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
}
}
Autumn 2016
CE203 Part 6
68
Using Frames 5
specifies what should
happen when the user clicks the close-box of the
window containing the frame.
This will usually be the termination of the program,
as in this example.
Other options include…
DISPOSE_ON_CLOSE, which causes the window to
be closed whilst leaving the program running (e.g.
skype)
DO_NOTHING_ON_CLOSE, which indicates that the
click should be ignored.
setDefaultCloseOperation()
Autumn 2016
CE203 Part 6
69
Using Frames 6
What if we want to do something specific when
the window is closed?
e.g. if the program has created several
frames we may wish to decrement the frame
count and terminate if it reaches zero.
In such circumstances it is necessary to add a
window listener (similar to an action listener) to
the frame.
Autumn 2016
CE203 Part 6
70
Summary
• Today we covered…
– Inner classes
– Anonymous inner classes
– Java security manager
– Graphics methods
– Frames
Autumn 2016
CE203 Part 6
71
Next week
• Threads
• More on the Java swing library
Autumn 2016
CE203 Part 6
72