I´m quite new to Java EE and have a comprehension question about running an application in the application server, in my case Wildfly 10.
My Problem is, that objects apparently keep their state, once they where instantiated on application start up, even if i close and re-open the browser session. In my case, i´m using a bean that tries to open a jdbc connection and writes to the facelet´s messages in case something goes wrong.
So, to test the scenario i shut down the database and started the application. As expected, the error message comes up. Now, after restarting the database, it is still not connecting and giving me the "no database" message. A complete restart of the application server is necessary in order to have the bean start over new.
So the question is, what do i have to do, to re-initialize all involved object instances of my application?
Here is the code of the bean in question:
#Named
#Stateless
public class CoworkerProducer
{
#Inject
private EntityManager em;
#Resource(lookup="java:/JMPostgres")
private DataSource dsJM;
public void addCoworkers(Long projectId)
{
Project managedProject = em.find(Project.class, projectId);
Long jmId = managedProject.getJmId();
try {
Connection con = dsJM.getConnection();
PreparedStatement ps = con.prepareStatement("SELECT * FROM employees e, departments d WHERE e.department_id = d.id AND d.project_id = " + jmId);
ResultSet result = ps.executeQuery();
while(result.next()){
Coworker cow = new Coworker();
cow.setProject(managedProject);
em.persist(cow);
}
}
catch (SQLException e) {
final FacesContext facesContext = FacesContext.getCurrentInstance();
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "no database!", null));
}
}
}
It's best practice to let the container, in your case Wildfly 10, handle the database connection, You can configure that in the standalone.xml file.
Documentation for configuration
In your case, create a (pooled) Datasource in Wildfly and enable connection validation and connection retries in Wildfly. That way, Wildfly will manage your database connection and reestablish connection if it failed.
Once you installed the MySQL driver in Wildfly, you can create the datasource on the Wildfly admin console (by default it runs on port 9990) or with the JBoss CLI.
Further reading:
Datasource configuration
Related
We have spring boot application (version => 2.4.3) that needs to run in weblogic 12.2.1.4.0. When we give url, name and password like below, it successfully deploy and can get connection, but when we deploy via jndi like below. It is getting error. How can we fix this? We already tried these links, but it is not solved our problem.
https://weblogic.developer.interest.jdbc.narkive.com/2JvpDwJc/weblogic-jdbc-extensions-poolpermissionssqlexception
https://groups.google.com/g/weblogic.developer.interest.jdbc/c/SobQpZNwrfM?pli=1
https://groups.google.com/g/weblogic.developer.interest.jdbc/c/lkTGus61SNE
Weblogic errror=>
weblogic.common.resourcepool.ResourcePermissionsException: User "<anonymous>" does not have permission to perform operation "reserve" on resource "myusername" of module "none" of application "none" of type "ConnectionPool"
weblogic.jdbc.extensions.PoolPermissionsSQLException: weblogic.common.resourcepool.ResourcePermissionsException: User "<anonymous>" does not have permission to perform operation "reserve" on resource "myusername" of module "none" of application "none" of type "ConnectionPool"
at weblogic.jdbc.common.internal.JDBCUtil.wrapAndThrowResourceException(JDBCUtil.java:281)
at weblogic.jdbc.common.internal.WLDataSourceImpl.getPoolConnection(WLDataSourceImpl.java:563)
at weblogic.jdbc.common.internal.WLDataSourceImpl.getConnectionInternal(WLDataSourceImpl.java:660)
Working properties =>
# Oracle settings
spring.datasource.url=jdbc:oracle:thin:#10.10.10.10:1521:MYDB
spring.datasource.username=myusername
spring.datasource.password=userpassword
spring.datasource.driver.class=oracle.jdbc.driver.OracleDriver
not working properties =>
spring.datasource.jndi-name=jdbc/ABC
spring.datasource.driver.class=oracle.jdbc.driver.OracleDriver
Error occur in this code 'dataSource.getConnection()'
#Component
#Slf4j
public class SysUrlLinkDao {
#Autowired
private DataSource dataSource;
public ImagePojo loadImgPathLink(String value) {
ImagePojo generic = new ImagePojo();
String query = " SELECT * FROM IMG_PATH WHERE PARAM_VALUE =?";
try (Connection connection = dataSource.getConnection();
PreparedStatement preStatement = connection.prepareStatement(query)) {
preStatement.setString(1, value);
try (ResultSet rset = preStatement.executeQuery()) {
while (rset.next()) {
generic = new ImagePojo();
generic.setImagePath(rset.getString("PATH"));
generic.setLinkPath(rset.getString("LINK"));
}
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return generic;
}
}
After removing 'Locale.setDefault(new Locale("tr", "TR"));' in ContextListener, it can get connection. I don't understand why it gets faults from weblogic datasource. Secondly, when we deploy our war package to local weblogic. It is also gets datasource error and after logging off console, we cannot log in. Admin console also affected. We tried correct username and password, but it gives error like this 'Access denied'. All these has solved with removing default locale.
I know this has been asked a hundred times and I think I have read all the posts and tried every variation of the solutions. I'm using NetBeans and new to it. I'm sure I'm just missing some small step because it seems like its just not seeing the driver that I added to the library. This is the first time I have tried to connect to a database so please be gentle.
try
{
String host = "jdbc:sqlserver://Server:1433;Database";
String uName = "User";
String uPass = "Password";
Connection con = DriverManager.getConnection(host,uName,uPass);
System.out.println("Your are connected to SQLServer 2014");
}
catch (SQLException err)
{
System.out.println(err.getMessage());
}
You forgot to register the jdbc driver class.
Call
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
before calling Connection con = DriverManager.getConnection(host,uName,uPass);.
It will resolve the issue.
UPDATE
In documentation for new jdbc drivers it is declared that this step is not necessary. But in practical work, I have found that this step is required even for new drivers, otherwise you will get "No suitable driver found" error. This error occurs sometimes, for example it does not occur when you are making and running a console jar-application, but occurs when you have created and deployed a web-application.
So, I advise to register the jdbc driver class before getting the database connection via DriverManager.getConnection() call.
I'm trying get the data base connection using JNDI Name. I'm sing Websphere application server.
Please find below code.
public class GetDbConnection {
private static Connection getConnection() throws Exception {
Hashtable<String, String> pdEnv = new Hashtable<String, String>();
pdEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.ibm.websphere.naming.WsnInitialContextFactory");
pdEnv.put(Context.PROVIDER_URL, "iiop://10.70.52.228:30305/");
Connection connection = null;
try{
Context ctx = new InitialContext(pdEnv);
System.out.println("Initial Context: "+ctx.getNameInNamespace());
DataSource ds = (DataSource) ctx.lookup("jdbc/siperian-mdmtrg01-cmx_ors-ds");
System.out.println("DataSource Object : "+ds.getClass());
connection = ds.getConnection();
System.out.println("Connection established ::" +connection);
}catch(Exception ex){
ex.printStackTrace();
}
return connection; }
I'm getting below error.This is the full print stack trace.
Initial Context: MDMTRG2Cell01/clusters/InformaticaMDM_Cluster
J2CA0036E: An exception occurred while invoking method
setDataSourceProperties on
com.ibm.ws.rsadapter.spi.WSManagedConnectionFactoryImpl used by
resource jdbc/siperian-mdmtrg01-cmx_ors-ds :
java.lang.NoClassDefFoundError:
com/ibm/websphere/appprofile/accessintent/AccessIntent
Please help me in this reagrd.
The cause of the problem is that the WebSphere Application Server Java™ virtual machine (JVM) could not find the JDBC JAR file.
Example if we are using DB2 datasource we need DB2 JAR, in websphere classpath that contains the implementation class.
The most likely cause is that the classpath of the JDBC Provider configuration has used a WebSphere Application Server variable, for example, DB2_JDBC_DRIVER_PATH, which has not been set for the corresponding WebSphere Application Server jvm process.
This could also be caused on Unix based servers by the userID not having permission to access the jar that contains the class.
I have wrote Java Client application (bean for Oracle form) to access the data through "jdbcdatasource" created on Weblogic 12c. It works fine when I am running on desktop, but when I am embedding on oracle forms as a bean, it gives following error:
java.lang.ClassNotFoundException: weblogic.jdbc.common.internal.RmiDataSource_12210_WLStub
java bean is an executable jar file includes all the dependency jar file, and it is executed independently by double click.
Here is a code:
Context ctx = null;
Hashtable ht = new Hashtable();
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3:" + url + ":7001");
if(sUser != null && sPwd != null){
ht.put(Context.SECURITY_PRINCIPAL, sUser);
ht.put(Context.SECURITY_CREDENTIALS, sPwd);
}
ctx = new InitialContext(ht);
System.out.println("!!! WebLogic Server Connection Done!");
javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");
java.sql.Connection conn = ds.getConnection();
System.out.println("!!! DataSource Connection Done!");
In the environment of Oracle forms it connect to the weblogic server but could not access the data source by displaying above error.
Any suggestion?
Just to make things clear to me.
When you say :
"to access the data through "jdbcdatasource" created on Weblogic 12c."
and you code shows:
"javax.sql.DataSource ds = (javax.sql.DataSource) ctx.lookup("myDatasource");"
The lookup parameter value shouldn't be exactly like "jdbcdatasource" instead of "myDataSource' as you stated before or it was just to explain your situation ?
I'm trying to follow Java's JDBC tutorials to write a Java program that can connect to SQL Server 2008. I'm getting lost at the point of making a connection.
The following snippet is from the tutorial:
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:comp/env/jdbc/myDB");
Connection con = ds.getConnection();
DataSource ds = (DataSource) org.apache.derby.jdbc.ClientDataSource()
ds.setPort(1527);
ds.setHost("localhost");
ds.setUser("APP")
ds.setPassword("APP");
Connection con = ds.getConnection();
There's no explanation of what comp/env/jdbc/myDB should point to, and I don't know how I should choose a port. Also, the object ds seems to be defined twice.
I'm using the JSQLDataSource driver, for the record. Can anyone point me in the right direction here?
http://java.sun.com/docs/books/tutorial/jdbc/basics/connecting.html
I'm not sure anyone above has really answered the question.
I found this microsoft sample useful.
The key information in there is really that the class you need is SQLServerDataSource
that is basically a configuration object - you use it something like this:
SQLServerDataSource dataSource = new SQLServerDataSource();
dataSource.setUser("aUser");
dataSource.setPassword("password");
dataSource.setServerName("hostname");
dataSource.setDatabaseName("db");
You would then call
dataSource.getConnection();
to get a connection object which is basically the thing you use to talk to the database.
Use
connection.prepareStatement("some sql with ? substitutions");
to make something for firing off sql and:
connection.prepareCall
for calling stored procedures.
Start with the JDBC tutorial or the Microsoft docs.
and this:
String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
Class.forName(driver);
String url = "jdbc:microsoft:sqlserver://host:1433/database";
Connection conn = DriverManager.getConnection(url, "username", "password");
Fill in your values for host, database, username, and password. The default port for SQL server is 1433.
UPDATE: Good point below. JDBC drivers can be had from both Microsoft and jTDS. I prefer the latter.
JNDI lookups have to do with Java EE app servers that support connection pooling. You can ask the app server to create a pool of connections, which can be an expensive thing to do, and loan them out to clients like library books as needed.
If you aren't using a Java EE app server or connection pooling, you have to create the connection on your own. That's where manual processes and DriverManager come in.
EXPLANATION: As for why the Sun tutorial shows DataSource twice, I'd say it's a case of poor editing. If you look above the code sample it says you can get a DataSource "by lookup or manually". The code snippet below shows both together, when it should be one or the other.
You know it's an inadvertent error because there's no way the code as written could compile. You have "ds" declared twice.
So it should read "...lookup", followed by its code snippet, and then "...manually", followed by its code snippet.
I like the jTDS driver for connecting to SQL Server. A URL will look like this:
jdbc:jtds:sqlserver://localhost/Finance;instance=sqlexpress
Check this for jTDS Url Info.
This also has some interesting information to help troubleshoot jtds to sql express sorts of problems.
DataSource ds = new SimpleDriverDataSource(new com.mysql.jdbc.Driver(),
"jdbc:mysql://database:1433;databaseName=name", "username", "password");
JdbcTemplate jdbc = new JdbcTemplate(ds);
This question has already been answered long time ago. The question was asked about JNDI lookup. With lookup you have to see the application server log to see what the connection is bound to. For example in Jboss startup, I can see:
[ConnectionFactoryBindingService] Bound ConnectionManager 'jboss.jca:service=DataSourceBinding,name=myDB' to JNDI name 'java:myDB'
Using that name=myDB you lookup
InitialContext ic = new InitialContext();
DataSource ds = ic.lookup("java:myDB");
Notice how the server log and the code both point to the JNDI name java:myDB.