Spring data source configuration issue :Logon Denied - spring-boot

I have the below properties file in application.properties
# Database settings
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#dbbdev:1500:SIDNAME
spring.datasource.username=user$name
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.generate-ddl=off
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=false
spring.jpa.properties.javax.persistence.validation.mode=none
spring.jpa.hibernate.format_sql=true
My main class is below : -
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
System.out.println( "Hello World! -- " );
}
I am getting the below error :-
2019-06-27 16:34:39.804 WARN 14556 --- [ main]
o.s.b.a.orm.jpa.DatabaseLookup : Unable to determine jdbc
url from datasource
org.springframework.jdbc.support.MetaDataAccessException: Could not
get Connection for extracting meta-data; nested exception is
org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to
obtain JDBC Connection; nested exception is java.sql.SQLException:
ORA-01017: invalid username/password; logon denied
aused by: org.springframework.jdbc.CannotGetJdbcConnectionException:
Failed to obtain JDBC Connection; nested exception is
java.sql.SQLException: ORA-01017: invalid username/password; logon
denied
at
org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
~[spring-jdbc-5.1.8.RELEASE.jar:5.1.8.RELEASE] at
org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:319)
~[spring-jdbc-5.1.8.RELEASE.jar:5.1.8.RELEASE] ... 65 common frames
omitted Caused by: java.sql.SQLException: ORA-01017: invalid
username/password; logon denied
I have checked my user name and password is correct .Following dependecy exis
exists in parent pom
How to resolve the issue.
<properties>
<java.version>1.8</java.version>
<springboot.version>2.1.6.RELEASE</springboot.version>
<ojdc.version>12.1.0.2.0</ojdc.version>
</properties>

The stacktrace that you have attached, shows that :
[ main] o.s.b.a.orm.jpa.DatabaseLookup : Unable to determine jdbc url from datasource
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta-data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: ORA-01017: invalid username/password; logon denied
and the first part says that spring fails to determine the jdbc url from datasource. So, your jdbc url that you have provided in your application.properties is either wrong or it is not getting connected from your server.
Try providing the datasource url like :
# Database settings
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.datasource.url=jdbc:oracle:thin:#dbbdev:1500/SIDNAME
if SIDNAME is your service name.

Related

Spring Security OAuth2 - Unable to start Spring Boot App if configured with multiple external Auth Servers and failed to connect to one of them

