ActiveMQ Broker inside WSL or docker throws invalid username/password; logon denied - spring

I wrote a simple program to connect to a DB using a spring bean from inside Docker or WSl2. It connects fine.
The moment I add a broker tag to the XML it fails with error.
NOTE : the 'broker' tag, even when added as empty, commenting everything out, causes the same issue.
Below is my program and the bean XML
public class TestDB {
public static void main(String[] args) {
Connection connection1 = null, connection2 = null;
try (ConfigurableApplicationContext mContext = new ClassPathXmlApplicationContext("test.xml");) {
String jdbcClassName="oracle.jdbc.OracleDriver";
String url="jdbc:oracle:thin:#xyz.company.com:1521:abc";
String user="TEST_DB";
String password="test";
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcClassName);
ds.setUrl(url);
ds.setUsername(user);
ds.setPassword(password);
connection1 = ds.getConnection();
BasicDataSource ds2 = (BasicDataSource) mContext.getBean("application-ds");
connection2 = ds2.getConnection();
}
catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection1!=null) {
System.out.println("Connected successfully.");
try {
connection1.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection2!=null) {
System.out.println("Connected via bean.");
try {
connection2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Here is the test.xml:
<beans .....>
<broker xmlns="http://activemq.apache.org/schema/core" persistent="true" brokerName="ABC_MESSAGING_SERVER" advisorySupport="false" useJmx="false">
<destinationPolicy>
<policyMap>
<policyEntries>
<policyEntry queue="my_account" />
</policyEntries>
</policyMap>
</destinationPolicy>
<persistenceAdapter>
<jdbcPersistenceAdapter dataSource="#application-ds"/>
</persistenceAdapter>
</broker>
<bean id="application-ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#xyz.company.com:1521:abc" />
<property name="username" value="TEST_DB" />
<property name="password" value="test" />
<property name="maxActive" value="200" />
<property name="poolPreparedStatements" value="true" />
</bean>
</beans>
The output, with the broker part commented is:
and with broker :
org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (ORA-01017: invalid username/password; logon denied)
at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at TestDB.main(TestDB.java:29)
Caused by: java.sql.SQLException: ORA-01017: invalid username/password; logon denied
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:509)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:456)
at oracle.jdbc.driver.T4CTTIoer11.processError(T4CTTIoer11.java:451)
at oracle.jdbc.driver.T4CTTIfun.processError(T4CTTIfun.java:1040)
at oracle.jdbc.driver.T4CTTIoauthenticate.processError(T4CTTIoauthenticate.java:552)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:550)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:268)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:501)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:1292)
at oracle.jdbc.driver.T4CTTIoauthenticate.doOAUTH(T4CTTIoauthenticate.java:1025)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:743)
at oracle.jdbc.driver.PhysicalConnection.connect(PhysicalConnection.java:793)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:57)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:747)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:562)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)

I am answering my own question.
The problem was my Database was version Oracle 12.2.0.1 and my ojdbc jar was ojdbc8-19.3.0.0.
It did not matter when testing on widnows or linux machines.
However using it alongside activemq broker in WSL2 or Docker (virtual envs basically) then it caused 'Invalid username password logon error'.
had to replace the jar with ojdbc8-12.2.0.1 on client side

Related

Access to postgresql server from Spring application

