Skip to content

Commit 467c880

Browse files
committed
2 parents 7520984 + b408c0b commit 467c880

36 files changed

+6701
-16
lines changed

java/AoJ/README.md

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,15 @@ better to get it to the community as soon as we could. We hope that you agree.
3636
## Building AoJ
3737

3838
AoJ and ADBA require JDK 9 or later. Download ADBA from the
39-
[OpenJDK sandbox](http://hg.openjdk.java.net/jdk/sandbox/file/9d3b0eb749a9/src/jdk.incubator.adba).
40-
It does not have any dependencies outside of Java SE. Download AoJ from
39+
[OpenJDK sandbox](http://hg.openjdk.java.net/jdk/sandbox/file/JDK-8188051-branch/src/jdk.incubator.adba/share/classes). It does not have any dependencies outside of Java SE.
40+
41+
For building the API modules:
42+
```
43+
$ mkdir -p mods/jdk.incubator.adba
44+
$ javac -d mods/jdk.incubator.adba/ $(find jdk.incubator.adba -name "*.java")
45+
$ jar --create --file=mlib/jdk.incubator.adba.jar --module-version=1.0 -C mods/jdk.incubator.adba/ .
46+
````
47+
Download AoJ from
4148
[GitHub](https://github.com/oracle/oracle-db-examples/tree/master/java/AoJ). Both
4249
are modularized so be sure to include the module-info.java files. AoJ depends on
4350
ADBA. The AoJ sample file depends on JUnit which is included with most IDEs but is
@@ -106,8 +113,8 @@ introduction to ADBA see the [JavaOne 2017 presentation](http://www.oracle.com/t
106113
}
107114
// wait for the async tasks to complete before exiting
108115
ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.MINUTES);
109-
}```
110-
116+
}
117+
```
111118

112119
## AoJ Design Spec in 100 words or less
113120

java/README.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
# Java based examples
2-
This is a repository of sample code that will demonstrate various concepts to assist Java developers in designing applications for accessing and processing data from the Oracle Database, leveraging Java Database Connectivity (JDBC), Universal Connection Pool (UCP); or running Java code directly in the database leveraging the embedded JVM (a.k.a. OJVM).
3-
2+
This is a repository of sample code that will demonstrate various concepts to assist Java developers in designing applications for accessing and processing data in the Oracle Database, leveraging Java Database Connectivity (JDBC), Universal Connection Pool (UCP); or running Java code directly in the database leveraging the embedded JVM (a.k.a. OJVM).
43
We have just added the AoJ sub-repository for the Asynchronous Java Database Access (ADBA) over JDBC.
54

6-
# What's in Oracle database 12c Release 2 for Java Developers?
7-
* **Java 8**: Java 8 in JDBC/UCP and OJVM; JDBC 4.2
8-
* **Performance**: JIT (OJVM), Network Compression over WAN (JDBC), Configurable connection health check frequency (UCP), PL/SQL Callbace interface (JDBC)
9-
* **Scalability**: Shared Pool for Multi-Tenant Database (UCP), Shared Pool for Sharded database (UCP), Sharding Key APIs (JDBC, UCP), DRCP Proxy session sharing, DRCP support for multiple labels
10-
* **High-Availability**: Java APIs for FAN events (SimpleFan.jar), Planned Maintenance in the driver (JDBC), Application Continuity for XA Datasources, Transaction Guard for XA Datasource
11-
* **Security**: SSL v1.2 / TLS v 1.2 (JDBC)
12-
* **Manageability**: XMLconfiguration (UCP), Enable/disable/suspend/resume feature level logging (JDBC), MAX_THINK_TIME for Transactions in progress (DRCP), new statistics view and AWR reports
13-
* **Ease of Use** : Web Services Callout (OJCM), Long Identifiers (OJVM), PL/SQL Boolean (JDBC), Debugger for OJVM (Java Debug Wire Protocol)
5+
## JDBC
6+
Has the basic examples for JDBC and the Universal Connection Pool (UCP) code samples.
7+
## OJVM
8+
Has code samples for running Java in the database foreground process for in-place processing using the embedded JVM.
9+
10+
## HRWebApp
11+
A complete end to end MVC application.
12+
13+
## AoJ
14+
Has code samples for learning the Asynchronous Database Access over vanilla/synchronous JDBC. This is for functional testing only.
1415

15-
# [White paper](http://bit.ly/2orH5jf)
16-
# [See our OTN landing page for more information and resources](http://www.oracle.com/technetwork/database/application-development/java/overview/index.html)
16+
# [See our OTN landing page for more information and resources](http://www.oracle.com/technetwork/database/application-development/jdbc/overview/index.html)
Lines changed: 307 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,307 @@
1+
/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.*/
2+
/**
3+
* DESCRIPTION
4+
*
5+
* This code sample illustrates the usage of below Oracle column data types -
6+
* <p>
7+
* DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE and TIMESTAMP WITH LOCAL TIME ZONE
8+
* </p>
9+
* The code sample creates a simple table with these data types and performs
10+
* insert, update, and retrieval operation on the table.
11+
* <p>
12+
* It is required that applications have Oracle JDBC driver jar (ojdbc8.jar) in
13+
* the class-path, and that the database backend supports SQL (this sample uses
14+
* an Oracle Database).
15+
* </p>
16+
* <p>
17+
* To run the sample, you must enter the DB user's password from the console,
18+
* and optionally specify the DB user and/or connect URL on the command-line.
19+
* You can also modify these values in this file and recompile the code.
20+
* </p>
21+
*
22+
* java DateTimeStampSample -l <url> -u <user>
23+
*
24+
*/
25+
import java.io.BufferedReader;
26+
import java.io.InputStreamReader;
27+
import java.sql.Connection;
28+
import java.sql.Date;
29+
import java.sql.PreparedStatement;
30+
import java.sql.ResultSet;
31+
import java.sql.SQLException;
32+
import java.sql.SQLType;
33+
import java.sql.Statement;
34+
import java.sql.Timestamp;
35+
import java.time.LocalDateTime;
36+
import java.time.ZonedDateTime;
37+
38+
import oracle.jdbc.OracleType;
39+
import oracle.jdbc.pool.OracleDataSource;
40+
41+
public class DateTimeStampSample {
42+
43+
// Either modify user and url values to point your DB or
44+
// provide these values using command line arguments.
45+
private static String user = "myuser";
46+
private static String password = "mypassword";
47+
private static String url = "jdbc:oracle:thin:@//myhost:1521/myservice";
48+
49+
public static void main(String[] args) throws Exception {
50+
51+
// These 2 can be either default or from command-line
52+
url = getOptionValue(args, "-l", url);
53+
user = getOptionValue(args, "-u", user);
54+
55+
// DB user's Password must be entered
56+
readPassword(" Enter Password for " + user + ": ");
57+
58+
DateTimeStampSample demo = new DateTimeStampSample();
59+
demo.run();
60+
}
61+
62+
void run() throws SQLException {
63+
try (Connection conn = getConnection()) {
64+
65+
// Truncate the existing table
66+
truncateTable(conn);
67+
68+
// employee details
69+
int empId = 1001;
70+
Date dateOfBirth = Date.valueOf("1988-09-04");
71+
LocalDateTime joiningDate = LocalDateTime.now();
72+
ZonedDateTime dateOfResignation = ZonedDateTime
73+
.parse("2018-05-09T22:22:22-08:00[PST8PDT]");
74+
Timestamp dateOfLeaving = Timestamp.valueOf(LocalDateTime.now());
75+
Employee e = new Employee(empId, dateOfBirth, joiningDate,
76+
dateOfResignation, dateOfLeaving);
77+
show("\nInsert employee record into table with id = "+empId);
78+
insertEmployee(e, conn);
79+
80+
show("\nEmployee details of employee = " + empId);
81+
Employee emp = getEmployeeDetails(1001, conn);
82+
if (emp != null)
83+
emp.print();
84+
85+
show("Update the employee details of employee = " + empId);
86+
updateEmployee(empId, conn);
87+
88+
show("\nUpdated details of employee = " + empId);
89+
Employee emp1 = getEmployeeDetails(1001, conn);
90+
if (emp1 != null)
91+
emp1.print();
92+
93+
show("JDBCDateTimeSample demo completes.");
94+
}
95+
96+
}
97+
98+
/**
99+
* Inserts employee data into table using given connection.
100+
*
101+
* @param emp
102+
* Employee data
103+
* @param conn
104+
* Connection to be used to insert the employee data.
105+
* @throws SQLException
106+
*/
107+
private void insertEmployee(Employee emp, Connection conn)
108+
throws SQLException {
109+
final String insertQuery = "INSERT INTO EMP_DATE_JDBC_SAMPLE VALUES(?,?,?,?,?)";
110+
try (PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {
111+
SQLType dataType = null;
112+
113+
pstmt.setInt(1, emp.getId());
114+
pstmt.setDate(2, emp.getDateOfBirth());
115+
dataType = OracleType.TIMESTAMP_WITH_LOCAL_TIME_ZONE;
116+
pstmt.setObject(3, emp.getJoiningDate(), dataType);
117+
dataType = OracleType.TIMESTAMP_WITH_TIME_ZONE;
118+
pstmt.setObject(4, emp.getResignationDate(), dataType);
119+
pstmt.setTimestamp(5, emp.getDateOfLeaving());
120+
pstmt.executeUpdate();
121+
show("Employee record inserted successfully.");
122+
}
123+
}
124+
125+
/**
126+
* Fetches the employee data for given employee id.
127+
*
128+
* @param id
129+
* Employee id.
130+
* @param conn
131+
* Connection to be used to fetch employee data.
132+
* @return
133+
* @throws SQLException
134+
*/
135+
private Employee getEmployeeDetails(int id, Connection conn)
136+
throws SQLException {
137+
final String selectQuery = "SELECT EMP_ID, DATE_OF_BIRTH, DATE_OF_JOINING, "
138+
+ "DATE_OF_RESIGNATION, DATE_OF_LEAVING FROM EMP_DATE_JDBC_SAMPLE WHERE EMP_ID = ?";
139+
try (PreparedStatement pstmt = conn.prepareStatement(selectQuery)) {
140+
pstmt.setInt(1, id);
141+
try (ResultSet rs = pstmt.executeQuery()) {
142+
if (rs.next()) {
143+
int employeeId = rs.getInt(1);
144+
Date datOfBirth = rs.getDate(2);
145+
LocalDateTime dateOfJoining = rs.getObject(3, LocalDateTime.class);
146+
ZonedDateTime dateOfResignation = rs
147+
.getObject(4, ZonedDateTime.class);
148+
Timestamp dateOfLeaving = rs.getTimestamp(5);
149+
return new Employee(employeeId, datOfBirth, dateOfJoining,
150+
dateOfResignation, dateOfLeaving);
151+
} else {
152+
show("Employee record not found in the database.");
153+
return null;
154+
}
155+
}
156+
157+
}
158+
}
159+
160+
/**
161+
* Updates the employee record for given employee id.
162+
*
163+
* @param id
164+
* Employee id.
165+
* @param conn
166+
* Connection to be used to update employee data.
167+
* @throws SQLException
168+
*/
169+
private void updateEmployee(int id, Connection conn) throws SQLException {
170+
final String updateQuery = "UPDATE EMP_DATE_JDBC_SAMPLE SET DATE_OF_JOINING=? WHERE EMP_ID =?";
171+
try (PreparedStatement pstmt = conn.prepareStatement(updateQuery)) {
172+
SQLType dataType = OracleType.TIMESTAMP_WITH_LOCAL_TIME_ZONE;
173+
pstmt.setObject(1,
174+
ZonedDateTime.parse("2015-12-09T22:22:22-08:00[PST8PDT]"), dataType);
175+
pstmt.setInt(2, id);
176+
int updateCount = pstmt.executeUpdate();
177+
show("Successfully updated employee details.");
178+
}
179+
}
180+
181+
private void truncateTable(Connection conn) {
182+
final String sql = "TRUNCATE TABLE EMP_DATE_JDBC_SAMPLE";
183+
try (Statement st = conn.createStatement()) {
184+
st.executeQuery(sql);
185+
show("Table truncated successfully.");
186+
} catch (SQLException e) {
187+
showError("Truncate table operation failed.", e);
188+
}
189+
}
190+
191+
static Connection getConnection() throws SQLException {
192+
OracleDataSource ods = new OracleDataSource();
193+
ods.setURL(url);
194+
ods.setUser(user);
195+
ods.setPassword(password);
196+
Connection conn = ods.getConnection();
197+
return conn;
198+
}
199+
200+
private static void show(String msg) {
201+
System.out.println(msg);
202+
}
203+
204+
static void showError(String msg, Throwable exc) {
205+
System.out.println(msg + " hit error: " + exc.getMessage());
206+
}
207+
208+
// Get specified option value from command-line, or use default value
209+
static String getOptionValue(String args[], String optionName,
210+
String defaultVal) {
211+
String argValue = "";
212+
try {
213+
int i = 0;
214+
String arg = "";
215+
boolean found = false;
216+
while (i < args.length) {
217+
arg = args[i++];
218+
if (arg.equals(optionName)) {
219+
if (i < args.length)
220+
argValue = args[i++];
221+
if (argValue.startsWith("-") || argValue.equals("")) {
222+
argValue = defaultVal;
223+
}
224+
found = true;
225+
}
226+
}
227+
228+
if (!found) {
229+
argValue = defaultVal;
230+
}
231+
} catch (Exception e) {
232+
showError("getOptionValue", e);
233+
}
234+
return argValue;
235+
}
236+
237+
/**
238+
* Reads the password from console.
239+
*
240+
* @param prompt
241+
* @throws Exception
242+
*/
243+
static void readPassword(String prompt) throws Exception {
244+
if (System.console() != null) {
245+
char[] pchars = System.console().readPassword("\n[%s]", prompt);
246+
if (pchars != null) {
247+
password = new String(pchars);
248+
java.util.Arrays.fill(pchars, ' ');
249+
}
250+
} else {
251+
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
252+
show(prompt);
253+
password = r.readLine();
254+
}
255+
}
256+
257+
/**
258+
* A simple class to represent the employee table structure. An instance of
259+
* this class represents a row in employee table.
260+
*/
261+
static class Employee {
262+
private int id;
263+
private Date dateOfBirth;
264+
private LocalDateTime joiningDate;
265+
private ZonedDateTime dateOfResignation;
266+
private Timestamp dateOfLeaving;
267+
268+
Employee(int id, Date dateOfBirth, LocalDateTime joiningDate,
269+
ZonedDateTime dateOfResignation, Timestamp dateOfLeaving) {
270+
this.id = id;
271+
this.dateOfBirth = dateOfBirth;
272+
this.joiningDate = joiningDate;
273+
this.dateOfResignation = dateOfResignation;
274+
this.dateOfLeaving = dateOfLeaving;
275+
}
276+
277+
int getId() {
278+
return id;
279+
}
280+
281+
Date getDateOfBirth() {
282+
return this.dateOfBirth;
283+
}
284+
285+
LocalDateTime getJoiningDate() {
286+
return this.joiningDate;
287+
}
288+
289+
ZonedDateTime getResignationDate() {
290+
return this.dateOfResignation;
291+
}
292+
293+
Timestamp getDateOfLeaving() {
294+
return this.dateOfLeaving;
295+
}
296+
297+
void print() {
298+
show("/----------------------------------------------------------------/");
299+
show("ID : " + id);
300+
show("Date Of Birth : " + dateOfBirth);
301+
show("Joining Date : " + joiningDate);
302+
show("Resignation Date : " + dateOfResignation);
303+
show("Date of Leaving : " + dateOfLeaving);
304+
show("/----------------------------------------------------------------/\n");
305+
}
306+
}
307+
}

0 commit comments

Comments
 (0)