Background :
Configure Spring Boot Application to support Multiple External Authorization Servers
Example of application.properties :
#First Authorization Server
spring.security.oauth2.client.registration.my_okta_account.client-id=<client id>
spring.security.oauth2.client.registration.my_okta_account.client-secret=<client secret>
spring.security.oauth2.client.provider.my_okta_account.issuer-uri=<okta issuer>
#Second Authorization Server
spring.security.oauth2.client.registration.my_azure_ad.client-id=<client id>
spring.security.oauth2.client.registration.my_azure_ad.client-secret=<client secret>
spring.security.oauth2.client.provider.my_azure_ad.issuer-uri=<azure ad issuer>
Problem Description :
At startup time Spring Boot will try to create a clientRegistrationRepository Bean based on the configuration info in the properties file for each Authorization Server and try to establish rest connection with it.
If Connection to External Authorization Server failed, Application will fail to start.
Error :
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of
This is caused by : Caused by: java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of "<azure ad issuer>" at org.springframework.security.oauth2.client.registration.ClientRegistrations.getBuilder(ClientRegistrations.java:220) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1] at org.springframework.security.oauth2.client.registration.ClientRegistrations.fromIssuerLocation(ClientRegistrations.java:144) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1] at org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientPropertiesRegistrationAdapter.getBuilderFromIssuerIfPossible(OAuth2ClientPropertiesRegistrationAdapter.java:83) ~[spring-boot-autoconfigure-2.4.5.jar:2.6.3]
This is caused by Caused by: org.springframework.web.client.ResourceAccessException: I/O error on GET request for "< azure ad issuer >/.well-known/openid-configuration": sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:785) ~[spring-web-5.3.6.jar:5.3.6] at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:670) ~[spring-web-5.3.6.jar:5.3.6] at org.springframework.security.oauth2.client.registration.ClientRegistrations.lambda$oidc$0(ClientRegistrations.java:155) ~[spring-security-oauth2-client-5.6.1.jar:5.6.1]
This is a snippet of the method in org.springframework.security.oauth2.client.registration.ClientRegistrations that failed :
private static Supplier<ClientRegistration.Builder> oidc(URI issuer) {
// #formatter:off
URI uri = UriComponentsBuilder.fromUri(issuer)
.replacePath(issuer.getPath() + OIDC_METADATA_PATH)
.build(Collections.emptyMap());
// #formatter:on
return () -> {
RequestEntity<Void> request = RequestEntity.get(uri).build();
Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
OIDCProviderMetadata metadata = parse(configuration, OIDCProviderMetadata::parse);
ClientRegistration.Builder builder = withProviderConfiguration(metadata, issuer.toASCIIString())
.jwkSetUri(metadata.getJWKSetURI().toASCIIString());
if (metadata.getUserInfoEndpointURI() != null) {
builder.userInfoUri(metadata.getUserInfoEndpointURI().toASCIIString());
}
return builder;
};
}
ClientRegistrations.java can be found here : https://github.com/spring-projects/spring-security/blob/5.6.x/oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/registration/ClientRegistrations.java
The Line that failed is : Map<String, Object> configuration = rest.exchange(request, typeReference).getBody();
Disclaimer :
As you might noticed this is a Certificate Exception and can easily be recovered by importing the root CA for <azure ad issuer>
Question :
Is there a way to suppress this error and force Spring Boot App to start even if the configuration of one of the Authorization Servers failed to create the 'clientRegistrationRepository'?
I tried to use Spring Lazy Initialization at the level of the Controller which depends on 'clientRegistrationRepository' Bean, but even if the controller is not yet initialized 'WebMvcAutoConfiguration' will try to instantiate the 'clientRegistrationRepository'
Error : org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$EnableWebMvcConfiguration': Unsatisfied dependency expressed through method 'setConfigurers' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.OAuth2ClientConfiguration$OAuth2ClientWebMvcSecurityConfiguration': Unsatisfied dependency expressed through method 'setClientRegistrationRepository' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'clientRegistrationRepository' defined in class path resource [org/springframework/boot/autoconfigure/security/oauth2/client/servlet/OAuth2ClientRegistrationRepositoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository]: Factory method 'clientRegistrationRepository' threw exception; nested exception is java.lang.IllegalArgumentException: Unable to resolve Configuration with the provided Issuer of < azure ad issuer >
My goal here is to successfully start the Spring Boot Application even if the connection to one of the External Authorization Server is not working.

Spring Boot 2.0.4 - H2 Database - #SpringBootTest - Failing on Caused by: org.h2.jdbc.JdbcSQLException: Schema "classpath:db/schema.sql" not found

