Servlet and awt.Frame
hello there,
i'm a newbie with java and servlets... and i'm having this problem:
public class main extends HttpServlet {
private static final long serialVersionUID = 1L;
MyFrame a;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Hello World</title></head>");
out.println("<body> Hey there people!");
out.println("</body></html>");
out.close();
a = new MyFrame();
a.setVisible(true);
}and this is MyFrame:
public class MyFrame extends Frame {
private static final long serialVersionUID = 9176965981032835272L;
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox grigio = new Checkbox("Non schedulato", radioGroup, true),
arancio = new Checkbox("Schedulato in progress", radioGroup, true),
rosso = new Checkbox("Schedulato in ritardo", radioGroup, true),
verde = new Checkbox("Chiuso", radioGroup, true);
Panel azione = new Panel();
Button ok = new Button("ok");
public MyFrame() {
setLayout(null);
azione.setBounds(10, 30, 180, 200);
azione.setLayout(new BoxLayout(azione, BoxLayout.PAGE_AXIS));
azione.add(grigio);
azione.add(arancio);
azione.add(rosso);
azione.add(verde);
ok.setSize(180, 30);
azione.add(ok);
azione.setVisible(true);
add(azione);
setVisible(true);
setBounds(100, 100, 200, 260);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}i can't get the MyFrame opened even if it compile and run... i can see "Hey there people!" but no frame :(
what am i mistaking?
thanks in advance
This can't be real...
Servlets are server-side components. Somewhere on your server, a Frame is created. You, as the client, will never notice that.
Similar Messages
-
Very simple Java AWT Frame resize question
In the following code, I create an awt Frame. Unfortunately, when I run the resulting Java application (on Windows) and use the mouse to resize the window, none of the Frame's resize/setSize methods get called. Can anyone explain why this is?
Thanks
Greg
import java.awt.* ;
public class Junk extends Frame {
public static void main (String args[])
Junk j = new Junk ();
j.show ();
public void resize(Dimension arg0)
super.resize(arg0);
public void resize(int arg0, int arg1)
super.resize(arg0, arg1);
public void setSize(Dimension arg0)
super.setSize(arg0);
public void setSize(int arg0, int arg1)
super.setSize(arg0, arg1);
}When the user resizes the frame with the mouse, the resizing action probably happens entirely on the Frame's peer, without the java.awt.Frame getting involved at all. setSize() and [deprecated] resize() allow an application to programmatically change the size of a Frame, but the Frame just passes the new size to its peer.
If you want to detect when your Frame has been resized, use addComponentListener to register a component listener on the Frame, and then put your code in the componentResized method of the listener. -
How to remove title bar in awt frame?
how can i remove the title bar of frame and make it fullscreen so as to cover all the desktop?
how can i remove the title bar of frame and make it
fullscreen so as to cover all the desktop?foll should suffice in a simple situation
import java.awt.Window;
import java.awt.Frame;
import java.awt.Toolkit;
public class BigWindow extends Frame
public BigWindow()
//get screen size
int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
//make parent frame invisible
this.setVisible(false);
//create a new window without borders and titlebar
Window window = new Window(this);
window.setSize(width,height);
window.setVisible(true);
public static void main(String args[])
new BigWindow();
} -
How to disable the maximise button of a awt Frame
Hi guys..
Is there any way to disable the maximise button of the awt Frame (Not JFrame). I have tried the
setResizable(false), but that one is not solving my problem. Any code will highly be Appreciated.
tks in advance
Jameel
My ids r
[email protected]
[email protected]i used setResizable and it disables theframes max button
import java.awt.*;
import java.awt.event.*;
public class frame extends Frame
public frame()
setSize(200,200);
setVisible(true);
setResizable(false);
public static void main(String a[])
new frame();
what do u really need -
How to prevent the automatic full-white repainting of an AWT Frame?
Using Java 1.6.0, Windows XP, 1.6.0-b105 Client VM I have the following problem:
I made a double buffered AWT frame. But it still flashes sometimes. It gives one flash about 6 seconds after start of application. There seems to be an incoming event "for no discernible reason". I have overridden all paint/repaint/update methods in my Frame sub class.
These unwanted flashes are caused by the AWT painting the frame in white and then calling paint.
I may have caught these weird calls:
The good/normal case looks like:
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1206)
at xed.xed_Frame.paint(xed_Frame.java:125)
at xed.xed_Frame.update(xed_Frame.java:119)
at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
at sun.awt.RepaintArea.paint(RepaintArea.java:216)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:301)
at java.awt.Component.dispatchEventImpl(Component.java:4486)
at java.awt.Container.dispatchEventImpl(Container.java:2116)
at java.awt.Window.dispatchEventImpl(Window.java:2429)
at java.awt.Component.dispatchEvent(Component.java:4240)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
The differences in the bad case: (Not all traces of this kind cause the flashing. But after all flashes there seems to be such a trace.)
at xed.xed_Frame.paint(xed_Frame.java:125)
at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
at sun.awt.RepaintArea.paint(RepaintArea.java:224)
at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:301)
So how do I stop these unwanted white redraws of the Frame?Accidentally found the answer:
System.setProperty("sun.awt.noerasebackground", "true"); -
Added Jcombobox into awt.frame causing handling event function cannot receive event
Dear Sir,
I want to ask how an awt.Choice can set the number of rows that it can display, like the method setMaximumRowCount in JCombobox. Since I want to set more row can be displayed, but choice no any method can set. And I have tried to add Jcombobox into awt.frame, then, the handling event function cannot receive event for the right-top cornet button(minimize, maximum, close).
Best Regards,please post a Short, Self Contained, Correct Example showing your problem.
bye
TPD -
Help needed on Servlets and JSTL
Hi
I am using tomcat 5.5 and JDK 1.5. What are the softwares I have to download for compiling servlets and creating JSTL ?. Help needed.
Thanks
IndyaRajaI tried compling servlet, but it is raising error
that coul not find package javax.servletWhat I did not mention... you need to add those JARs in the Classpath explicitly. You will find them in %TOMCAT_HOME%\common\lib. You atleast need to add servlet-api.jar to your Classpath. :) -
Difference between servlet and filter
difference between servlet and filter
Its not a secret you know; if you just read a little about what they are used for, you answer your own question plus many more to follow.
Servlet: http://en.wikipedia.org/wiki/Java_Servlet
Filter: http://www.oracle.com/technetwork/java/filters-137243.html -
Difference between servlet and ActionServlet
Difference between servlet and ActionServlet..
Anybody replyjsf_VWP5.5.1 wrote:
Difference between servlet and ActionServlet..
Anybody replyAs their name imply, ActionServlets like outdoor activities, whereas Servlets are rather contemplative types.
The only time Servlets exhibit behavior similar to ActionServlets, in under extremely stressful situations, like when a Servlet is being chased by a pit bull. -
How to get the query values from the url in a servlet and pass them to jsp
ok..this is the situation...
all applications are routed through a login page...
so if we have a url like www.abc.com/appA/login?param1=A¶m2=B , the query string must be passed onto a servlet(which is invoked before the login page is displayed)..the servlet must process the query string and then should pass all those values(as hidden values) to the login jsp..then user enters username and pswd, then there should be another servlet which takes all the hidden values of jsp and also username and pswd, authenticates the user and sends the control back to that particular application along with the hidden values...
so i need help on how to parse the query string from the original url in the servlet, pass it out to jsp, and then pass it back to the servlet and back to the original application...damnn...any help would be greatly appreciated...thanksok..this is the situation...Sounds like you have a bad design on your hands.
You're going to send passwords in a GET request as clear text? Nice security there.
Why not start with basic security and work your way up?
% -
Playback of clips only plays between 4 and 12 frames
Hi all,
I am fairly new to Premiere, have used After Effects CS4 to produce some clips, but need something that handles editing better, and I thought I would give Premiere CS4 a try.
Unfortunately, I can't get Source or Sequence preview working. I click the play button and the video plays for about 1/2 to 1/4 or a second (between 4 and 16 frames) and then stops, returning to the place where I hit play. Almost like I had selected an in and out of 14 frames and hit "play in to out".
The duration of the playback is random, but never more than a full second.
The computer I am on is:
Model Name: MacBook Pro
OS: Snow Leopard 10.6.2
Processor Name: Intel Core 2 Duo
Processor Speed: 2.4 GHz
L2 Cache: 3 MB
Memory: 4 GB
Bus Speed: 800 MHz
Chipset Model: GeForce 8600M GT
Bus: PCIe
VRAM (Total): 256 MB
Vendor: NVIDIA (0x10de)
RAM Size: 4 GB
Type: DDR2 SDRAM 667 MHz
HDD: 500Gb 7200RPM (50% empty)
Apple system updater says I am up to date.
I have Adobe Premiere CS4 installed (trial) 4.2.1 (003 (MC: 166418))
Adobe Updater says I am up to date.
I have done the following to try and resolve:
* Tried different source files (mp4, mov)
* Tried rendering a video in After Effects CS4 as MOV H264 and importing
* Tried putting still frames on the time line and playing those (no effects, no transitions)
* Tried playing no video, just music
* Ensure that "clear all markers" is done on the source and preview monitors
* Ensure loop is not playing
* Force in and out markers to a 5 second clip and press play
* Full deinstall and reinstall of all adobe products (I had some CS3 left overs that I cleaned out)
* Deleted all adobe application preferences folders before reinstall
* Deleted plugin cache
* Created new projects and tried all the above.
I have tried shutting down every other program before running Premiere, it is definitely not a resources problem, there is 3Gb of RAM free and CPUs sitting at 5% when I try this.
I am looking at buying Premiere, but if I can't get playback to work it's a bit of a waste
Anyway, any help or pointers would be appreciated!
MikelThanks everyone for the long thread and lots of comments, unfortunately I have tried them all.
I even purchased a full copy of Premiere Pro (as part of a Masters collection set) and this still has not fixed the problem.
The screen recording of my problem is exactly the same as the one linked to here: Screen Recording 2 720p.mov, and I am also going to open a support ticket with Adobe.
Another point is that it even does not work on a tiny video that I used (320 x 240px) Still same problems.
This is very frustrating.
It should be noted that After Effects and Encore both play videos fine in a similar situation, it is just Premiere that is bombing out.
See the first post for my configuration, it is still the same, except now I own a full copy of Premiere Pro as part of CS4 Masters collection.
Any further ideas?
Mikel -
Hello, 2 questionss here>is it possible or is there a way to convert all object s outlines in all frames to fills at once and not frame by frame? and why sometimes erases the outline instead of converting it to fill?
Hello, 2 questionss here>is it possible or is there a way to convert all object s outlines in all frames to fills at once and not frame by frame? and why sometimes erases the outline instead of converting it to fill?
-
Can only see first and last frame of clip in the timeline HELP PLEASE
Hi, my first time and I did look for an answer, but can't find one. I have premiere elements 4 and I am trying out ver. 9. In ver. 4 the clips in the timelin shows all the frames, but in ver. 9 it only shows the first and last frame of the clips. Is there any way to make all the frames show. By "all the frames", I mean the clips fill with frames.I liked to see all the frames in the timeline, it is easier for me to select and trim the bits out.
My specs are Core 2 Duo 6750, Nvidia 8600GTS, 4G Ram, Vista Home Premium. 3 HDD 3TB.
Thank you for answering
WernerAs for the GUI, PrE had one more like PrPro (the early versions), up through PrE 3. With PrE 4, they streamlined the GUI (and some of the operation), and went with the "dark look." PrPro went in that direction starting with CS3, and now, the two programs' GUI looks more alike - darker. Personally, I like PrPro 2.0's brighter GUI. Now, one can alter the brightness, but the contrast can work against doing much of that - give me the lighter GUI....
The look of PrE 4 thru PrE 9 is very similar, though things have moved about some. Still the look is similar. Same for PrPro CS 3 through CS 5.5.
As for the trial, things have changed in PrPro, as of CS 5.5. Once, the PrPro trial was very crippled, but had no watermark. No more. No crippling, and still no watermark. The trial for PrE is far less crippled, but does have the watermark. We do not know what changes might be coming with the trial of PrE10. We will just have to wait and see. One great option that Adobe offers is the 30-day, money-back guarantee. If you buy Premiere (either flavor), and use it for 29 days, but do not like it, then you return it for your money back. This is the full-paid version (both flavors) with nothing crippled, and no watermark. Not that many companies make such an offer. Basically, on can use the trial for 30 days, to see some of the powers of the program, and then buy it, and try it fully for another 29 days. If not completely satisfied, they get their money back - essentially a 59 day trial.
Were I doing AVCHD, I would definitely look at buying PrE 9, and giving it a 29 day shakedown. The only caveat is that AVCHD requires a lot of computer "horsepower," and not all computers (especially if more than a year, or so old) are up to that task. I find it amazing that a consumer format, like AVCHD, requires more computer power to process, than most professional formats, until one gets up to, say RED 2K/4K. However, that is the nature of the H.264 CODEC, and by that, I mean all H.264, not just the AVCHD version.
Good luck and happy editing,
Hunt -
How can I have a default servlet and an index.html?
Hi,
I writing a small webapp to test/understand the 2.2 Servlet Spec. I am deploying this as a WAR to Orion, Tomcat and Silverstream.
The app's name is: "myapp"
My application has an index.html, which is listed as the sole welcome-file in the welcome-file-list element in the app's web.xml.
The interesting thing is that, after adding a default Servlet (<url-pattern>/</url-pattern>), I can no longer access the app's index.html either implicitly or explicitly:
1. Implicit:
- http://localhost/myapp
- http://localhost/myapp/
2. Explicit:
- http://localhost/myapp/index.html
- http://localhost/myapp/index.html/
All of these invoke the Default Servlet in all 3 app servers.
Question: How can I have both a default Servlet and an index page?
Thanks in advance.
Milesyou can define it in the web.xml file
look at the dtd, element "welcome-file-list" -
Using database connection in a servlet and get errors after 8 hours
Hey,
I'm running a poker script using applet/servlets and it works great. But for some reason about about 8 hours that database layer stops working. At first I thought it was the connections to mySQL that were timing out (because im using connection pooling) but after turning pooling off (I now create the connection each time) I'm still seeing that same error (I can create a connection but when I do an action ex. like a select statment I get an error). What i'm wondering could it be that the driver I load with Class.forName() some how unloads it's self after x amount of time not being used? Not sure if that is it but if anyone could give me some insight that would be great. The Error i recieve is below:
INFO: Database Event:DatabaseController: Error executing database query.
ERROR: Communications link failure due to underlying exception:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: Software caused connection abort: recv failed
STACKTRACE:
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:104)
at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:144)
at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:172)
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1839)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2288)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2784)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1531)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1622)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2370)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2297)
at com.mysql.jdbc.Statement.executeQuery(Statement.java:1183)
at com.softnet.database.DatabaseController.executeDatabaseQuery(DatabaseController.java:190)
at com.softnet.games.GameServer.validateUser(GameServer.java:438)
at com.softnet.games.GameServer.handleData(GameServer.java:113)
at com.softnet.network.HttpConnectionThread.run(HttpServletListener.java:191)
** END NESTED EXCEPTION **
I know the query is good because it works all other times just not after about 8 hours.
--Z3r0CooLHey,
Thanks for the responces. For the connection pooling I would open 5 connections and keep them open. So i though maybe after 8 hours after not being used they would timeout. Thats why i turned off conection pooling and create a new connection each time. Anyways i'll post the code below incase i made a mistake somewhere.
package com.softnet.database;
/************************ DatabaseControler **************************/
import java.sql.*;
import java.util.*;
import com.softnet.database.DatabaseConnectionPool;
import com.softnet.database.DatabaseSettings;
public class DatabaseController
implements DatabaseListener
//Used to make sure the database driver is loaded
private boolean databaseDriverState = false;
//Used to store a database connection
private Connection databaseConnection = null;
//If to user connection pooling or not
private boolean useConnectionPooling = false;
//Used to hold the connection pool varible
private DatabaseConnectionPool connectionPool = null;
//Used to store database settings
private DatabaseSettings databaseSettings;
//Used to hold the DatabaseController listeners
private List databaseControllerListeners = new ArrayList();
//min number of connections for connection pool
private int minNumberOfConnections = 1;
//max number of connections for connection pool -1 is unlimited
private int maxNumberOfConnections = -1;
//DatabaseController Constructors
public DatabaseController(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController(DatabaseSettings databaseSettings, boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
public DatabaseController() {}
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Connection Pooling Get/Set
public boolean getConnectionPooling()
return useConnectionPooling;
public void setConnectionPooling(boolean useConnectionPooling, int minNumberOfConnections, int maxNumberOfConnections)
this.useConnectionPooling = useConnectionPooling;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
if(useConnectionPooling == true)
if(connectionPool == null)
connectionPool = new DatabaseConnectionPool(databaseSettings, minNumberOfConnections, maxNumberOfConnections);
connectionPool.addDatabaseListener(this);
else
if(connectionPool != null)
connectionPool.destroyConnections();
connectionPool.removeDatabaseListener(this);
connectionPool = null;
//Return if there connected
public boolean isConnected()
boolean isConnected;
if(databaseConnection != null)
isConnected = true;
else
isConnected = false;
return isConnected;
//Used to connect to database or get a connection for the connection pool
public void connect()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//If we dont have a current connection, make one
if(databaseConnection == null && databaseDriverState == true)
if(useConnectionPooling == false)
try
databaseConnection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch (SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error connecting to database. \nERROR: " + sqle.getMessage());
databaseConnection = null;
else
databaseConnection = connectionPool.getConnection();
//Used to disconnect from the database or give back the connection to the connection pool
public void disconnect()
if(databaseConnection != null)
if(useConnectionPooling == false)
try
//Close DB Connection
databaseConnection.close();
catch(SQLException ignore) {}
finally
databaseConnection = null;
else
connectionPool.returnConnection(databaseConnection);
databaseConnection = null;
public ResultSet executeDatabaseQuery(String sSQL)
ResultSet databaseResult = null;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
databaseResult = databaseStatement.executeQuery(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database query.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return databaseResult;
public int executeDatabaseUpdate(String sSQL)
int rowsAffected = -1;
if(databaseConnection != null)
try
Statement databaseStatement = databaseConnection.createStatement();
rowsAffected = databaseStatement.executeUpdate(sSQL);
catch(SQLException sqle)
//Raise event
raiseDatabaseEvent("DatabaseController: Error executing database update.\nSQL: " + sSQL + "\nERROR: " + sqle.getMessage());
return rowsAffected;
//Used to load the Database Driver
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver).newInstance();
driverLoaded = true;
catch (Exception e)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + e.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Wrap the DatabaseConnectionPool Error to the DatabaseController
public void databaseEventOccurred(DatabaseEvent de)
raiseDatabaseEvent(de.getErrorMessage());
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.add(databaseControllerListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseControllerListener)
databaseControllerListeners.remove(databaseControllerListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseControllerListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
/********************* DatabaseConnectionPool **************/
package com.softnet.database;
import java.io.*;
import java.sql.*;
import java.util.*;
import com.softnet.database.*;
import com.softnet.database.DatabaseSettings;
public class DatabaseConnectionPool
//min number of connections
private int minNumberOfConnections = 1;
//max number of connections -1 is unlimited
private int maxNumberOfConnections = -1;
//Store the connections
protected Hashtable databaseConnections = null;
//Database Info
protected DatabaseSettings databaseSettings;
//to hold Driver state
private boolean databaseDriverState = false;
//To hold connection checker
private DatabaseConnectionCheck connectionChecker = null;
//Used to hold the DatabaseConnectionPool listeners
private List databaseConnectionPoolListeners = new ArrayList();
public DatabaseConnectionPool(DatabaseSettings databaseSettings, int minNumberOfConnections, int maxNumberOfConnections)
this.databaseSettings = databaseSettings;
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Load Driver
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create connection
createConnections();
public DatabaseConnectionPool(int minNumberOfConnections, int maxNumberOfConnections)
this.minNumberOfConnections = minNumberOfConnections;
this.maxNumberOfConnections = maxNumberOfConnections;
//Database Settings Get/Set
public DatabaseSettings getDatabaseSettings()
return databaseSettings;
public void setDatabaseSettings(DatabaseSettings databaseSettings)
this.databaseSettings = databaseSettings;
//Driver State Get
public boolean getDatabaseDriverState()
return databaseDriverState;
public void createConnections()
if(databaseDriverState == false)
databaseDriverState = loadDatabaseDriver(databaseSettings.getDatabaseDriver());
//Create all connections and load the minimum in the Hashtable
if(databaseConnections == null)
if(databaseDriverState == true && minNumberOfConnections != 0)
databaseConnections = new Hashtable();
for(int i = 0; i < minNumberOfConnections; i++)
try
databaseConnections.put(DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword()), Boolean.FALSE);
catch(SQLException sqle)
//Problem break loop and destroy any connections
destroyConnections();
//Raise event
raiseDatabaseEvent("DatabaseConnectionPool: Error creating database connections. \nERROR: " + sqle.getMessage());
break;
//If no connection check exists create one
if(connectionChecker == null)
connectionChecker = new DatabaseConnectionCheck(this);
connectionChecker.start();
public Connection getConnection()
Connection connection = null;
boolean errorWithConnection = false;
Enumeration connections = databaseConnections.keys();
synchronized (databaseConnections)
while(connections.hasMoreElements())
errorWithConnection = false;
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
// Update the Hashtable to show this one's taken
databaseConnections.put(connection, Boolean.TRUE);
// Return the connection
return connection;
//All connections being used check to max to see if we can make a new one
if(maxNumberOfConnections == -1 || maxNumberOfConnections > databaseConnections.size())
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.TRUE);
return connection;
//If not connections free and max connections reached wait for a free connection
return getConnection();
public void returnConnection(Connection connection)
boolean errorWithConnection = false;
//Make sure connection still works
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(databaseSettings.getDatabaseURL(), databaseSettings.getUserName(), databaseSettings.getUserPassword());
catch(SQLException sqle)
errorWithConnection = true;
if(errorWithConnection == false)
databaseConnections.put(connection, Boolean.FALSE);
public void destroyConnections()
Connection connection = null;
if(databaseConnections != null)
//Close all connections
Enumeration connections = databaseConnections.keys();
while (connections.hasMoreElements())
connection = (Connection) connections.nextElement();
try
connection.close();
catch(SQLException ignore) {}
//Free up hashtable
databaseConnections = null;
private boolean loadDatabaseDriver(String databaseDriver)
boolean driverLoaded;
if(databaseDriver.equals("") == false)
try
//Load Database Driver
Class.forName(databaseDriver);
driverLoaded = true;
catch (ClassNotFoundException cnfe)
//Raise event
raiseDatabaseEvent("DatabaseController: Error loading database driver. \nERROR: " + cnfe.getMessage());
driverLoaded = false;
else
driverLoaded = false;
return driverLoaded;
//Event Handling Code
//Used to add database listeners (Its sync'd so you can change the listeners when firing an event)
public synchronized void addDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.add(databaseConnectionPoolListener);
//Used to remove a listener from the list (Its sync'd so you can change the listeners when firing an event)
public synchronized void removeDatabaseListener(DatabaseListener databaseConnectionPoolListener)
databaseConnectionPoolListeners.remove(databaseConnectionPoolListener);
//Used to send the raise event to the listeners
private synchronized void raiseDatabaseEvent(String databaseError)
DatabaseEvent databaseEvent = new DatabaseEvent(this, databaseError);
Iterator listeners = databaseConnectionPoolListeners.iterator();
while(listeners.hasNext())
DatabaseListener listener = (DatabaseListener) listeners.next();
listener.databaseEventOccurred(databaseEvent);
class DatabaseConnectionCheck extends Thread
private DatabaseConnectionPool connectionPool;
DatabaseConnectionCheck(DatabaseConnectionPool connectionPool)
this.connectionPool = connectionPool;
public void run()
try
while(true)
//check threads every 30 seconds
this.sleep(300000);
if(connectionPool.databaseConnections != null)
Connection connection = null;
Enumeration connections = connectionPool.databaseConnections.keys();
synchronized (connectionPool.databaseConnections)
while(connections.hasMoreElements())
connection = (Connection) connections.nextElement();
Boolean state = (Boolean) connectionPool.databaseConnections.get(connection);
//If connection is not used, use it.
if(state == Boolean.FALSE)
try
connection.setAutoCommit(true);
catch(SQLException e)
//Problem with connection remove connection and replace it
connectionPool.databaseConnections.remove(connection);
try
connection = DriverManager.getConnection(connectionPool.databaseSettings.getDatabaseURL(), connectionPool.databaseSettings.getUserName(), connectionPool.databaseSettings.getUserPassword());
catch(SQLException sqle)
connection = null;
// Update the Hashtable with new connection if its not null
if(connection != null)
connectionPool.databaseConnections.put(connection, Boolean.FALSE);
catch(InterruptedException ignored) {}
Basicly the why it works is the connection pool hold the database connections. When the user needs a connection they use the database controller to request a connection (By create a instance and called the connect() method) and the connection is either created or grabed from the connection pool. After the user is done with the connection they call the disconnect() method which closes the connection or returns it to the connection pool.
--Z3r0CooL
Maybe you are looking for
-
Adobe Media Encoder CS5.5 won't even start
So, here I am at day 5 of the full CS5.5 install (after the trial period, during which everything functioned well) and each day there has been some new challenge. Today, Adobe Media Encoder just simply will not run. Not when trying to do an export fr
-
Pacman -Su killed my system!
Hi I made a systemupgrade and now is my system (rootserver) dead! How can i save my system remote? [root@rocky pacman.d]# pacman -Su Targets: automake-1.10-1 damageproto-1.1.0-1 freetype2-2.3.1-1 gcc-4.1.2-3 glibc-2.5-4 kernel-headers-2.6.20-1 kernel
-
hio, i m creating delievery in VL01.in that material documnet created but there is no accounting document observed why? pl suggest me.
-
Oracle Error occured, while checking for Already Committed data
Hi, In my 1 day old workspace I see more than 3000 errors logged in the owb_error_log_table with text as shown below , can someone from Oracle please advise what the problem seems to be ? Oracle Error occured, while checking for Already Committed dat
-
Clearing Extra Applications from the "Open With' Menu in 10.5
Hello, After installing an HP printer, my 'open with' dialogue is cluttered with lots of HP junk. How can I remove these items on 10.5? I've found a lot of answers for 10.4 and earlier, but nothing that works on Leopard. Thanks for any help, -Grey