Problems accessing Context.xml Mail resource in OpenShift - java

Please help,
I have a Java Spring MVC application (Tomcat 7) on OpenShift which is trying to use a resource lookup in Context.xml. I keep getting 500 errors when it tries to create the session session = (Session) envContext.lookup("mail/Session"); ( see code below ). There are no exceptions in the logs in app-root/logs/jbossews.log, e.printStackTrace(); doesn't print anything in the catch block. Do exceptions get logged somewhere else perhaps? I'm used to having a access.log and error.log in apache/tomcat, jbossews.log doesn't see to tell me anything (FYI I am not using RHC tools, I'm just tailing the log over ssh).
My project runs fine on my local system in eclipse with no issues.
Please help,
Thanks
Session session = null;
Context initalContext = new InitialContext();
Context envContext = (Context) initalContext.lookup("java:comp/env");
try{
// Blows up here with a 500 error
session = (Session) envContext.lookup("mail/Session");
}
catch (Exception e) {
// No StackTrace printed
e.printStackTrace();
}
Here is my resource located in jbossews/conf/context.xml
<Resource
name="mail/Session"
type="javax.mail.Session"
auth="Container"
mail.smtp.host="smtp.gmail.com"
mail.smtp.socketFactory.port="465"
mail.smtp.socketFactory.class="javax.net.ssl.SSLSocketFactory"
mail.smtp.auth="true"
mail.smtp.port="465"
mail.from="XXXXXX#mailserver.com"
mail.user="XXXXXX#mailserver.com"
password="XXXXXX"
/>
I tried adding the following to my web.xml to see if that would fix the problem (It didn't).
<resource-ref>
<description>Resource reference to a factory for javax.mail.Session instances that may be used for sending electronic mail messages, preconfigured to connect to the appropriate SMTP server.</description>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>

Figured out my issue was due to an issue in my pom.xml (Not related to accessing Context.xml after all). Annoyingly Exceptions weren't being logged in jbossews.log so I had to explicitly log them via Exception exception = (Exception) httpRequest.getAttribute("javax.servlet.error.exception");
exception.printStackTrace(); ( httpRequest being a HttpServletRequest Object)
The problem in my pom.xml was this, I tried using:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.1</version>
<scope>provided</scope>
</dependency>
Using the following dependency solved the issue.
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.2</version>
</dependency>
Note: In order for the Context.xml "mail/Session" resource to work on OpenShift I had to create a lib folder in src/main/webapp/WEB-INF/ and place javax.mail-api.jar inside.
Hope this helps anyone else experiencing problems.

Related

Cannot cast from ConnectionWrapper to oracle.jdbc.OracleConnection using JAVA1.8 and Tomcat 8.5.28

Why connection is not working after few seconds? Application is hanging up and not running as expected and returning the below error.
java.lang.ClassCastException:
org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
cannot be cast to org.apache.tomcat.dbcp.dbcp2.DelegatingConnection
Below is the code that is used to get the connection:
OracleConnection oracleConnection = (OracleConnection)
((DelegatingConnection)connection).getInnermostDelegate();
using libraries: commons-pool1.6.jar for encryption & tomcat-dbcp.jar for database.
Using encrypted username and password in Tomcat context.xml.
Also, using accessToUnderlyingConnectionAllowed=true in context.xml file.
Issue is with JAVA8 and Tomcat8. Able to work properly with plain credentials, the only issue happens with encrypted credentials.
You shouldn't do casting or unwrapping. Use correct DataSource type in Tomcat 'conf/context.xml' file. In case of Oracle it is: oracle.jdbc.pool.OracleDataSource.
Set also correct driver and factory.
Look at this example of mine:
<Context>
<!-- Default set of monitored resources. If one of these changes, the -->
<!-- web application will be reloaded. -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<WatchedResource>WEB-INF/tomcat-web.xml</WatchedResource>
<WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<Resource name="UNCUNC"
auth="Container"
type="oracle.jdbc.pool.OracleDataSource"
factory="oracle.jdbc.pool.OracleDataSourceFactory"
driverClassName="oracle.jdbc.OracleDriver"
url="jdbc:oracle:thin:#p260unc4.big.ru:1566:uncunc"
user="dsserv"
password="dsservPass"
connectionProperties="SetBigStringTryClob=true"
maxTotal="20" maxIdle="10"
maxWaitMillis="-1"/>
<JarScanner scanManifest="false"/>
Later in the java code use it like this (don't cast):
try {
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("UNCUNC");
} catch (NamingException e) {
logger.error("DATASOURCE error", e);
}
Connection conn = ds.getConnection();
Should work just fine. Take attention in different versions of Tomcat you need to use 'username' instead 'user' field.
I faced the same issue. After a lot of analysis realized it was classloading issue. Fixed the issue by providing ojdbc jar in shared.loaded (in conf/catalina.properties)
shared.loader="/path/to/ojdbcN_jar/ojdbcN.jar"
This will make sure that the OracleConnection classes are loaded from the same jar in Tomcat and in the deployed webapp.
And in the application where OracleConnection is needed, use the below:
OracleConnection oracleConnection = connection.unwrap(OracleConnection.class);
Note: In my application I have ojdbc jar so that my application compiles fine, but when deployed, the jar used will be the one mentioned in shared loader.
Also don't forget to enable accessToUnderlyingConnectionAllowed when creating the Tomcat JDBC connection pool

JNDI Lookup and PARENT_LAST with Websphere

I'm experiencing a side effect with the following scenario:
I'm looking up a URL via JNDI in a J2EE 5.0 web application running on Websphere Application Server 8.5.5 this way:
URL jndiLmcUrl = null;
try {
Context initialContext = new InitialContext();
jndiLmcUrl = (URL) initialContext.lookup("java:comp/env/url/ENLMC);
} catch (NamingException ne) {
String message = "Unable to found middleware configuration file specified with Jndi property java:/comp/env/url/" + systemPropertyName + " as URI/URL. Trying as system property";
LOG.error(message);
}
My web.xml configuration is:
<resource-ref>
<res-ref-name>url/ENLMC</res-ref-name>
<res-type>java.net.URL</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
In addition i have defined the URL Resource using WAS Console under Resources/URL/Urls with server scope.
ALL IS WORKING FINE as expected.
But, for some reasons (primarily WS Metro usage) i've to move the application to PARENT_LAST using MyApplication/ManageModules/Class loaded with local class loader first (parent last).
After this operation the JNDI lookup fails raising a Naming Exception.
Thank you for your precious help.

JDBC connection pool to MySQL on OpenShift

First of all, I'm a computer science student, and I'm not very much into computer science world yet (i.e. I've little experience doing stuff on my own). So sorry for not having all the knowledge possible on it.
Then, in one of my classes I learnt how to create web application with java (jsp, beans, etc.) plus all the client-side stuff (html, css, javascript, ect.).
I work on NetBeans IDE.
To connect to a MySQL database, I use connection pooling in this way:
1) Add MySQL JDBC Driver jar
2) A DBConnect.java java class with a method that returns a connection:
public static Connection getConnection() {
/* JNDI query to locate the DataSource object */
Context initContext;
try {
initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env"); // JNDI standard naming root
DataSource ds = (DataSource) envContext.lookup("jdbc/aName");
/* Ask DataSource for a connection */
Connection conn;
try {
conn = ds.getConnection();
return conn;
} catch (SQLException ex) {
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("cannot open Connection", ex);
}
} catch (NamingException ex) {
Logger.getLogger(DBConnect.class.getName()).log(Level.SEVERE, null, ex);
throw new RuntimeException("cannot find DataSource reference", ex);
}
}
3) web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<resource-ref>
<description>Resource reference to a DataSource for managing a connection pool.</description>
<res-ref-name>jdbc/aName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
4) context.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/myApp">
<Resource
auth="Container"
driverClassName="com.mysql.jdbc.Driver"
maxActive="100"
maxIdle="30"
maxWait="10000"
name="jdbc/aName"
username="username"
password="password"
type="javax.sql.DataSource"
url="jdbc:mysql://"whateverhost":"whateverport"/dbSchema?autoReconnect=true"/>
</Context>
Now, I created a small project and I wanted to publish it online for free. I ran into OpenShift and I managed to push all my files on it (even if the folders' schema is different).
The problem is that the connection pooling doesn't work, and I don't have a clue on what to do.
Running the application, these are the exceptions:
java.lang.RuntimeException: cannot open Connection
....
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
....
java.sql.SQLException: No suitable driver
....
mysql-connector jar is in /WEB_INF/lib and pom.xml has:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
Maybe the solution is quite simple but I don't know what to do.
Thank you.
I think the problem is your web.xml file. It's redundant. Context.xml specifies a data source with the appropriate configuration and then web.xml specifies one without a URL or driver class name.
Try removing this resource-ref block from web.xml and try again:
<resource-ref>
<description>Resource reference to a DataSource for managing a connection pool.</description>
<res-ref-name>jdbc/aName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
You also have extra quotes in your URL attribute in context.xml:
url="jdbc:mysql://"whateverhost":"whateverport"/dbSchema?autoReconnect=true"/>
Make this:
url="jdbc:mysql://whateverhost:whateverport/dbSchema?autoReconnect=true"/>
I'va ran into this problem myself on OpenShift and also on my Tomcat(that it was installed on personal PC).
It seems that the problem is related to the context.xml file.
Even if i edited the context.xml file that was in my cloned openshift project it seemed that the problem didn't dissappear.
I've managed to solve this on my personal machine by accessing eclipse server directory: /Servers/Tomcat v7.0 Server at localhost-config/context.xml
In the context.xml i had to manually add:
<Resource name="jdbc/MySQLPool"
url="jdbc:mysql://localhost:3306/sakila"
driverClassName="com.mysql.jdbc.Driver"
username="root"
password="nbuser"
auth="Container"
type="javax.sql.DataSource"
maxActive="20"
maxIdle="5"
maxWait="10000"
/>
Saved the file and everything was solved for the Tomcat on my PC.
At this moment i'm still trying to solve the OpenShift issue.
I am using eclipse, and even if i edit the context.xml that is in my OpenShift clone, it seems that somehow, the context.xml file on the OpenShift-Tomcat platform must be accessed and updated like in the previous example.
Hope this help !
Update:
I've managed to solve it for the OpenShift platform in the same manner.
By using Filezilla(guide for openshift can be found here: https://blog.openshift.com/using-filezilla-and-sftp-on-windows-with-openshift/ )
i've connected to the server, accesed the Tomcat directory(in my case: jbossews/conf/context.xml) and i've manually edited the file by adding the same xml Resource like above.
Hope it helps !

Tomcat -Hudson- Lookup failed for 'java:comp/env' in SerialContext in Unit tests

I'm using Tomcat and Hudson to run JUnit tests and i have a problem with testing the email sending. Running the test on Hudson i got the following error:
javax.naming.NamingException: Lookup failed for 'java:comp/env' in SerialContext
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.getComponentId(GlassfishNamingManagerImpl.java:773)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:655)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:156)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:428)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at com.mycompany.extmon.authentication.ChangePasswordForm.<init>(ChangePasswordForm.java:43)
at com.mycompany.extmon.authentication.ChangePasswordFormTest.changePasswordTestMissingUser(ChangePasswordFormTest.java:42).
I dont get it why does it drops this Glassfish related exception because I'm using tomcat this way:
Context initCtx;
Context envCtx;
Session mailSession;
public ChangePasswordForm() throws NamingException {
initCtx = new InitialContext();
envCtx = (Context) initCtx.lookup("java:comp/env");
mailSession = (Session) envCtx.lookup("mail/erik.csik.ext#mycomoany.com");
Everything works fine on the live build ,no error, email is sent,but it fails on the unit tests. What did i forgot to set or where should i look for the problem? I have found nothing useful so far. I guess it is something with the Hudson config but I cant find where might the problem be.
Included context.xml part:
<Resource name="mail/erik.csik.ext#mycompany.com" auth="Container"
type="javax.mail.Session"
mail.smtp.auth="true"
mail.smtp.host="mail.mycompany.net"
mail.smtp.port="25"
mail.smtp.user="admin"
mail.transport.protocol="smtp"
password="password"
mail.smtp.from="erik.csik.ext#mycompany.com"/>
Looks like you have a typo in your lookup:
<Resource name="mail/erik.csik.ext#mycompany.com"
vs.
envCtx.lookup("mail/erik.csik.ext#mycomoany.com");
.......................................^

JMS client connecting to JBoss 6 AS exception

Right now I'm getting this exception from a simple JMS client I wrote to just test to see if I can connect to the JBoss JMS. Here is the snippet of my code below:
Properties props = new Properties();
props.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming");
props.setProperty("java.naming.provider.url", url_);
Context context = new InitialContext(props);
System.out.println("performing lookup...");
Object tmp = context.lookup("/ConnectionFactory");
System.out.println("lookup completed, making topic");
TopicConnectionFactory tcf = (TopicConnectionFactory) tmp;
conn = tcf.createTopicConnection();
topic = (Topic) context.lookup(name_);
session = conn.createTopicSession(false, TopicSession.AUTO_ACKNOWLEDGE);
conn.start();
TopicSubscriber recv = session.createSubscriber(topic);
recv.setMessageListener(this);
I have the following jars:
jms.jar (I got this from outside the JBoss distro)
jbossall-client.jar
log4j.jar
jboss-logging.jar
javax.jms.jar (I got this from outside the JBoss distro)
jnpserver.jar
jboss-common-core.jar
I get the following exception:
javax.naming.CommunicationException [Root exception is java.rmi.UnmarshalException: error unmarshalling return; nested exception is:
java.lang.ClassNotFoundException: org.hornetq.jms.referenceable.SerializableObjectRefAddr (no security manager: RMI class loader disabled)]
This is being run locally, also it seems it's connecting to the JBoss server just that it's throwing this exception.
To anybody interested I was able to solve this by adding a few more jar files to my classpath. Also the problem was that I didn't have a security manager in place.
hornetq-jms.jar
hornetq-logging.jar
hornetq-bootstrap.jar
hornetq-core.jar
hornetq-jboss-as-integration.jar
jboss-as-hornetq-int.jar
netty.jar
This jar files can be found with the JBoss distribution.
This resolved exactly the same issue for me.
<dependency>
<groupId>jboss</groupId>
<artifactId>jboss-aop-jdk50-client</artifactId>
<version>4.2.2.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.netty</groupId>
<artifactId>netty</artifactId>
<version>3.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-jms-client</artifactId>
<version>2.2.5.Final</version>
</dependency>
<dependency>
<groupId>org.hornetq</groupId>
<artifactId>hornetq-core</artifactId>
<version>2.2.5.Final</version>
</dependency>

Categories