I have built an application with Spring Boot 2.0.4 and integrated with JPA.
Now I want to run some tests with h2 database, but I am unable to execute the Spring Boot tests with h2.
The exceptions are shown below:
Caused by: org.springframework.jdbc.datasource.init.UncategorizedScriptException: Failed to execute database script; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Schema "classpath:db/schema.sql" not found [90079-197]
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:58)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.runScripts(DataSourceInitializer.java:210)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.createSchema(DataSourceInitializer.java:104)
at org.springframework.boot.autoconfigure.jdbc.DataSourceInitializerInvoker.afterPropertiesSet(DataSourceInitializerInvoker.java:64)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1758)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1695)
... 74 more
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Failed to obtain JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Schema "classpath:db/schema.sql" not found [90079-197]
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:81)
at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:46)
... 79 more
Caused by: org.h2.jdbc.JdbcSQLException: Schema "classpath:db/schema.sql" not found [90079-197]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:357)
at org.h2.message.DbException.get(DbException.java:179)
at org.h2.message.DbException.get(DbException.java:155)
at org.h2.engine.Database.getSchema(Database.java:1808)
at org.h2.engine.Session.setCurrentSchemaName(Session.java:1317)
at org.h2.jdbc.JdbcConnection.setSchema(JdbcConnection.java:1989)
at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:423)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:370)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:194)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:460)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:534)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:112)
at org.springframework.jdbc.datasource.DataSourceUtils.fetchConnection(DataSourceUtils.java:151)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:115)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:78)
... 80 more
And my application-test.properties is:
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.jdbc-url=jdbc:h2:mem:test
spring.datasource.schema=classpath:db/schema.sql
spring.datasource.data=classpath:db/data.sql
spring.datasource.initialization-mode=always
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=none
logging.level.org.hibernate.SQL=debug
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
These exceptions happened when I executed schema.sql, but h2 want to execute this script in schema named "classpath:schema.sql" which is specified in spring.datasource.schema.
It is pretty clear by the exception Not Found that Spring boot is not able to find the schema.sql file.
Simply copy the src/main/resources/db/schema.sql to src/test/resources/db/schema.sql.
Your property should looks like this:
spring.datasource.schema=db/schema.sql
In the class DataSourceInitializer you can see how it is used
public boolean createSchema() {
List<Resource> scripts = getScripts("spring.datasource.schema",
this.properties.getSchema(), "schema");
if (!scripts.isEmpty()) {
if (!isEnabled()) {
logger.debug("Initialization disabled (not running DDL scripts)");
return false;
}
String username = this.properties.getSchemaUsername();
String password = this.properties.getSchemaPassword();
runScripts(scripts, username, password);
}
return !scripts.isEmpty();
}
the method getScripts add the classpath String:
private List<Resource> getScripts(String propertyName, List<String> resources,
String fallback) {
if (resources != null) {
return getResources(propertyName, resources, true);
}
String platform = this.properties.getPlatform();
List<String> fallbackResources = new ArrayList<>();
fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
fallbackResources.add("classpath*:" + fallback + ".sql");
return getResources(propertyName, fallbackResources, false);
}
So you don't have to set it.
Set spring.jpa.defer-datasource-initialization = true in your application.properties file.

Hikaricp Oracle connection issue

I have the following code to get connection to the oracle database. But using hikaricp I am getting the exception.
java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
Code:
private static HikariDataSource dataSource() {
final HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setMaximumPoolSize(100);
hikariDataSource.setMinimumIdle(10);
hikariDataSource.setDataSourceClassName("oracle.jdbc.pool.OracleDataSource");
Properties properties = new Properties();
properties.put("user", "user");
properties.put("password", "pass");
properties.put("databaseName", "XE");
properties.put("serverName", "192.168.21.13");
properties.put("portNumber", "1521");
hikariDataSource.setDataSourceProperties(properties);
//Additionally I am setting connection test query and max life time also
return hikariDataSource;
}
The complete stacktrace is
Exception in thread "main" java.lang.RuntimeException: Fail-fast during pool initialization
at com.zaxxer.hikari.pool.HikariPool.fillPool(HikariPool.java:499)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:162)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:113)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.zaxxer.hikari.HikariDataSource.getConnection(HikariDataSource.java:102)
at java.lang.reflect.Method.invoke(Method.java:597)
Caused by: java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
at oracle.jdbc.pool.OracleDataSource.makeURL(OracleDataSource.java:1277)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:185)
at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:157)
at com.zaxxer.hikari.pool.HikariPool.addConnection(HikariPool.java:418)
at com.zaxxer.hikari.pool.HikariPool.fillPool(HikariPool.java:498)
... 11 more
How do I establish successful pool? I am using oracle jar
http://download.oracle.com/otn/utilities_drivers/jdbc/111070/ojdbc6.jar
and the jdk is 1.6. Hikaricp version is 2.2.5 for java 6.
try to set the driver type to thin.
properties.put("driverType", "thin");

