I am using the Spring Data Cassandra project v1.3.0 am unable to configure SSL for my Cassandra cluster (v2.0.17). The Sprint Data Cassandra documentation says it supports Cassandra 2.X using the DataStax Java Driver (2.0.X) so there shouldn't be an issue there. Here is my Java cassandra configuration that initializes the cassandra cluster bean:
#Autowired
private Environment env;
#Bean
public CassandraClusterFactoryBean cluster() {
SSLContext context = null;
try {
context = getSSLContext(
env.getProperty("cassandra.connection.ssl.trustStorePath"),
env.getProperty("cassandra.connection.ssl.trustStorePassword"),
env.getProperty("cassandra.connection.ssl.keyStorePath"),
env.getProperty("cassandra.connection.ssl.keyStorePassword"));
} catch (Exception ex) {
log.warn("Error setting SSL context for Cassandra.");
}
// Default cipher suites supported by C*
String[] cipherSuites = { "TLS_RSA_WITH_AES_128_CBC_SHA",
"TLS_RSA_WITH_AES_256_CBC_SHA" };
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(env.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(env.getProperty("cassandra.port")));
cluster.setSslOptions(new SSLOptions(context, cipherSuites));
cluster.setSslEnabled(true);
return cluster;
}
#Bean
public CassandraMappingContext mappingContext() {
return new BasicCassandraMappingContext();
}
#Bean
public CassandraConverter converter() {
return new MappingCassandraConverter(mappingContext());
}
#Bean
public CassandraSessionFactoryBean session() throws Exception {
CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
session.setCluster(cluster().getObject());
session.setKeyspaceName(env.getProperty("cassandra.keyspace"));
session.setConverter(converter());
session.setSchemaAction(SchemaAction.NONE);
return session;
}
#Bean
public CassandraOperations cassandraTemplate() throws Exception {
return new CassandraTemplate(session().getObject());
}
private static SSLContext getSSLContext(String truststorePath,
String truststorePassword, String keystorePath,
String keystorePassword) throws Exception {
FileInputStream tsf = new FileInputStream(truststorePath);
FileInputStream ksf = new FileInputStream(keystorePath);
SSLContext ctx = SSLContext.getInstance("SSL");
KeyStore ts = KeyStore.getInstance("JKS");
ts.load(tsf, truststorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(ksf, keystorePassword.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(ks, keystorePassword.toCharArray());
ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(),
new SecureRandom());
return ctx;
}
I have verified the environment properties to set the SSL context are being populated properly and are the same keystore and truststore being used in the cassandra configuration file. Below is my cassandra configuration regarding enabling client to node encryption:
server_encryption_options:
internode_encryption: all
keystore: /usr/share/ssl/cassandra_client.jks
keystore_password: cassandra
truststore: /usr/share/ssl/cassandra_client_trust.jks
truststore_password: cassandra
# More advanced defaults below:
# protocol: TLS
# algorithm: SunX509
store_type: JKS
cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA] #,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
# require_client_auth: true
# enable or disable client/server encryption.
client_encryption_options:
enabled: true
keystore: /usr/share/ssl/cassandra_client.jks
keystore_password: cassandra
require_client_auth: true
# Set trustore and truststore_password if require_client_auth is true
truststore: /usr/share/ssl/cassandra_client_trust.jks
truststore_password: cassandra
# More advanced defaults below:
# protocol: TLS
# algorithm: SunX509
store_type: JKS
cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA] #,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]
When launching my client application I get the following error when cassandra cluster is being initialized:
17:02:39,330 WARN [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 58) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.cassandra.core.CassandraOperations com.cloudistics.cldtx.mwc.service.CassandraServiceImpl.cassandraOperations; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraTemplate' defined in com.cloudistics.cldtx.mwc.conn.CassandraConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.core.CassandraOperations]: Factory method 'cassandraTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in com.cloudistics.cldtx.mwc.conn.CassandraConfig: Invocation of init method failed; nested exception is com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /127.0.0.1:9042 (com.datastax.driver.core.ConnectionException: [/127.0.0.1:9042] Unexpected error during transport initialization (com.datastax.driver.core.OperationTimedOutException: [/127.0.0.1:9042] Operation timed out)))17:02:39,330 WARN [org.springframework.web.context.support.XmlWebApplicationContext] (ServerService Thread Pool -- 58) Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.springframework.data.cassandra.core.CassandraOperations com.cloudistics.cldtx.mwc.service.CassandraServiceImpl.cassandraOperations; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cassandraTemplate' defined in com.cloudistics.cldtx.mwc.conn.CassandraConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.cassandra.core.CassandraOperations]: Factory method 'cassandraTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'session' defined in com.cloudistics.cldtx.mwc.conn.CassandraConfig: Invocation of init method failed; nested exception is com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /127.0.0.1:9042 (com.datastax.driver.core.ConnectionException: [/127.0.0.1:9042] Unexpected error during transport initialization (com.datastax.driver.core.OperationTimedOutException: [/127.0.0.1:9042] Operation timed out)))
If anybody has any insight into this it would be greatly appreciated. I followed these instructions on Datastax to prepare the server certificates and enable client-to-node encryption.
I could able to do this with following code. Hope this helps.
cassandra.properties
# KeyStore Path
cassandra.cassks=classpath:cass.keystore.p12
# KeyStore Password
cassandra.casskspass=defkeypass
# KeyStore Type
cassandra.casskstype=pkcs12
# TrustStore Path
cassandra.cassts=classpath:cass.truststore.p12
# TrustStore Password
cassandra.casstspass=deftrustpass
# TrustStore Type
cassandra.casststype=pkcs12
CassandraProperties.java
#Configuration
#ConfigurationProperties("cassandra")
#PropertySource(value = "${classpath:conf/cassandra.properties}")
#Validated
#Data
public class CassandraProperties {
#NotNull
private Boolean ssl;
#NotNull
private String sslver;
private Resource cassks;
private String casskspass;
private String casskstype;
private Resource cassts;
private String casstspass;
private String casststype;
}
CassandraConfig.java
public class CassandraConfig extends AbstractCassandraConfiguration {
#Autowired
private CassandraProperties cassandraProp;
#Bean
public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(cassandraProp.getContactpoints());
cluster.setPort(cassandraProp.getPort());
if (true == cassandraProp.isSSEnabled()) {
File KeyStoreFile = null;
File TrustStoreFile = null;
InputStream keyStoreIS = null;
InputStream tustStoreIS = null;
KeyStore keyStore = null;
KeyStore trustStore = null;
TrustManagerFactory tmf = null;
KeyManagerFactory kmf = null;
SSLContext sslContext = null;
RemoteEndpointAwareJdkSSLOptions sslOptions = null;
try {
KeyStoreFile = cassandraProp.getCassks().getFile();
keyStoreIS = new FileInputStream(KeyStoreFile);
keyStore = KeyStore.getInstance(cassandraProp.getCasskstype());
keyStore.load(keyStoreIS, cassandraProp.getCasskspass().toCharArray());
TrustStoreFile = cassandraProp.getCassts().getFile();
tustStoreIS = new FileInputStream(TrustStoreFile);
trustStore = KeyStore.getInstance(cassandraProp.getCasststype());
trustStore.load(tustStoreIS, cassandraProp.getCasstspass().toCharArray());
tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(trustStore);
kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, cassandraProp.getCasskspass().toCharArray());
sslContext = SSLContext.getInstance(cassandraProp.getSslver());
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
sslOptions = new RemoteEndpointAwareJdkSSLOptions.Builder().withSSLContext(sslContext).build();
} catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
| KeyManagementException | UnrecoverableKeyException e) {
e.printStackTrace();
}
cluster.setSslEnabled(true);
cluster.setSslOptions(sslOptions);
}
return cluster;
}
}
Related
I was working with 8.0 version of Websphere application server. I was trying to get SSLSocketFactory from JSSEHelper. Although
I have successfuly got the SSLSocketFactory
I have successfuly got the SSLSocket from SSLSocketFactory
I have successfuly established the secure connection,
but cipher suites provided in ClientHello message corresponded neither to
CellDefault SSL Settings/NodeDefault SSL Settings/NodeDefaultnor
nor to my own custom SSL configuration.
The solution to this problem was to avoid retrieving SSLSocketFactory from JSSEHelper. Instead of using JSSEHelper, I should use static method getDefault() from SSLSocketFactory class in whis way:
public SSLSocket getSslSocket(Properties sslProps) {
SSLSocketFactory factory = SSLSocketFactory.getDefault();
SSLSocket socket = null;
try {
socket = (SSLSocket) factory.createSocket();
} catch (IOException e) {
e.printStackTrace();
}
return socket;
}
More details can be found here:
Could anybody please clarify why this statement:
slSocketFactory = jsseHelper.getSSLSocketFactory(sslMap, sslProps)
returns incorrect 'SSL socket factory' while this statement
SSLSocketFactory.getDefault()
returns the correct one?
Moreover, in what case should I use factory retrieved from these statements respectively?
SSLSocketFactory.getDefault();
jsseHelper.getSSLSocketFactory(sslMap, sslProps)
getSSLSocketFactory(java.lang.String sslAliasName, java.util.Map connectionInfo, SSLConfigChangeListener listener)
Thank you very much
Although it is not intuitive, statement:
SSLSocketFactory factory = SSLSocketFactory.getDefault();
returns the WebSphere custom SSLSocketFactory.
Then you can enforce SSL-configuration on thread in this way:
Properties sslProperties = getProperties();
jsseHelper.setSSLPropertiesOnThread(sslProperties);
SSLSocket socket = getSslSocket();
CommonIO.writeToSocket(socket, "127.0.0.1", 1234);
jsseHelper.setSSLPropertiesOnThread(null);
Although JSSEHelper.getSSLSocketFactory(sslMap, sslConfig_XYZ) returns also factory but their sockets ignore cipher suites encapsulated in SSL-configuration sslConfig_XYZ.
On the other hand, if you want to enforce only
protocol
keystore
truststore
this method:
JSSEHelper.getSSLSocketFactory(sslMap, sslConfig_XYZ)
is sufficient enough.
We are running drools 6.1.0 on Weblogic 12.1.2 as a stateless EJB 3.0 Bean. The bean returns the following exception when there is more load on the server during the initialization process when it is creating new instances in the pool.
EJB Exception: : java.lang.RuntimeException: java.io.NotSerializableException: org.drools.core.common.DefaultFactHandle
at org.drools.core.util.ClassUtils.deepClone(ClassUtils.java:514)
at org.drools.core.definitions.impl.KnowledgePackageImpl.deepCloneIfAlreadyInUse(Kn owledgePackageImpl.java:770)
at org.drools.core.definitions.impl.KnowledgePackageImpl.deepCloneIfAlreadyInUse(KnowledgePackageImpl.java:66)
at org.drools.core.impl.KnowledgeBaseImpl.addPackages(KnowledgeBaseImpl.java:722)
at org.drools.core.impl.KnowledgeBaseImpl.addKnowledgePackages(KnowledgeBaseImpl.java:266)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.createKieBase(KieContainerImpl.java:412)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.getKieBase(KieContainerImpl.java:346)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:498)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:443)
at org.drools.compiler.kie.builder.impl.KieContainerImpl.newKieSession(KieContainerImpl.java:425)
The code we have to initialize a new stateful session is as below:
protected KieSession kieSession= null;
protected ReleaseId releaseId = null; //fetched by logic to identify the release id>
if(kieSession != null){
kieSession.dispose();
kieSession = null;
}
KieServices kServices = KieServices.Factory.get();
KieContainer container = kServices.newKieContainer(this.releaseId);
kieSession = container.newKieSession();
This is happening in the constructor of the Stateless Bean.
Could you help us with any suggestions on resolving this issue?
I have setup a spring boot (v 1.1.9) application to deploy as a WAR file. And I'm trying to integrate this web application with an existing data service module (added as a maven dependency).
Environment trying to deploy: WebSphere Application Server 8.5.5.4
The issue I'm facing is an application start-up failure when try to look-up a JNDI dataSource (jdbc/fileUploadDS) as below within the dependent data service module.
#Configuration
#Profile("prod")
public class JndiDataConfig implements DataConfig {
#Bean
public DataSource dataSource() throws NamingException {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/fileUploadDS");
}
}
My Spring Boot configuration:
#Configuration
#ComponentScan(basePackages = { "au.com.aiaa.fileupload.data.*", "demo" })
#EnableAutoConfiguration(exclude = { HibernateJpaAutoConfiguration.class, DataSourceAutoConfiguration.class })
public class SampleApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(applicationClass, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(applicationClass);
}
private static Class<SampleApplication> applicationClass = SampleApplication.class;
#Bean
public static Properties fileUploadJndiProperties() throws NamingException {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("props/FileUploadProperties");
jndiFactoryBean.setExpectedType(Properties.class);
jndiFactoryBean.setLookupOnStartup(true);
jndiFactoryBean.afterPropertiesSet();
return (Properties) jndiFactoryBean.getObject();
}
}
Note that I'm able to lookup props/FileUploadProperties successfully. But failing to do the same for a datasource.
My doubt is it is trying to load a EmbeddedWebApplicationContext which is not what I want.
The stack trace is:
Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:301)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1186)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:706)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at **org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:109)**
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:691)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
at org.springframework.boot.builder.SpringApplicationBuilder.run(SpringApplicationBuilder.java:142)
at org.springframework.boot.context.web.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:89)
at org.springframework.boot.context.web.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:51)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:175)
..................
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Factory method [public javax.sql.DataSource au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource() throws javax.naming.NamingException] threw exception; nested exception is **javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".**
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:188)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:586)
... 132 common frames omitted
Caused by: javax.naming.NameNotFoundException: Name comp/env/jdbc not found in context "java:".
at com.ibm.ws.naming.ipbase.NameSpace.getParentCtxInternal(NameSpace.java:1970)
at com.ibm.ws.naming.ipbase.NameSpace.retrieveBinding(NameSpace.java:1377)
at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1220)
at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1142)
at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)
at javax.naming.InitialContext.lookup(InitialContext.java:436)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig.dataSource(JndiDataConfig.java:41)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.CGLIB$dataSource$0(<generated>)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe$$FastClassBySpringCGLIB$$3c9e0518.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:312)
at au.com.aiaa.fileupload.data.dao.configuration.JndiDataConfig$$EnhancerBySpringCGLIB$$8001dbbe.dataSource(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:60)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:611)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:166)
What am I missing here? Even when I try to explicitly define the dataSource bean method in SampleApplication.java like below it fails with the same error.
#Bean
public static DataSource dataSource() throws NamingException {
JndiObjectFactoryBean jndiFactoryBean = new JndiObjectFactoryBean();
jndiFactoryBean.setJndiName("java:comp/env/jdbc/fileUploadDS");
jndiFactoryBean.setExpectedType(DataSource.class);
jndiFactoryBean.setLookupOnStartup(true);
jndiFactoryBean.setResourceRef(true);
jndiFactoryBean.afterPropertiesSet();
return (DataSource) jndiFactoryBean.getObject();
}
I referred this and it says we need to set enableNaming() on servlet container? Can I do something similar for non-embedded web application context? Or is it purely a WAS 8.5 issue??
You need to have resource reference with jdbc/fileUploadDS name in your web.xml. And make sure it is bound to actual datasource name during installation or via ibm-web-bnd.xml file.
Definition in web.xml:
<resource-ref>
<description />
<res-ref-name>jdbc/fileUploadDS</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
If you dont want to use web.xml, then in normal Java EE app you could just add in web component (servlet, filter) the following class annotation:
#Resource(name="jdbc/fileUploadDS", type=javax.sql.DataSource.class, lookup="jdbc/fileUploadDS")
but I'm not Spring-boot expert, so don't know, if it will work or is possible there.
I am able to connect my Spring-Boot application (deployed in Websphere Application Server 9) to WAS datasource.
The following code worked for me, for connecting to DataSource:
#Bean(name = "WASDataSource")
public DataSource WASDataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("DSNAME");
}
#Bean(name = "WASDataSourceJdbcTemplate")
public JdbcTemplate jdbcTemplate_WASDS(#Qualifier("WASDataSource")
DataSource dsDB2) {
return new JdbcTemplate(dsDB2);
}
Note: The name of Datasource "DSNAME" is the name which appears on the UI of Websphere console.
You can see that via -> Select Resources > JDBC > Data Sources.
Then I created jdbc template:
#Autowired
#Qualifier("WASDataSourceJdbcTemplate")
private JdbcTemplate db2WASTemplate;`
And running query using the query method works fine :
db2WASTemplate.query()
I did not create any Web.xml or ibm-web-bnd.xml files
I just configured spring boot with my custom datasource as follows:
#Bean
#ConfigurationProperties("spring.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
and inside the application.properties file I defined all datasource settings as usual
spring.datasource.driver-class-name= ***
spring.datasource.url= ***
spring.datasource.username= ***
spring.datasource.password= ***
spring.datasource.jndi-name=jdbc/myDB
It works nicely with #SpringBootApplication with all other default settings
I am facing the same problem. I don't know how to define tag in spring boot since there is no web.xml file in the spring boot.
So far what I came to know that we have to define it in the application file from where we start our spring application. I think we need to use this method to set the Datasource:
#Bean(destroyMethod="")
#ConfigurationProperties(prefix="datasource.mine")
public DataSource dataSource() throws Exception {
JndiDataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
return dataSourceLookup.getDataSource("java:jdbc/configurationFile");
}
One more to the list of the mysterious "peer not authenticated".
I have an apache httpclient using 4.2 lib. I have explicitly set to trust all certificates in the code.
I have a Tomcat server (JRE 1.7U45), serving the requests on Linux. The server has a self signed certificate.
Client side code:
private DefaultHttpClient getHttpsClient() {
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
final SSLSocketFactory sf;
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
}
} }, new SecureRandom());
sf = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme(url.getScheme(), url.getPort(), sf));
ClientConnectionManager cm = new BasicClientConnectionManager(
registry);
return new MyDefaultHttpClient(cm);
} catch (Exception e) {
return new MyDefaultHttpClient();
}
}
This error is only seen intermittently on "Solaris 5.10" (32 bit JRE 1.7.0u45) clients talking to the server.
Sometime, the request on the same box go thru fine, but at other times, this just throws "Peer Not Authenticate"
I have other flavors of OS clients, where the call is going thru just fine.
Would any of have any suggestions/pointers to look into this issue?
More Update:
Ran the ssl debug on the server and we see that intermittently, it throws
http-bio-8443-exec-7, handling exception: javax.net.ssl.SSLHandshakeException: Invalid Padding length: 105
http-bio-8443-exec-7, IOException in getSession(): javax.net.ssl.SSLHandshakeException: Invalid Padding length: 105
This was due the following bug in JRE 1.7 http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8013059
Also, the apache httpclient 4.2 added to the confusion, where it masking the actual exception thrown instead throwing the generic "Peer not authenticated"
In the server.xml of tom-cat, for connector element, add the cipher attribute with a list of non-DH ciphers
E.g.
ciphers="SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA,SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA"
This solved the issue.
Hope this is useful to someone.
Thanks
I have a class that acts as standalone client for Glassfish V3 JMS queue. This class works fine from my localhost, i.e. both glassfish server and the standalone client are on my local PC.
Now I need to install this client on a Linux machine. Glassfish V3 is already running on this Linux machine. I have added appserv-rt.jar from the glassfish installation directory and added it in the directory of standlaone client and set the classpath. But I keep getting this error:
javax.naming.NoInitialContextException: Cannot instantiate class: com.sun.enterprise.naming.SerialInitContextFactory [Root exception is java.lang.ClassNotFoundException: com.sun.enterprise.naming.SerialInitContextFactory]
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 com.cisco.zbl.controller.ZblBulkUploadThread.run(ZblBulkUploadThread.java:55)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ClassNotFoundException: com.sun.enterprise.naming.SerialInitContextFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
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)
... 5 more
Here is my Java code:
public class ZblBulkUploadThread implements Runnable,MessageListener{
private static final Category log = Category.getInstance(ZblBulkUploadThread.class) ;
private Queue queue;
public void run()
{
try
{
ZblConfig zblConfig = new ZblConfig() ;
InitialContext jndiContext = null;
MessageConsumer messageConsumer=null;
Properties props = new Properties();
props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory");
props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming");
props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl");
jndiContext = new InitialContext(props);
log.debug(zblConfig.getProperty("JMSConnectionFactoryName")) ;
//System.setProperty("java.naming.factory.initial","com.sun.jndi.ldap.LdapCtxFactory");
ConnectionFactory connectionFactory = (ConnectionFactory)jndiContext.lookup(zblConfig.getProperty("JMSConnectionFactoryName"));
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
queue = (Queue)jndiContext.lookup(zblConfig.getProperty("JMSQueueName")) ;
messageConsumer = session.createConsumer(queue);
connection.start();
while(true)
{
Message message = messageConsumer.receive() ;
ObjectMessage om = ((ObjectMessage)message) ;
try
{
RedirectFile file = (RedirectFile)om.getObject() ;
log.debug("filePath "+file.getFilePath()) ;
log.debug(" userName "+file.getUserName()) ;
log.debug(" mode is "+file.getMode()) ;
processMessage(file,zblConfig) ;
}
catch(Exception ex)
{
log.error("ERROR "+ex.getMessage()) ;
ex.printStackTrace() ;
}
}
}
catch(Exception ex)
{
ex.printStackTrace() ;
log.error("Error "+ex.getMessage()) ;
}
}
The error comes at this line: jndiContext = new InitialContext(props);
It does not make any difference if I use the no-arg constructor of InitialContext.
Here is my unix shell script that invokes this java program (Standlaone client):
APP_HOME=/local/scripts/apps/bulkUpload;
CLASSPATH=.:$APP_HOME/lib/gf-client.jar:$APP_HOME/lib/zbl.jar:$APP_HOME/lib/log4j- 1.2.4.jar:$APP_HOME/lib/javaee.jar:$APP_HOME/lib/poi-3.8-beta5-20111217.jar:$APP_HOME/lib/poi-examples-3.8-beta5-20111217:$APP_HOME/lib/poi-excelant-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-schemas-3.8-beta5-20111217:$APP_HOME/lib/poi-scratchpad-3.8-beta5-20111217:$APP_HOME/lib/appserv-rt.jar:
echo "CLASSPATH=$CLASSPATH";
export APP_HOME;
export CLASSPATH;
cd $APP_HOME;
#javac -d . ZblBulkUploadThread.java
java -cp $CLASSPATH -Dzbl.properties=zbl-stage.properties -Djava.naming.factory.initial=com.sun.enterprise.naming.SerialInitContextFactory com.cisco.zbl.controller.ZblBulkUploadThread
Please help me - I have been stuck on this problem for a long time.
do a which java command and see if jdk is being picked up correctly. I doubt that linux is picking gc4j
update:
change this line
CLASSPATH=.:$APP_HOME/lib/gf-client.jar:$APP_HOME/lib/zbl.jar:$APP_HOME/lib/log4j- 1.2.4.jar:$APP_HOME/lib/javaee.jar:$APP_HOME/lib/poi-3.8-beta5-20111217.jar:$APP_HOME/lib/poi-examples-3.8-beta5-20111217:$APP_HOME/lib/poi-excelant-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-schemas-3.8-beta5-20111217:$APP_HOME/lib/poi-scratchpad-3.8-beta5-20111217:$APP_HOME/lib/appserv-rt.jar: to
CLASSPATH=.:$APP_HOME/lib/gf-client.jar:$APP_HOME/lib/zbl.jar:$APP_HOME/lib/log4j- 1.2.4.jar:$APP_HOME/lib/javaee.jar:$APP_HOME/lib/poi-3.8-beta5-20111217.jar:$APP_HOME/lib/poi-examples-3.8-beta5-20111217:$APP_HOME/lib/poi-excelant-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-3.8-beta5-20111217:$APP_HOME/lib/poi-ooxml-schemas-3.8-beta5-20111217:$APP_HOME/lib/poi-scratchpad-3.8-beta5-20111217:$APP_HOME/lib/appserv-rt.jar