I have a Spring application (Hibernate c3p0) that connects well to an Oracle DB server.
I want to do the same thing with a PostgreSQL DB server, but it sends me the error java.net.UnknownHostException.
In applicationContext, my dataSource is :
<bean id="appDS" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="org.postgresql.Driver" />
<property name="jdbcUrl" value="jdbc:postgresql://THE_SERVER:5432/schema" />
<property name="user" value="appc0" />
<property name="password" value="THE_PWD" />
</bean>
I tried a connection from another very simple java application (from the same server):
public static void main(String[] args) {
try {
System.out.println("TEST Driver Manager START");
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://THE_SERVER:5432/schema";
String user = "appc0";
String passwd = "THE_PWD";
Connection conn = DriverManager.getConnection(url, user, passwd);
System.out.println("Schema : " + conn.getSchema());
System.out.println("ClientInfo : " + conn.getClientInfo());
System.out.println("TEST Driver Manager END");
System.out.println("TEST C3P0 START");
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass( "org.postgresql.Driver" );
cpds.setJdbcUrl( "jdbc:postgresql://THE_SERVER:5432/schema" );
cpds.setUser("appc0");
cpds.setPassword("THE_PWD");
System.out.println("User :"+ cpds.getUser());
System.out.println("TEST C3P0 END");
} catch(Exception e) {
e.printStackTrace();
}
And no mistake in this case, I connect well. This does not seem to be a network problem.
Does anyone know where the problem may come from?
Versions are:
postgresql-42.2.0.jre7.jar
c3p0-0.9.1.2.jar

java.lang.Security Exception

i implemented spring application which is running based on schedulers in weblogic 10. server.
while i am deploying it. i am getting above exception.
here is my stack trace
java.lang.SecurityException: [Security:090398]Invalid Subject: principals=[bpm_weblogic, AdminChannelUsers, Administrators, AppTesters, CrossDomainConnectors, Deployers, Monitors, Operators, OracleSystemGroup]
at weblogic.security.service.SecurityServiceManager.seal(SecurityServiceManager.java:833)
at weblogic.security.service.IdentityUtility.authenticatedSubjectToIdentity(IdentityUtility.java:30)
at weblogic.security.service.RoleManager.getRoles(RoleManager.java:183)
at weblogic.security.service.AuthorizationManager.isAccessAllowed(AuthorizationManager.java:375)
at weblogic.jndi.internal.ServerNamingNode.checkPermission(ServerNamingNode.java:442)
at weblogic.jndi.internal.ServerNamingNode.checkLookup(ServerNamingNode.java:423)
at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:180)
at weblogic.jndi.internal.BasicNamingNode.unbind(BasicNamingNode.java:565)
at weblogic.jndi.internal.WLEventContextImpl.unbind(WLEventContextImpl.java:173)
at javax.naming.InitialContext.unbind(InitialContext.java:435)
at com.tcs.controller.BpmController.run(BpmController.java:94)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.scheduling.support.ScheduledMethodRunnable.run(ScheduledMethodRunnable.java:64)
at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:53)
at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:178)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:292)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
my spring application is running in one weblogic environment and i am calling bpm which is running in another weblogic environment.
here if don't call bpm i am not getting exception and if i user dataSource instead of jndi it is working fine.
but the problme is i have to call the bpm and i can't user dataSource configuration in production.
here is my controller class
public String executeBpm(User user) {
IBPMContext context = null;
String status = null;
if (logger.isDebugEnabled()) {
logger.debug("executeBpm method starts");
}
try {
if (user.getUserId() != null && !("").equals(user.getUserId())) {
context = ITBABPMContext.getIBPMContextUsingName(user.getUserId());
}
HashMap<String, Object> elements = (HashMap<String, Object>) user.getMap();
UpdateTaskDetails updates = new UpdateTaskDetails();
if (user.getTaskId() != null && !("").equals(user.getTaskId())) {
updates.setTaskID(user.getTaskId());
}
if (user.getTaskId() != null && !("").equals(user.getTaskId())) {
updates.setTaskOutcome(user.getTaskOutcome());
}
if (user.getUserComment() != null && !("").equals(user.getUserComment())) {
updates.setUserComment(user.getUserComment());
}
if (!elements.isEmpty() && elements.size() > 0) {
updates.setElementList(elements);
}
if (logger.isDebugEnabled()) {
logger.debug("executeBpm method ends");
}
status = ITBAACMUtil.updateTaskOutcome(updates, context);
if (status.equalsIgnoreCase("success")) {
bpmProcessorService.write(user.getUserId(), user.getSeqNo());
}
} catch (ITBABPMRuntimeException e) {
e.printStackTrace();
} catch (BPMServiceClientException e) {
e.printStackTrace();
} catch (BPMException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return status;
}
my dao class
public void write(String userId,Long seqNo){
try{
String query=messageSource.getMessage(BPMConstants.FAILED_QUERY,new Object[]{Long.toString(seqNo)},Locale.US);
jdbcTemplate.update(query);
}catch(Exception e){
logger.error("exception at updating the status to failed ..");
logger.error(e.getStackTrace());
}
}
here one thing is cross domain mapping is are already there and other applications are running just fine. so i don't think this is the issue with cross domain mapping.
here is my configuration file.
<context:component-scan base-package="com.app" />
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="MCDataSource"/>
</bean>
<bean id="txManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager" />
<bean id="transactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager">
<property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
</bean>
<!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#172.19.8.159:1521/OIM.itba.gov.in" />
<property name="username" value="AppDB"></property>
<property name="password" value="AppDB"></property>
<property name="initialSize" value="2" />
<property name="maxActive" value="5" />
</bean> -->
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename">
<value>messages</value>
</property>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="runScheduler" class="com.app.controller.BpmController" />
<task:scheduled-tasks>
<task:scheduled ref="runScheduler" method="run" cron="0 0/5 * * * ?" />
</task:scheduled-tasks>
Hey it seems your problem is you are not switching the context correctly. Once you open up the IBPM context then you are coming back and trying to lookup on your local jndi tree but you have IBPM context credentials which do not authenticate on your local weblogic. You need to open a new context before you perform a jndi lookup operation to your datasource.
Here is some sample code:
jndiTemplate(org.springframework.jndi.JndiTemplate) { bean ->
bean.scope = "prototype"
environment = [
"java.naming.factory.initial":"weblogic.jndi.WLInitialContextFactory",
"java.naming.security.principal" : "username",
"java.naming.security.credentials": "password"
]
}
dataSource(org.springframework.jndi.JndiObjectFactoryBean){
jndiTemplate = ref(jndiTemplate)
jndiName = "name"
exposeAccessContext=true
}
Then when you want to lookup the jndi you can something like.
Inject the jndiTemplate and:
jndiTemplate.context.getProperties()
Or
InitialContext initialContext = new InitialContext(jndiTemplate.getEnvironment());
You can then close it.

Running simple SELECT MS SQL Server query with JDBCTemplate using JTDS driver and c3p0 data source

I am connecting to MS SQL server with following datasource
<bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" >
<property name="driverClass" value="net.sourceforge.jtds.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:jtds:sqlserver://<server>:<port>" />
<property name="user" value="${echo_db_user}" />
<property name="password" value="${echo_db_password}" />
</bean>
<bean id="myProviderDAO" class="com.care.dao.impl.DataProviderImpl">
<property name="dataSource" ref="myDataSource" />
</bean>
public class DataProviderImpl extends JdbcDaoSupport{
public Object runQuery(String staticQuery) {
try {
return getJdbcTemplate().queryForList(staticQuery);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
staticQuery is:
Select
sender,
status_dt
FROM
ServiceTickets.dbo.trouble_ticket
WHERE
status_dt BETWEEN '02-17-2010 07:00:00' AND '04-30-2014 05:00:00'
When running this query I am getting following exception:
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [
Select
sender,
status_dt
FROM
ServiceTickets.dbo.trouble_ticket
WHERE
status_dt BETWEEN '02-17-2010 07:00:00' AND '04-30-2014 05:00:00'
]; nested exception is java.sql.SQLException: ORA-00933: SQL command not properly ended
at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:98)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
Connection is happening as I have debugged the code and it passed where connection is retrieved.
Same query If I execute on Toad (client to ms sql server) executes properly.
I have used same set of steps to connect to Qracle DB and executing its queries and it works fine, only in case of MS SQL server I am facing this issue.

RMI ClassNotFound

I get ClassNotFound exception, here is code:
Server:
<bean id="metaFactoryRmiServiceExporter"
class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="metaFactoryService"/>
<property name="service" ref="metaFactoryServiceImpl"/>
<property name="serviceInterface" value="IMetaFactoryService"/>
<property name="registryPort" value="1098"/>
</bean>
Client:
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
try {
Registry registry = LocateRegistry.getRegistry("127.0.0.1",1098);
registry.lookup("metaFactoryService");
for (String s:registry.list()) {
System.out.println(s);
}
} catch (Exception e) {
e.printStackTrace();
}
I can get the registry.list() but lookup throws exception. why ?
I've configured security.policy.

Very simple Spring transactions of JDBC not roll back (even log said yes)

I'm new to Spring transactions. I use Spring 3.2.2 and MySQL 5.5.20(InnoDB). I can see in the log file that it did roll back, but in the database, the record still being updated to 9. What did I miss? Thanks.
The config.xml:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/javatest?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="xxx" />
</bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="hello" class="com.xol.oss.HelloService">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
The Java code:
public void setDataSource(BasicDataSource dataSource) {
this.dataSource = dataSource;
}
#Transactional
public void getData() {
Connection con=null;
try {
con = dataSource.getConnection();
Statement stat = con.createStatement();
stat.executeUpdate("update testdata set foo=9 where id=1");
throw new RuntimeException("an Exception for test");
} catch (SQLException e) {
e.printStackTrace();
} finally{
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The log said it did roll back:
15:15:36,936 DEBUG DataSourceTransactionManager:366 - Creating new transaction with name [com.xol.oss.HelloService.getData]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT; ''
15:15:37,525 DEBUG DataSourceTransactionManager:205 - Acquired Connection [jdbc:mysql://127.0.0.1:3306/javatest?useUnicode=true&characterEncoding=UTF-8, UserName=root#localhost, MySQL-AB JDBC Driver] for JDBC transaction
15:15:37,535 DEBUG DataSourceTransactionManager:222 - Switching JDBC Connection [jdbc:mysql://127.0.0.1:3306/javatest?useUnicode=true&characterEncoding=UTF-8, UserName=root#localhost, MySQL-AB JDBC Driver] to manual commit
15:15:37,581 DEBUG DataSourceTransactionManager:844 - Initiating transaction rollback
15:15:37,582 DEBUG DataSourceTransactionManager:280 - Rolling back JDBC transaction on Connection [jdbc:mysql://127.0.0.1:3306/javatest?useUnicode=true&characterEncoding=UTF-8, UserName=root#localhost, MySQL-AB JDBC Driver]
15:15:37,583 DEBUG DataSourceTransactionManager:323 - Releasing JDBC Connection [jdbc:mysql://127.0.0.1:3306/javatest?useUnicode=true&characterEncoding=UTF-8, UserName=root#localhost, MySQL-AB JDBC Driver] after transaction
15:15:37,583 DEBUG DataSourceUtils:327 - Returning JDBC Connection to DataSource
Exception in thread "main" java.lang.RuntimeException: an RuntimeException for test
at com.xol.oss.HelloService.getData(HelloService.java:31)
at com.xol.oss.HelloService$$FastClassByCGLIB$$3d7d84e8.invoke(<generated>)
The problem is that you are not using the connection managed by spring, instead you are opening a new connection. Change the code to the following and try.
import org.springframework.jdbc.datasource.DataSourceUtils;
#Transactional
public void getData() {
Connection con=null;
try {
// Get the connection associated with the transaction
con = DataSourceUtils.getConnection(dataSource);
Statement stat = con.createStatement();
stat.executeUpdate("update testdata set foo=9 where id=1");
throw new RuntimeException("an Exception for test");
} catch (SQLException e) {
e.printStackTrace();
} finally{
DataSourceUtils.releaseConnection(dataSource, con);
}
}
If you are writing new code you should be using the JdbcTemplate instead of raw jdbc.
class HelloService {
JdbcTemplate jdbcTemplate;
public setDataSource(DataSource dataSource) {
jdbcTemplate = new JDBCTemplate(dataSource);
}
#Transactional
public void getData() {
jdbcTemplate.update(update testdata set foo=9 where id=1);
throw new RuntimeException("an Exception for test");
}

Resources