Webshpere datasource error:Unable to lookup JNDI name

I am developing an application with Hibernate and Websphere Application Server 8.0.
I have create a datasource in Websphere and it can connect with database successfully.
But from application I am getting following error:
SystemErr R Error creating Session: org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/OracleDS]
Following is the setup I have done:
Websphere datasource setup:
hibernate.cfg.xml
web.xml
When I try to get sessiofactory, it gives me error:
HibernateUtil.java:
try
{
Configuration configuration = new Configuration().configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
catch (HibernateException he)
{
System.err.println("Error creating Session: " + he);
throw new ExceptionInInitializerError(he);
}
Error:
java.lang.NullPointerException
at com.ibm.ws.webcontainer.metadata.WebComponentMetaDataImpl.getJavaNameSpace(WebComponentMetaDataImpl.java:143)
at com.ibm.ws.threadContext.JavaNameSpaceAccessorImpl.getJavaNameSpace(JavaNameSpaceAccessorImpl.java:79)
at com.ibm.ws.naming.java.javaURLContextFactory.createURLContextRoot(javaURLContextFactory.java:137)
at com.ibm.ws.naming.urlbase.UrlContextFactory.getObjectInstance(UrlContextFactory.java:101)
at org.apache.aries.jndi.URLContextProvider.getContext(URLContextProvider.java:43)
at org.apache.aries.jndi.DelegateContext.getURLContext(DelegateContext.java:252)
at org.apache.aries.jndi.DelegateContext.findContext(DelegateContext.java:214)
at org.apache.aries.jndi.DelegateContext.findContext(DelegateContext.java:207)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:432)
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1818)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1776)
at com.test.util.HibernateUtil.(HibernateUtil.java:25)
Error creating Session: org.hibernate.service.jndi.JndiException: Unable to lookup JNDI name [java:comp/env/jdbc/OracleDS]
Please let me know what I am missing.
I have applied more tries, now I am getting following error:
FFDC Exception:javax.naming.NamingException SourceId:com.ibm.ws.naming.java.javaURLContextFactory.createURLContextRoot ProbeId:142 Reporter:java.lang.Class#dfac0b43
javax.naming.NamingException: NMSV0308W: javaURLContextFactory cannot create a javaURLContext object because there is no java URL name space currently accessible from the executing thread.
at com.ibm.ws.naming.java.javaURLContextFactory.createURLContextRoot(javaURLContextFactory.java:170)
at com.ibm.ws.naming.urlbase.UrlContextFactory.getObjectInstance(UrlContextFactory.java:101)
at org.apache.aries.jndi.URLContextProvider.getContext(URLContextProvider.java:43)
at org.apache.aries.jndi.DelegateContext.getURLContext(DelegateContext.java:252)
at org.apache.aries.jndi.DelegateContext.findContext(DelegateContext.java:214)
at org.apache.aries.jndi.DelegateContext.findContext(DelegateContext.java:207)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:157)
at javax.naming.InitialContext.lookup(InitialContext.java:432)
at org.hibernate.service.jndi.internal.JndiServiceImpl.locate(JndiServiceImpl.java:65)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.configure(DatasourceConnectionProviderImpl.java:116)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1818)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1776)
at com.test.util.HibernateUtil.(HibernateUtil.java:25)
Did you create binding between you reference and JNDI name?
You can do it
either using admin console - Enterprise Application > ApplicationName > Resource references. then select reference and map it to the datasource JNDI name
or using binding file - you need to create ibm-web-bnd.xml file with the following contents:
<resource-ref name="jdbc/OracleDS" binding-name="jdbc/OracleDS" />
In WebSphere you don't need java:comp/env at the hibernate datasource.
So your hibernate.cfg.xml would look like this:
.
.
.
<!-- JNDI Datasource -->
<property name="hibernate.connection.datasource">jdbc/OracleDS</property>
.
.
.

Calling session Bean deployed on jboss 5.x from client side

