Servlet and transaction
Hi everybody!
I have a question concerning transaction logging and servlets. I'm using the dbconnectionBroker class for my connections. i'm setting the connection.setAutoCommit(true) to use rollback and commit functionality.
when i start to edit a row in my database i start a transaction by updating the row (e.g update name=name) to lock the row. by that i avoid that a second user can edit the row at the same time. so far so good. when the first user ends his work with a propper submit everything is fine, i can close my transaction with commit. but: if the user closes his explorer just for fun while editing the row, the connection and the transaction remain open and the row is therefore locked for other users.
are there any suggestions on how to avoid this kind of 'deadlock'?
I have allready tried to save the connection in a synchronized map and to remove open connections after a certain period of time (problems with parallel access)
thanks for your help
1st of all i can see that you haven't studied a bit about Transcanctions. setAutoCommit(true) is wrong and DOESNT ENABLE transcactions. you must set it to false. transcactions mean that you GROUP SQL statements and if one fails ALL fail. So if your user closes his window means that his "kills" your servlet which means your code which means your transcanction which means that no rows are locked and no insert, update, delete or any other SQL query is done.
Study Databases connectivity, transactions and RDBMS. They will help you understand more things about you managing your DB through servlets. I hope i helped.
Similar Messages
-
Servlet and Object Serialization
Hi,
I am developing a routing server in Java
2 Instances of the same server will be running in 2 different data centers.
The servers have a Jetty server embedded with a Servlet inside.
Server 1 will use a GET method to talk to the Server 2 -> Servlet which will write the state of an object back which will read by Server 1 and reconstruct the object back.
Do you find any issues in Object Serialization/DeSerialization in the Servlet.
What are the factors that I need to consider in this case?
Regards,
JanaMake sure that your servlet handles the transaction in the same thread that doPost() or doGet() is called in.
I ended up porting some old ServerSocket based code to a servlet, and was handing off the request and response objects to a handler thread on the server side. I ended up with a ton of intermittent errors like this.
Once I started handling the transactions in the same thread things worked heartbreakingly well. -
Diff B/W master data and transaction data
Hi all,
What is the main Diff B/W master data and transaction data. give me some example ?
Thanks in Advance
Krish...hi krish,
MASTER Data is the data that exists in the organization like employee details, material master, customer master, vendor master etc. These are generally created once.
Master data are distributed throughout the company, they are often not standardised and often redundant. As a result it is very costly to offer efficient customer service, keep track of supply chains and make strategic decisions. With SAP Master Data Management (SAP MDM) these important business data from across the company can be brought together, harmonised and made accessible to all staff and business partners. As a key component of SAP NetWeaver, SAP MDM ensures data integrity via all IT systems.
Regardless of the industry, companies often work with different ERP and Legacy systems. The result: the business processes are based on information about customers, partners and products which is displayed in different ways in the systems. If the data are recorded manually, there are more inconsistencies: some data sets are entered several times, others cannot be retrieved by all divisions of the company.
As corporate applications are becoming increasingly complex and produce ever greater amounts of data, the problem is intensified further. Nevertheless, your employees must work with the inconsistent data and make decisions on this basis. The lack of standardised master data easily leads to wrong decisions, which restrict efficiency and threaten customer satisfaction and profitability.
In a word: in order to save costs and ensure your companys success it is necessary to consolidate master data about customers, partners and products, make them available to all employees beyond system boundaries and use attributes valid company-wide for the purpose of description.
TRASNACTION Data - These are the business documents that you create using the master data - Purchase orders, sales orders etc
http://help.sap.com/saphelp_nw2004s/helpdata/en/9d/193e4045796913e10000000a1550b0/content.htm
Regards,
GNK. -
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. -
Dear Friends,
How a Basic Cube differs from a Transactional and Remote Cube ?
A Small Example- Cube Carries the Transaction data of Customer ,Material, Sales details ( characteristics) and price, Quantity and Revenue (keyfigures) .
When do we Really have to Change or to Create the Other Cubes to hold those Data ?
What is the Exact Purpose that a Scenario Needs the Remote and Transactional Cube ?
I hope Remote Cube Can be created with "Infoservices" and "Source system" . What is the demand for both these options?
Thanks well in advance ,
Rameshhi,
Remotecbue will have only structure and It does't hold any data.
and it is used to bring live data to BW ..At the time of reporting only the data fetches from the source system. So it takes more time to execute.
it will not hav update rules...
Transactional InfoCubes are used only in conjunction with SEM. The data from this kind of InfoCube is accessed transactionally, meaning data is written to the InfoCube (possibly by several users at the same time) and reread as soon as possible. Basic InfoCubes are not suitable for this. You should use Basic InfoCubes for read-only access (for example, when reading reference data).
Rfer
http://help.sap.com/saphelp_bw33/helpdata/en/39/100c38e15711d4b2d90050da4c74dc/frameset.htm
thanks
(Assign points if useful..) -
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?
% -
Downloding the SAP master data and transaction data to a flat file
Hello All,
Is there any SAP standard method or transaction to download the SAP master data and transaction data to flat file.
With out using ABAP development, SAP had provided any tool or method to download the SAP system master and transaction data to flat file.
Thanks,
Feroz.hi
as of now up to my knowledge no. -
Current server is the coordinator and transaction is not found
Hi,
We're using Weblogic 8.1 SP3. We have a single weblogic domain and 2 clusters in it. EAR1 is deployed in cluster 1 and EAR2 is deployed in cluster 2. EAR2 is compiled and created using j2ee.jar and not weblogic.jar.
We have a MessageDrivenBean which is CMT / Required in EAR1 calls a BMT Stateless Session Bean in EAR2.
A new transaction is begun in the BMT SB method and commit or rollback is called based on exception. A RuntimeException is thrown back to the MDB in case the transaction is rolled back in Bean Managed SB.
Sometimes from the Bean Managed SB the following exception is thrown:
javax.transaction.TransactionRolledbackException: Current server is the coordinator and transaction is not found. It was probably rolled back and forgotten already.
at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:284)
at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:244)
at com.oakgrovesystems.reactor.frontDesk.EJBFrontDeskBean_1gq9kv_EOImpl_813_WLStub.handleRequest(Unknown Source)
at com.oakgrovesystems.reactor.requests.ReactorRequest.send(ReactorRequest.java:212)
at com.oakgrovesystems.reactor.client.EJBReactorProxy.sendRequest(EJBReactorProxy.java:44)
at com.oakgrovesystems.reactor.client.AbstractReactorProxy.handleRequest(AbstractReactorProxy.java:52)
at sun.reflect.GeneratedMethodAccessor153.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:324)
at tavant.bpm.client.proxy.DynamicFailoverReactorProxy.invoke(DynamicFailoverReactorProxy.java:84)
at $Proxy11.handleRequest(Unknown Source)
at tavant.bpm.client.ProcessHome.handleRequest(ProcessHome.java:298)
at tavant.bpm.client.ProcessHome.startProcess(ProcessHome.java:87)
at tavant.bpm.client.processor.CreateWorkflowInstance.startProcess(CreateWorkflowInstance.java:70)
at tavant.bpm.client.processor.CreateWorkflowInstance.invoke(CreateWorkflowInstance.java:51)
at tavant.bpm.ejb.AsynchronousProcessorMessageBean.onMessage(AsynchronousProcessorMessageBean.java:58)
at weblogic.ejb20.internal.MDListener.execute(MDListener.java:370)
at weblogic.ejb20.internal.MDListener.onMessage(MDListener.java:262)
at weblogic.jms.client.JMSSession.onMessage(JMSSession.java:2678)
at weblogic.jms.client.JMSSession.execute(JMSSession.java:2598)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:219)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:178)
This is not consistently reproducible though it happens when server is heavily loaded. When this exception occurs, the transaction in the BMT Session Bean is actually getting committed! The message gets redelivered from the MDB.
What could be the problem?
Regards
SandhyaI'm seeing a similiar problem on our servers recently and thought I would add my problem as well. We are using Weblogic 8.1; don't know which SP is in production. We have an EAR file with an SB EJB that puts messages in a queue. The EAR is deployed in a cluster along with the queues. The errors below occurred in 3 of the 4 WLS instances in our cluster. This happened during a peak period and lasted for several seconds in Production.
###<Jul 1, 2005 11:18:12 AM EDT> <Warning> <RMI> <exsdxtxeax1x.prod.xxxx.xxx> <ems-04> <ExecuteThread: '12' for queue: 'web
logic.kernel.Default'> <<WLS Kernel>> <> <BEA-080006> <Failed to associate the transaction context with the response while marshall
ing an exception to the client:
javax.transaction.TransactionRolledbackException: Current server is the coordinator and transaction is not found. It was probably
rolled back and forgotten already..
javax.transaction.TransactionRolledbackException: Current server is the coordinator and transaction is not found. It was probably
rolled back and forgotten already.
at weblogic.transaction.internal.TransactionManagerImpl.sendResponse(Ljava.lang.Object;)Ljava.lang.Object;(TransactionManag
erImpl.java:1438)
at weblogic.rmi.internal.BasicServerRef.associateTxContext(Lweblogic.rmi.spi.InboundRequest;Lweblogic.rmi.spi.OutboundRespo
nse;)V(BasicServerRef.java:490)
at weblogic.rmi.internal.BasicServerRef.postInvoke(Lweblogic.rmi.extensions.server.RuntimeMethodDescriptor;Lweblogic.rmi.sp
i.InboundRequest;Lweblogic.rmi.spi.OutboundResponse;Ljava.lang.Throwable;)V(Optimized Method)
at weblogic.rmi.internal.BasicServerRef.handleRequest(Lweblogic.rmi.spi.InboundRequest;)V(Optimized Method)
at weblogic.rmi.internal.BasicExecuteRequest.execute(Lweblogic.kernel.ExecuteThread;)V(Optimized Method)
at weblogic.kernel.ExecuteThread.execute(Lweblogic.kernel.ExecuteRequest;)V(Optimized Method)
at weblogic.kernel.ExecuteThread.run()V(ExecuteThread.java:178)
at java.lang.Thread.startThreadFromVM(Ljava.lang.Thread;)V(Unknown Source)
> -
Connection failover and transaction failover
Connection failover and transaction failover
I need to know more about a behavior in a RAC cluster. When a node goes down that is executing one of my transaction through JDBC , does the connection and transaction failover to a new node without me needing to restart tran or reconnect ?
Please provide some insight
ThanksTransactions are NOT automatically rolled back. The application must do this otherwise the session will get disconnected.
If you code TAF, all sessions will failover to the backup connection. You can specify that select statements are automatically re-executed after the failover. Insert/update/delete transactions must be explicitly rolled back and resubmitted by the application.
IF you are using an ORacle Connection pool, the connection pool will automatically cleanup connections to the failed instance, abort inflight transactions. The application will either retry or it will propagate the error to the end user.
See the whitepaper on the OTN RAC page (otn.oracle.com/rac) Workload Management with Oracle RAC for more information. -
Can i display My application iview and transaction iview in single page ?
Hi,
I am new in web dynpro and portal. i am doing one approval application through web dynpro. Now i need to attache sap inbox to application. For that some budy suggested me about transaction view. So my questions are as folloes.
1.> How i attached my application to iview ?
2.> How i created Transaction iview ?
3.> Can i attache my application iview with transaction iview if it is possible then how ?
4.> Can i display My application iview and transaction iview in single page ?
Please guide me in this procesure.
Regards,
Gurprit BhatiaHi Gurprit,
1.> How i attached my application to iview ?
You can attach your application to web Dynpro IView, for this login into portal, in the Content Management tab right click on a folder, then New --> IView. Select WD java Application. Select your application and create an Iview.
2.> How i created Transaction iview ?
Similarly, instead of selecting WD java Application, select iView template, you will get a list of available templates, and in this you will find template for Transaction Iview, in this template define the Tx for which you want to create the template.
3.> Can i attache my application iview with transaction iview if it is possible then how ?
No, I dont think you can attach your application to transaction Iview. but, you can attach both IViews on single page.
4.> Can i display My application iview and transaction iview in single page ?
Yes, you can attach both IViews on single page. Again in Content Management tab, crate a PAGE; Then right click on created IViews and select add IView to Page ßß: Delta Link.
Hope this helps.
Regards,
Amit -
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 -
How to use ale/idocs in sap crm to transfer master and transactional data
hi all,
I am working on sap crm7.0 ehp1. I want to transfer my master and transactional data from crm development system to crm quality system here through idocs. I am aware of basic ale settings and successfully transfe the ztable data through idocs. But i am not able to find any proper step by step procedure for maste and transactional data in sap crm. Also sap ecc tcode NACE is not available here.
pls help..
regards,
kavita chaudharyKavita,
In CRM, Exchange Interface (XIF) ALE/IDOC is available to transfer master and transaction data. You can go through the following link for set up.
Basic Data exchange set up for ALE IDocs - Wiki - SCN Wiki
You can extend the standard XIF IDOCs using Transaction BDFg as well.
Thanks,
Ravi
Maybe you are looking for
-
How do I prevent my content from being erased when adding a new device to itunes?
I've had my 4s for about a year now and I just got a new windows laptop. I installed itunes and signed in but i dont know how to add my phone to this itunes. I know that normally you just plug your phone into the computer and it does it automatically
-
Linksys E4200: How to access USB hard drive remotely from Android phone or computer
Hello. I just purchased a Linksys e4200 router today along with a WD 2TB MyBook hard drive. My intent is to set these two up together so that i can share files on the hard drive with: Computers on my home network ( 1 Windows 7 desktop wired, 1 window
-
Slow BB, changed microfilter, how long does it tak...
hello I have been getting about 12-15Mbit/s, but this has been getting worse over the last few months. I think it's a duff microfilter, I was seeing noise margin of about 20dB, but I swapped one of them and now it's showing 4.5dB, which I think is he
-
Problem on using Business Object Data Service Designer to copy data to HANA
Expert, I want to use BODSD (v14) to copy tables from SQL server to HANA, so I create Job, Workflow, dataflow, source tables in SQL server, target tables in HANA and Querys, then execute the job. All tables have been successfully transferred to HAN
-
Hi, Is there a way i can have an Central KM Repository. I have an BW Java portal and a Central Portal .Is there a way i can configure the BW Java portal to Use the KM of Central Portal . Thanks, sree