Want the quickest and easiest way to get started with db4o? Use the following Db4oUtil class. This class is very similar to the HibernateUtil class that you may be familiar with if you're a Hibernate user. It uses a thread local object so it's thread safe, makes multi-tier usage a no brainer and it's just plain simple to use.
The simple step-by-step for this tutorial:
- Copy the Db4oUtil.java code below into a new class
- Use the Db4oUtil methods in your code, samples below
That is it... seriously. You can optionally tweak the fields in Db4oUtil to your liking, like you'll want to change the YAPFILENAME field for each application you will use this with.
Db4oUtil.java
public class Db4oUtil {
// EDIT THESE SETTINGS
private static final String YAPFILENAME = "test.db4o.yap";
private static final int PORT = 0;
/*
If you want the server to be networked, change the port number above and uncomment the USER, PASSWORD lines below/
Then in getObjectServer, uncomment the objectServer.grantAccess line
*/
//private static final String USER = "username";
//private static final String PASSWORD = "password";
private static ObjectServer objectServer;
private static final ThreadLocal dbThreadLocal = new ThreadLocal();
public static ObjectContainer getObjectContainer() {
ObjectContainer oc = (ObjectContainer) dbThreadLocal.get();
if (oc == null || oc.ext().isClosed()) {
oc = getObjectServer().openClient();
dbThreadLocal.set(oc);
}
return oc;
}
public static void closeObjectContainer() {
ObjectContainer oc = (ObjectContainer) dbThreadLocal.get();
dbThreadLocal.set(null);
if (oc != null) oc.close();
}
public synchronized static ObjectServer getObjectServer() {
if (objectServer == null) {
objectServer = getObjectServerForFilename(YAPFILENAME, PORT);
// and give access
//objectServer.grantAccess(USER, PASSWORD);
}
return objectServer;
}
public static void shutdown() {
if (objectServer != null) {
objectServer.close();
}
}
public static ObjectServer getObjectServerForFilename(String yapfilename, int port) {
File parentDir = getDbDirectory();
File dbfile = new File(parentDir, yapfilename);
// for replication //////////////////////////
Db4o.configure().generateUUIDs(Integer.MAX_VALUE);
Db4o.configure().generateVersionNumbers(Integer.MAX_VALUE);
// other options
Db4o.configure().exceptionsOnNotStorable(true);
Db4o.configure().objectClass("java.math.BigDecimal").translate(new com.db4o.config.TSerializable());
// now open server
ObjectServer objectServer = Db4o.openServer(dbfile.getPath(), port);
return objectServer;
}
private static File getDbDirectory() {
// will store data files in {user.home}/db4o/data directory
String dbfile = System.getProperty("user.home") + "/db4o/data";
File f = new File(dbfile);
if (!f.exists()) {
f.mkdirs();
}
return f;
}
}
You can edit the fields at the top to modify your database filename, etc.Using Db4oUtil
This is a simple code sample of usage:// Get ObjectContainer - you can repetitively call this function in different methods without the need to pass the ObjectContainer aroundThat's all there is to it!
ObjectContainer oc = Db4oUtil.getObjectContainer();
// YOUR CODE HERE - use the ObjectContainer and do all your stuff here
// Close ObjectContainer when done
Db4oUtil.closeDb();
// Close object server when completely exiting application
Db4oUtil.shutdown();