I'm running JBoss 5.1 GA with JDK 1.6 on Linux and trying to call session bean(jar containing this session bean is deployed on jboss server), Now i want to call this session bean from client, but didnt work.
Java Code at client Side
public class CallingJbossSessionBeanFromClient {
/**
* #param args
* #throws Exception
*/
public static void main(String[] args) throws Exception
{
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
p.put(Context.PROVIDER_URL, "jnp://182.158.93.41:8080");
Context context = new InitialContext(p);
System.out.println("Successfully Lookup and going to call SessionBean Function deployed on JBoss-5.1.0 Server");
SlsSessiongRemote remote=(SlsSessionRemote) context.lookup("SlsSessionBean/remote");
//SlsSessionBean/remote is RemoteBinding of session Bean
System.out.println("Called");
}
}
where 'SlsSessionBean/remote' is remote binding of session bean deployed on jboss server.
#Stateless
#RemoteBinding(jndiBinding="SlsSessionBean/remote")
but end up with following error
Exception in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: org.jnp.interfaces.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:20)
Caused by: java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:46)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:654)
... 4 more
After seeing above error i added jbossjmx-ant.jar in the classpath of 'CallingJbossSessionBeanFromClient' class and got following error
Exception in thread "main" java.lang.NoClassDefFoundError: org/jboss/logging/Logger
at org.jnp.interfaces.NamingContext.<clinit>(NamingContext.java:181)
at org.jnp.interfaces.NamingContextFactory.getInitialContext(NamingContextFactory.java:55)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:20)
Caused by: java.lang.ClassNotFoundException: org.jboss.logging.Logger
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:303)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316)
... 7 more
After seeing above error i added jboss-logging-spi.jar in the classpath of 'CallingJbossSessionBeanFromClient' class and got following error
Exception in thread "main" javax.naming.CommunicationException: Could not obtain connection to any of these urls: 182.158.93.41:8080 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to retrieve stub from server /182.158.93.41:8080 [Root exception is java.io.EOFException]]
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1763)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:693)
at org.jnp.interfaces.NamingContext.lookup(NamingContext.java:686)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at CallingJbossSessionBeanFromClient.main(CallingJbossSessionBeanFromClient.java:22)
Caused by: javax.naming.CommunicationException: Failed to retrieve stub from server /182.158.93.41:8080 [Root exception is java.io.EOFException]
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:327)
at org.jnp.interfaces.NamingContext.checkRef(NamingContext.java:1734)
... 4 more
Caused by: java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2281)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2750)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:780)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:280)
at org.jnp.interfaces.NamingContext.getServer(NamingContext.java:312)
... 5 more
Plz tell me, am i on the right way to call sesion bean from client java class?
I have spent hours looking for solution on Google. However I cannot seem to find anything that holds the hand..try to be more clear, i'm in lack of ideas in this problem, even it sounds like a classic
Plz suggest solution
The solution to this problem is to open the JMX-Console and click on the service=Naming to view the MBean view of the Naming service. Check if the port used is still 1099.....
Changed the URL to jnp://182.158.93.41:1299, the client could communicate with the EJB.
If you are running over JBoss AS 5.x
Here is RMI based JNDI description.
RMI-Port: default -1099 / If dynamic port changed to ports-01 Then Port is 1199
Now, Remaining Things are OK, Modify code ass below
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
p.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
p.put(Context.PROVIDER_URL, "jnp://182.158.93.41:1199");
Another Point is case of accessing
SlsSessiongRemote remote=(SlsSessionRemote) context.lookup("SlsSessionBean/remote");
if - #Stateless(name="SlsSessionBean")
Then Remote JNDI- [SlsSessionBean/remote] and Local JNDI - [SlsSessionBean/local]
if - #Stateless(name="SlsSessionBean", mappedName="SlsSessionBeanGlobal")
Then Remote JNDI- [SlsSessionBeanGlobal] and Local JNDI - [SlsSessionBean/local]

Resources