5 comments:
Is the db4oUtil.java class all I need to begin using db4o with Tomcat? Will the helper class be able to handle multiple connections to the db4o server like a typical web applications? I can't believe its could be that easy :)
Although this can be used in any applicaion, it can definitely handle multiple connections from multiple tomcat requests with no problem. For each request, you can use Db4oUtil.getObjectContainer() throughout the entire request cycle and you'll be sure to get the exact same ObjectContainer for each call. Be sure to close the connections at the end of each request though - Db4oUtil.closeObjectContainer().
Also, if you think you'll be getting heavy traffic, you may want to plug a Connection Pooling mechanism in there.
Can someone please read this topic: http://developer.db4o.com/forums/thread/29406.aspx on the db4o forum, i'm having too much problems with duplicating objects when storing object that has another object in it. I made my program just like travis reeder said, I should be getting the same objectcontainer over and over, but this seems not to be the case...
Marko, you will get the same ObjectContainer in the same thread until you call Db4oUtil.closeObjectContainer(). In a web application if you're using a ServletFilter to close it, then it will be the same ObjectContainer for the life of a single request.
Generally, you'll have to re-get your object when submitting, then copy the fields. This is a big pain, I realize, but hopefully db4o will have better ID support soon. Keep an eye on COR-177.
I make good use of BeanUtils from Apache for copying object fields.
i need a code for space ,planet program
im giving the specification
Intermediate Object-Oriented Programming
Assignment - Semester 1, 2008
Due Date: 9.30am 7th April 2008
Delays caused by computer downtime cannot be accepted as a valid reason for a late submission without penalty. Students must plan their work to allow for both scheduled and unscheduled downtime.
Submission Details
You must submit an electronic version of your assignment on latcs6 using the submit command. Ensure you submit all required files. Files should be submitted one file at a time. For example, the file SpaceProgram.java would be submitted with the command:
> submit IOO SpaceProgram.java
This is an individual Assignment. You are not permitted to work as a group when writing this assignment.
Copying, Plagiarism: Plagiarism is the submission of somebody else’s work in a manner that gives the impression that the work is your own. The Department of Computer Science and Computer Engineering treats plagiarism very seriously. When it is detected, penalties are strictly imposed. Refer to the unit guide for further information and strategies you can employ to avoid a charge of academic misconduct. All reports and source code will be electronically checked for plagiarism.
Return of Assignment: You will receive a marking sheet with a mark break down within three weeks of submission.
Please Note: While you are free to develop the code for this assignment on any operating system, your solution must run on the latcs6 system.
Assignment Objectives
• To analyse, a problem in an object-oriented manner, and then design and implement an object-oriented solution
• To practise using inheritance in Java.
Problem Description
Samantha is an amateur astronomer who likes to view and record the celestial bodies she observes through her telescope. She would like to have a program that allows her to keep information about what she observes and to query the system to find out interesting facts such as which of the stars she has recorded is the furthest away from earth, or which of the celestial bodies she has seen is the largest.
She has already started to keep some facts in a file about the stars, planets, dwarf planets and moons she has seen. Your job is to write a program to read these facts from a file and provide a user interface to add and edit the information stored. You will also provide some query facilities to answer questions that interest Samantha.
Stars
Stars are stored in the file over 6 lines. For example:
Star
Altair
1.7
A
IV
16.73
• The first line of every entry is the type of the celestial object, in this case Star.
• The second line is the name of the star which may be one or more words.
• The third line is the radius of the star expressed in solar radius units. One solar radius is approximately 695,500 km.
• The fourth line is the spectral type. This classification is based on the colour of the star (its spectrum).
Class O – blue
Class B – blue white
Class A – white
Class F – yellowish white
Class G – yellow
Class K – orange
Class M – red
Class W – superluminous blue
Class L – dark red
Class T – cool brown dwarf
Class Y – ultra cool brown dwarf
Class C – carbon star
Class S – between a class M and carbon star
Class D – white dwarf
• The fifth line is the basic Yerkes spectral classification. This is a classification based on the luminosity of the star. There are seven possible values.
I – supergiants
II – bright giants
III – normal giants
IV – subgiants
V – dwarfs
VI – subdwarfs
VII - white dwarfs
• The sixth line is how far away the star is. The measurement is given in light years.
Planets
For planets the information is stored on 6 lines. For example:
Planet
Neptune
24764.0
1.0243 26
60190.0
48
• The first line of every entry is the type of the celestial object, in this case Planet.
• The second line is the name of the planet which may be one or more words.
• The third line is the radius of the planet expressed in kilometres.
• The fourth line is the mass of the planet in kilograms. This line contains the mantissa and exponent of the planet’s mass expressed in scientific notation. For example, for the planet Neptune the mass of the planet is 1.0243 x 1026kg
• The fifth line is the orbital period of the planet in days. This is how long it takes for the planet to orbit their star.
• The sixth line is the temperature of the planet in degrees Kelvin.
Dwarf Planets
Dwarf planets are like planets in that they are also natural satellites of a star, but they are not big enough to be classified as planets, but are larger than asteroids.
For Dwarf Planets the information takes 5 lines. For example:
DwarfPlanet
Ceres
480
9.43 20
167
• The first line is the type of the celestial object, in this case DwarfPlanet.
• The second line is the name of the dwarf planet which may be one or more words.
• The third line is the radius of the dwarf planet expressed in kilometres.
• The fourth line is the mass of the dwarf planet in kilograms. This line contains the mantissa and exponent of the dwarf planet’s mass expressed in scientific notation.
• The fifth line is the temperature of the dwarf planet in degrees Kelvin.
Moons
Information about moons is stored over 6 lines. For example:
Moon
Ganymede
2634.1
1.4819 23
Jupiter
110
• The first line is the type of the celestial object, in this case Moon.
• The second line is the name of the moon which may be one or more words.
• The third line is the radius of the moon expressed in kilometres.
• The fourth line is the mass of the moon in kilograms. This line contains the mantissa and exponent of the moon’s mass expressed in scientific notation.
• The fifth line is the name of the planet or dwarf planet that the moon orbits (i.e. the moon is a satellite of the planet or dwarf planet).
• The sixth line is the temperature of the moon in degrees Kelvin.
Unknown Values
In the data files, if a numeric value was not known a -1 was entered.
If a string or character value was not known a hyphen ‘-‘ was entered.
Task 1
Design and implement a class hierarchy to represent the celestial objects in this program.
Consider whether any methods or classes should be abstract.
Task 2
Write a menu-based system that repeatedly asks the user what task they would like to do and then carries out that task. The menu should look as follows:
------------------------------------------------
A - load from file
B - display to screen
C - add a new space body
D - write to file
E - display by size
F - display by name
G - display moons of planet/dwarf planet
H - display all space bodies in temperature range
I - display a given space body
J – display largest space body
K – display smallest space body
L – display most distant object
M - exit program
------------------------------------------------
Task 3
Implement the required functionality of each menu option:
A) Load from file
Ask the user for the name of a text file containing information about celestial objects, then load the information stored in that file.
If the file does not exist then a warning message must be displayed and the program goes back to the menu.
B) Display to screen
Displays all the space bodies stored in the system to screen. Each space body should be formatted as in the following examples:
Star: Achernar
spectral type = C
classification = V
radius = 10.0 solar radii
distance = 144.0 ly
Moon: Charon
radius = 603.5 km
mass = 1.52 x 10^21 kg
temp = 53.0 K
satellite of Pluto
DwarfPlanet: Eris
radius = 1300.0 km
mass = 1.67 x 10^22 kg
temp = 42.0 K
Planet: Mars
radius = 3396.0 km
mass = 6.4185 x 10^23 kg
temp = 227.0 K
orbital period = 686.971 days
C) Add a new space body
This should prompt the user for the type of a new object to add, and then, depending on the type they enter, prompt for values for the appropriate fields. For example:
Add a Star, Planet, DwarfPlanet or Moon? star
Enter the name of the Star: Achernar
Enter the radius: 10
Enter the type: C
Enter the classification: V
Enter the distance: 144
D) Write to file
Ask the user for the name of a text file to write information to then write the information to the file in the format initially used.
If the file cannot be created then a warning message must be displayed and the program goes back to the menu.
E) Display by size
Display all the objects in descending order of size (based on radius). If an object has a negative radius recorded, indicating an unknown value, it shouldn’t be displayed. Use the format given in part B) for each object displayed.
F) Display by name
Display all the objects in ascending alphabetical order. The ordering should be case insensitive. Use the format given in part B) for each object displayed.
G) Display moons of planet/dwarf planet
Ask the user for the name of a planet or dwarf planet and then display all the moons of it. Use the format given in part B) for each moon displayed.
H) Display space body in temperature range
Asks the user to enter the minimum and maximum temperature in Kelvin and then displays the type, name and temperature of all space objects with temperatures between those values. For example:
Enter minimum temp in Kelvin: 60
Enter maximum temp in Kelvin: 230
Planet - Mars - 227.0 K
Planet - Jupiter - 120.0 K
Moon - Europa - 103.0 K
Planet - Saturn - 88.0 K
DwarfPlanet - Ceres - 167.0 K
Moon - Ganymede - 110.0 K
Moon - Callisto - 134.0 K
Moon - Io - 130.0 K
Moon - Titan - 93.7 K
Moon - Rhea - 76.0 K
Moon - Titania - 60.0 K
Moon - Oberon - 61.0 K
Moon - Iapetus - 100.0 K
I) Display a given space body
Ask the user for the name of a space body and display all the information about the space body with that name using the format given in part B). If no space body with that name exists in the system, a warning should be given to the user and control returned to the menu.
J) Display largest space body
Display the space body in the system with the largest radius using the format shown in part B).
.
K) Display smallest space body
Display the space body in the system with the smallest radius using the format shown in part B)
L) Display most distant object
Display the object in the system that is furthest away (has the greatest distance) using the format shown in part B).
For all tasks
You may assume that the user always inputs correctly at the keyboard and that the file is in the correct format. You should however catch the exceptions that may be generated by the opening of files within the program.
Submission requirements
Assignments are to be submitted electronically on latcs6. You must submit all .java files. The program must be able to be compiled with the command
javac *.java
and run with the command
java SpaceProgram
There is a sample initial file in the directory ~csilib/cse1ioo/assignment for you to start with.
The marking scheme is as follows:
Task 1 – 15%
Marks are awarded here for the design and implementation of an appropriate class hierarchy. While this percentage is not high a good hierarchy design will make the tasks in part 3 significantly easier.
Task 2 – 10%
Marks are awarded here for a correctly functioning menu system.
Task 3 – 75%
Marks are awarded here for correctly functioning menu options.
A - load from file (10%)
B - display to screen (5%)
C - add a new space body (10%)
D - write to file (5%)
E - display by size (8%)
F - display by name (5%)
G - display moons of planet/dwarf planet (5%)
H - display space body in temperature range (5%)
I - display a given space body (5%)
J - display largest space body (5%)
K - display smallest space body (5%)
L - display most distant object (5%)
M - exit program (2%)
This assignment constitutes 10% of your overall mark in CSE1IOO.
Post a Comment